file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/vesper/IVesperPool.sol";
import "./interfaces/aave/IAave.sol";
import "./interfaces/dydx/ISoloMargin.sol";
/**
* @title FlashLoanHelper:: This contract does all heavy lifting to get flash loan via Aave and DyDx.
* @dev End user has to override _flashLoanLogic() function to perform logic after flash loan is done.
* Also needs to approve token to aave and dydx via _approveToken function.
* 2 utility internal functions are also provided to activate/deactivate flash loan providers.
* Utility function are provided as internal so that end user can choose controlled access via public functions.
*/
abstract contract FlashLoanHelper {
using SafeERC20 for IERC20;
AaveLendingPoolAddressesProvider internal aaveAddressesProvider;
address internal constant SOLO = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
uint256 public dyDxMarketId;
bytes32 private constant AAVE_PROVIDER_ID = 0x0100000000000000000000000000000000000000000000000000000000000000;
bool public isAaveActive = false;
bool public isDyDxActive = false;
constructor(address _aaveAddressesProvider) {
require(_aaveAddressesProvider != address(0), "invalid-aave-provider");
aaveAddressesProvider = AaveLendingPoolAddressesProvider(_aaveAddressesProvider);
}
function _updateAaveStatus(bool _status) internal {
isAaveActive = _status;
}
function _updateDyDxStatus(bool _status, address _token) internal {
if (_status) {
dyDxMarketId = _getMarketIdFromTokenAddress(SOLO, _token);
}
isDyDxActive = _status;
}
/// @notice Approve all required tokens for flash loan
function _approveToken(address _token, uint256 _amount) internal {
IERC20(_token).safeApprove(SOLO, _amount);
IERC20(_token).safeApprove(aaveAddressesProvider.getLendingPool(), _amount);
}
/// @dev Override this function to execute logic which uses flash loan amount
function _flashLoanLogic(bytes memory _data, uint256 _repayAmount) internal virtual;
/***************************** Aave flash loan functions ***********************************/
bool private awaitingFlash = false;
/**
* @notice This is entry point for Aave flash loan
* @param _token Token for which we are taking flash loan
* @param _amountDesired Flash loan amount
* @param _data This will be passed downstream for processing. It can be empty.
*/
function _doAaveFlashLoan(
address _token,
uint256 _amountDesired,
bytes memory _data
) internal returns (uint256 _amount) {
require(isAaveActive, "aave-flash-loan-is-not-active");
AaveLendingPool _aaveLendingPool = AaveLendingPool(aaveAddressesProvider.getLendingPool());
AaveProtocolDataProvider _aaveProtocolDataProvider =
AaveProtocolDataProvider(aaveAddressesProvider.getAddress(AAVE_PROVIDER_ID));
// Check token liquidity in Aave
(uint256 _availableLiquidity, , , , , , , , , ) = _aaveProtocolDataProvider.getReserveData(_token);
if (_amountDesired > _availableLiquidity) {
_amountDesired = _availableLiquidity;
}
address[] memory assets = new address[](1);
assets[0] = _token;
uint256[] memory amounts = new uint256[](1);
amounts[0] = _amountDesired;
// 0 = no debt, 1 = stable, 2 = variable
uint256[] memory modes = new uint256[](1);
modes[0] = 0;
// Anyone can call aave flash loan to us, so we need some protection
awaitingFlash = true;
// function params: receiver, assets, amounts, modes, onBehalfOf, data, referralCode
_aaveLendingPool.flashLoan(address(this), assets, amounts, modes, address(this), _data, 0);
_amount = _amountDesired;
awaitingFlash = false;
}
/// @dev Aave will call this function after doing flash loan
function executeOperation(
address[] calldata, /*_assets*/
uint256[] calldata _amounts,
uint256[] calldata _premiums,
address _initiator,
bytes calldata _data
) external returns (bool) {
require(msg.sender == aaveAddressesProvider.getLendingPool(), "!aave-pool");
require(awaitingFlash, "invalid-flash-loan");
require(_initiator == address(this), "invalid-initiator");
// Flash loan amount + flash loan fee
uint256 _repayAmount = _amounts[0] + _premiums[0];
_flashLoanLogic(_data, _repayAmount);
return true;
}
/***************************** Aave flash loan functions ends ***********************************/
/***************************** DyDx flash loan functions ***************************************/
/**
* @notice This is entry point for DyDx flash loan
* @param _token Token for which we are taking flash loan
* @param _amountDesired Flash loan amount
* @param _data This will be passed downstream for processing. It can be empty.
*/
function _doDyDxFlashLoan(
address _token,
uint256 _amountDesired,
bytes memory _data
) internal returns (uint256 _amount) {
require(isDyDxActive, "dydx-flash-loan-is-not-active");
// Check token liquidity in DyDx
uint256 amountInSolo = IERC20(_token).balanceOf(SOLO);
if (_amountDesired > amountInSolo) {
_amountDesired = amountInSolo;
}
// Repay amount, amount with fee, can be 2 wei higher. Consider 2 wei as fee
uint256 repayAmount = _amountDesired + 2;
// Encode custom data for callFunction
bytes memory _callData = abi.encode(_data, repayAmount);
// 1. Withdraw _token
// 2. Call callFunction(...) which will call loanLogic
// 3. Deposit _token back
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(dyDxMarketId, _amountDesired);
operations[1] = _getCallAction(_callData);
operations[2] = _getDepositAction(dyDxMarketId, repayAmount);
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
ISoloMargin(SOLO).operate(accountInfos, operations);
_amount = _amountDesired;
}
/// @dev DyDx calls this function after doing flash loan
function callFunction(
address _sender,
Account.Info memory, /* _account */
bytes memory _callData
) external {
(bytes memory _data, uint256 _repayAmount) = abi.decode(_callData, (bytes, uint256));
require(msg.sender == SOLO, "!solo");
require(_sender == address(this), "invalid-initiator");
_flashLoanLogic(_data, _repayAmount);
}
/********************************* DyDx helper functions *********************************/
function _getAccountInfo() internal view returns (Account.Info memory) {
return Account.Info({owner: address(this), number: 1});
}
function _getMarketIdFromTokenAddress(address _solo, address token) internal view returns (uint256) {
ISoloMargin solo = ISoloMargin(_solo);
uint256 numMarkets = solo.getNumMarkets();
address curToken;
for (uint256 i = 0; i < numMarkets; i++) {
curToken = solo.getMarketTokenAddress(i);
if (curToken == token) {
return i;
}
}
revert("no-marketId-found-for-token");
}
function _getWithdrawAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
/***************************** DyDx flash loan functions end *****************************/
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface AaveLendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
function getAddress(bytes32 id) external view returns (address);
}
interface AToken is IERC20 {
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view returns (address);
}
interface AaveIncentivesController {
function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256);
function claimRewards(
address[] calldata assets,
uint256 amount,
address to
) external returns (uint256);
}
interface AaveLendingPool {
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
}
interface AaveProtocolDataProvider {
function getReserveTokensAddresses(address asset)
external
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
function getReserveData(address asset)
external
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
}
//solhint-disable func-name-mixedcase
interface StakedAave is IERC20 {
function claimRewards(address to, uint256 amount) external;
function cooldown() external;
function stake(address onBehalfOf, uint256 amount) external;
function redeem(address to, uint256 amount) external;
function getTotalRewardsBalance(address staker) external view returns (uint256);
function stakersCooldowns(address staker) external view returns (uint256);
function COOLDOWN_SECONDS() external view returns (uint256);
function UNSTAKE_WINDOW() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
/* solhint-disable func-name-mixedcase */
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
interface ISwapManager {
event OracleCreated(address indexed _sender, address indexed _newOracle, uint256 _period);
function N_DEX() external view returns (uint256);
function ROUTERS(uint256 i) external view returns (IUniswapV2Router02);
function bestOutputFixedInput(
address _from,
address _to,
uint256 _amountIn
)
external
view
returns (
address[] memory path,
uint256 amountOut,
uint256 rIdx
);
function bestPathFixedInput(
address _from,
address _to,
uint256 _amountIn,
uint256 _i
) external view returns (address[] memory path, uint256 amountOut);
function bestInputFixedOutput(
address _from,
address _to,
uint256 _amountOut
)
external
view
returns (
address[] memory path,
uint256 amountIn,
uint256 rIdx
);
function bestPathFixedOutput(
address _from,
address _to,
uint256 _amountOut,
uint256 _i
) external view returns (address[] memory path, uint256 amountIn);
function safeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function unsafeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function safeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function unsafeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function comparePathsFixedInput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountIn,
uint256 _i
) external view returns (address[] memory path, uint256 amountOut);
function comparePathsFixedOutput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountOut,
uint256 _i
) external view returns (address[] memory path, uint256 amountIn);
function ours(address a) external view returns (bool);
function oracleCount() external view returns (uint256);
function oracleAt(uint256 idx) external view returns (address);
function getOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external view returns (address);
function createOrUpdateOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external returns (address oracleAddr);
function consultForFree(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
) external view returns (uint256 amountOut, uint256 lastUpdatedAt);
/// get the data we want and pay the gas to update
function consult(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
)
external
returns (
uint256 amountOut,
uint256 lastUpdatedAt,
bool updated
);
function updateOracles() external returns (uint256 updated, uint256 expected);
function updateOracles(address[] memory _oracleAddrs) external returns (uint256 updated, uint256 expected);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface CToken {
function accrueInterest() external returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) external view returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function borrow(uint256 borrowAmount) external returns (uint256);
function mint() external payable; // For ETH
function mint(uint256 mintAmount) external returns (uint256); // For ERC20
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function repayBorrow() external payable; // For ETH
function repayBorrow(uint256 repayAmount) external returns (uint256); // For ERC20
function transfer(address user, uint256 amount) external returns (bool);
function getCash() external view returns (uint256);
function transferFrom(
address owner,
address user,
uint256 amount
) external returns (bool);
function underlying() external view returns (address);
}
interface Comptroller {
function claimComp(address holder, address[] memory) external;
function enterMarkets(address[] memory cTokens) external returns (uint256[] memory);
function exitMarket(address cToken) external returns (uint256);
function compAccrued(address holder) external view returns (uint256);
function getAccountLiquidity(address account)
external
view
returns (
uint256,
uint256,
uint256
);
function markets(address market)
external
view
returns (
bool isListed,
uint256 collateralFactorMantissa,
bool isCompted
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
/** In order to keep code/files short, all libraries and interfaces are trimmed as per Vesper need */
library Account {
enum Status {Normal, Liquid, Vapor}
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
}
library Actions {
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (publicly)
Sell, // sell an amount of some token (publicly)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
}
library Types {
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
}
interface ISoloMargin {
function getMarketTokenAddress(uint256 marketId) external view returns (address);
function getNumMarkets() external view returns (uint256);
function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external;
}
/**
* @title ICallee
* @author dYdX
*
* Interface that Callees for Solo must implement in order to ingest data.
*/
interface ICallee {
// ============ Public Functions ============
/**
* Allows users to send this contract arbitrary data.
*
* @param sender The msg.sender to Solo
* @param accountInfo The account from which the data is being sent
* @param data Arbitrary data given by the sender
*/
function callFunction(
address sender,
Account.Info memory accountInfo,
bytes memory data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
// Interface to use 3rd party Uniswap V3 oracle utility contract deployed at https://etherscan.io/address/0x0f1f5a87f99f0918e6c81f16e59f3518698221ff#code
/// @title UniswapV3 oracle with ability to query across an intermediate liquidity pool
interface IUniswapV3Oracle {
function assetToEth(
address _tokenIn,
uint256 _amountIn,
uint32 _twapPeriod
) external view returns (uint256 ethAmountOut);
function ethToAsset(
uint256 _ethAmountIn,
address _tokenOut,
uint32 _twapPeriod
) external view returns (uint256 amountOut);
function assetToAsset(
address _tokenIn,
uint256 _amountIn,
address _tokenOut,
uint32 _twapPeriod
) external view returns (uint256 amountOut);
function assetToAssetThruRoute(
address _tokenIn,
uint256 _amountIn,
address _tokenOut,
uint32 _twapPeriod,
address _routeThruToken,
uint24[2] memory _poolFees
) external view returns (uint256 amountOut);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface TokenLike is IERC20 {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IStrategy {
function rebalance() external;
function sweepERC20(address _fromToken) external;
function withdraw(uint256 _amount) external;
function feeCollector() external view returns (address);
function isReservedToken(address _token) external view returns (bool);
function keepers() external view returns (address[] memory);
function migrate(address _newStrategy) external;
function token() external view returns (address);
function totalValue() external view returns (uint256);
function totalValueCurrent() external returns (uint256);
function pool() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IVesperPool is IERC20 {
function deposit() external payable;
function deposit(uint256 _share) external;
function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool);
function excessDebt(address _strategy) external view returns (uint256);
function permit(
address,
address,
uint256,
uint256,
uint8,
bytes32,
bytes32
) external;
function poolRewards() external returns (address);
function reportEarning(
uint256 _profit,
uint256 _loss,
uint256 _payback
) external;
function reportLoss(uint256 _loss) external;
function resetApproval() external;
function sweepERC20(address _fromToken) external;
function withdraw(uint256 _amount) external;
function withdrawETH(uint256 _amount) external;
function whitelistedWithdraw(uint256 _amount) external;
function governor() external view returns (address);
function keepers() external view returns (address[] memory);
function isKeeper(address _address) external view returns (bool);
function maintainers() external view returns (address[] memory);
function isMaintainer(address _address) external view returns (bool);
function feeCollector() external view returns (address);
function pricePerShare() external view returns (uint256);
function strategy(address _strategy)
external
view
returns (
bool _active,
uint256 _interestFee,
uint256 _debtRate,
uint256 _lastRebalance,
uint256 _totalDebt,
uint256 _totalLoss,
uint256 _totalProfit,
uint256 _debtRatio
);
function stopEverything() external view returns (bool);
function token() external view returns (IERC20);
function tokensHere() external view returns (uint256);
function totalDebtOf(address _strategy) external view returns (uint256);
function totalValue() external view returns (uint256);
function withdrawFee() external view returns (uint256);
// Function to get pricePerShare from V2 pools
function getPricePerShare() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "../dependencies/openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "../interfaces/bloq/ISwapManager.sol";
import "../interfaces/vesper/IStrategy.sol";
import "../interfaces/vesper/IVesperPool.sol";
abstract contract Strategy is IStrategy, Context {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint256 internal constant MAX_UINT_VALUE = type(uint256).max;
// solhint-disable-next-line var-name-mixedcase
address internal WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
IERC20 public immutable collateralToken;
address public receiptToken;
address public immutable override pool;
address public override feeCollector;
ISwapManager public swapManager;
uint256 public oraclePeriod = 3600; // 1h
uint256 public oracleRouterIdx = 0; // Uniswap V2
uint256 public swapSlippage = 10000; // 100% Don't use oracles by default
EnumerableSet.AddressSet private _keepers;
event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector);
event UpdatedSwapManager(address indexed previousSwapManager, address indexed newSwapManager);
event UpdatedSwapSlippage(uint256 oldSwapSlippage, uint256 newSwapSlippage);
event UpdatedOracleConfig(uint256 oldPeriod, uint256 newPeriod, uint256 oldRouterIdx, uint256 newRouterIdx);
constructor(
address _pool,
address _swapManager,
address _receiptToken
) {
require(_pool != address(0), "pool-address-is-zero");
require(_swapManager != address(0), "sm-address-is-zero");
swapManager = ISwapManager(_swapManager);
pool = _pool;
collateralToken = IVesperPool(_pool).token();
receiptToken = _receiptToken;
require(_keepers.add(_msgSender()), "add-keeper-failed");
}
modifier onlyGovernor {
require(_msgSender() == IVesperPool(pool).governor(), "caller-is-not-the-governor");
_;
}
modifier onlyKeeper() {
require(_keepers.contains(_msgSender()), "caller-is-not-a-keeper");
_;
}
modifier onlyPool() {
require(_msgSender() == pool, "caller-is-not-vesper-pool");
_;
}
/**
* @notice Add given address in keepers list.
* @param _keeperAddress keeper address to add.
*/
function addKeeper(address _keeperAddress) external onlyGovernor {
require(_keepers.add(_keeperAddress), "add-keeper-failed");
}
/// @notice Return list of keepers
function keepers() external view override returns (address[] memory) {
return _keepers.values();
}
/**
* @notice Migrate all asset and vault ownership,if any, to new strategy
* @dev _beforeMigration hook can be implemented in child strategy to do extra steps.
* @param _newStrategy Address of new strategy
*/
function migrate(address _newStrategy) external virtual override onlyPool {
require(_newStrategy != address(0), "new-strategy-address-is-zero");
require(IStrategy(_newStrategy).pool() == pool, "not-valid-new-strategy");
_beforeMigration(_newStrategy);
IERC20(receiptToken).safeTransfer(_newStrategy, IERC20(receiptToken).balanceOf(address(this)));
collateralToken.safeTransfer(_newStrategy, collateralToken.balanceOf(address(this)));
}
/**
* @notice Remove given address from keepers list.
* @param _keeperAddress keeper address to remove.
*/
function removeKeeper(address _keeperAddress) external onlyGovernor {
require(_keepers.remove(_keeperAddress), "remove-keeper-failed");
}
/**
* @notice Update fee collector
* @param _feeCollector fee collector address
*/
function updateFeeCollector(address _feeCollector) external onlyGovernor {
require(_feeCollector != address(0), "fee-collector-address-is-zero");
require(_feeCollector != feeCollector, "fee-collector-is-same");
emit UpdatedFeeCollector(feeCollector, _feeCollector);
feeCollector = _feeCollector;
}
/**
* @notice Update swap manager address
* @param _swapManager swap manager address
*/
function updateSwapManager(address _swapManager) external onlyGovernor {
require(_swapManager != address(0), "sm-address-is-zero");
require(_swapManager != address(swapManager), "sm-is-same");
emit UpdatedSwapManager(address(swapManager), _swapManager);
swapManager = ISwapManager(_swapManager);
}
function updateSwapSlippage(uint256 _newSwapSlippage) external onlyGovernor {
require(_newSwapSlippage <= 10000, "invalid-slippage-value");
emit UpdatedSwapSlippage(swapSlippage, _newSwapSlippage);
swapSlippage = _newSwapSlippage;
}
function updateOracleConfig(uint256 _newPeriod, uint256 _newRouterIdx) external onlyGovernor {
require(_newRouterIdx < swapManager.N_DEX(), "invalid-router-index");
if (_newPeriod == 0) _newPeriod = oraclePeriod;
require(_newPeriod > 59, "invalid-oracle-period");
emit UpdatedOracleConfig(oraclePeriod, _newPeriod, oracleRouterIdx, _newRouterIdx);
oraclePeriod = _newPeriod;
oracleRouterIdx = _newRouterIdx;
}
/// @dev Approve all required tokens
function approveToken() external onlyKeeper {
_approveToken(0);
_approveToken(MAX_UINT_VALUE);
}
function setupOracles() external onlyKeeper {
_setupOracles();
}
/**
* @dev Withdraw collateral token from lending pool.
* @param _amount Amount of collateral token
*/
function withdraw(uint256 _amount) external override onlyPool {
_withdraw(_amount);
}
/**
* @dev Rebalance profit, loss and investment of this strategy
*/
function rebalance() external virtual override onlyKeeper {
(uint256 _profit, uint256 _loss, uint256 _payback) = _generateReport();
IVesperPool(pool).reportEarning(_profit, _loss, _payback);
_reinvest();
}
/**
* @dev sweep given token to feeCollector of strategy
* @param _fromToken token address to sweep
*/
function sweepERC20(address _fromToken) external override onlyKeeper {
require(feeCollector != address(0), "fee-collector-not-set");
require(_fromToken != address(collateralToken), "not-allowed-to-sweep-collateral");
require(!isReservedToken(_fromToken), "not-allowed-to-sweep");
if (_fromToken == ETH) {
Address.sendValue(payable(feeCollector), address(this).balance);
} else {
uint256 _amount = IERC20(_fromToken).balanceOf(address(this));
IERC20(_fromToken).safeTransfer(feeCollector, _amount);
}
}
/// @notice Returns address of token correspond to collateral token
function token() external view override returns (address) {
return receiptToken;
}
/**
* @notice Calculate total value of asset under management
* @dev Report total value in collateral token
*/
function totalValue() public view virtual override returns (uint256 _value);
/**
* @notice Calculate total value of asset under management (in real-time)
* @dev Report total value in collateral token
*/
function totalValueCurrent() external virtual override returns (uint256) {
return totalValue();
}
/// @notice Check whether given token is reserved or not. Reserved tokens are not allowed to sweep.
function isReservedToken(address _token) public view virtual override returns (bool);
/**
* @notice some strategy may want to prepare before doing migration.
Example In Maker old strategy want to give vault ownership to new strategy
* @param _newStrategy .
*/
function _beforeMigration(address _newStrategy) internal virtual;
/**
* @notice Generate report for current profit and loss. Also liquidate asset to payback
* excess debt, if any.
* @return _profit Calculate any realized profit and convert it to collateral, if not already.
* @return _loss Calculate any loss that strategy has made on investment. Convert into collateral token.
* @return _payback If strategy has any excess debt, we have to liquidate asset to payback excess debt.
*/
function _generateReport()
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _payback
)
{
uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this));
uint256 _totalDebt = IVesperPool(pool).totalDebtOf(address(this));
_profit = _realizeProfit(_totalDebt);
_loss = _realizeLoss(_totalDebt);
_payback = _liquidate(_excessDebt);
}
function _calcAmtOutAfterSlippage(uint256 _amount, uint256 _slippage) internal pure returns (uint256) {
return (_amount * (10000 - _slippage)) / (10000);
}
function _simpleOraclePath(address _from, address _to) internal view returns (address[] memory path) {
if (_from == WETH || _to == WETH) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
} else {
path = new address[](3);
path[0] = _from;
path[1] = WETH;
path[2] = _to;
}
}
function _consultOracle(
address _from,
address _to,
uint256 _amt
) internal returns (uint256, bool) {
for (uint256 i = 0; i < swapManager.N_DEX(); i++) {
(bool _success, bytes memory _returnData) =
address(swapManager).call(
abi.encodePacked(swapManager.consult.selector, abi.encode(_from, _to, _amt, oraclePeriod, i))
);
if (_success) {
(uint256 rate, uint256 lastUpdate, ) = abi.decode(_returnData, (uint256, uint256, bool));
if ((lastUpdate > (block.timestamp - oraclePeriod)) && (rate != 0)) return (rate, true);
return (0, false);
}
}
return (0, false);
}
function _getOracleRate(address[] memory path, uint256 _amountIn) internal returns (uint256 amountOut) {
require(path.length > 1, "invalid-oracle-path");
amountOut = _amountIn;
bool isValid;
for (uint256 i = 0; i < path.length - 1; i++) {
(amountOut, isValid) = _consultOracle(path[i], path[i + 1], amountOut);
require(isValid, "invalid-oracle-rate");
}
}
/**
* @notice Safe swap via Uniswap / Sushiswap (better rate of the two)
* @dev There are many scenarios when token swap via Uniswap can fail, so this
* method will wrap Uniswap call in a 'try catch' to make it fail safe.
* however, this method will throw minAmountOut is not met
* @param _from address of from token
* @param _to address of to token
* @param _amountIn Amount to be swapped
* @param _minAmountOut minimum amount out
*/
function _safeSwap(
address _from,
address _to,
uint256 _amountIn,
uint256 _minAmountOut
) internal {
(address[] memory path, uint256 amountOut, uint256 rIdx) =
swapManager.bestOutputFixedInput(_from, _to, _amountIn);
if (_minAmountOut == 0) _minAmountOut = 1;
if (amountOut != 0) {
swapManager.ROUTERS(rIdx).swapExactTokensForTokens(
_amountIn,
_minAmountOut,
path,
address(this),
block.timestamp
);
}
}
// These methods can be implemented by the inheriting strategy.
/* solhint-disable no-empty-blocks */
function _claimRewardsAndConvertTo(address _toToken) internal virtual {}
/**
* @notice Set up any oracles that are needed for this strategy.
*/
function _setupOracles() internal virtual {}
/* solhint-enable */
// These methods must be implemented by the inheriting strategy
function _withdraw(uint256 _amount) internal virtual;
function _approveToken(uint256 _amount) internal virtual;
/**
* @notice Withdraw collateral to payback excess debt in pool.
* @param _excessDebt Excess debt of strategy in collateral token
* @return _payback amount in collateral token. Usually it is equal to excess debt.
*/
function _liquidate(uint256 _excessDebt) internal virtual returns (uint256 _payback);
/**
* @notice Calculate earning and withdraw/convert it into collateral token.
* @param _totalDebt Total collateral debt of this strategy
* @return _profit Profit in collateral token
*/
function _realizeProfit(uint256 _totalDebt) internal virtual returns (uint256 _profit);
/**
* @notice Calculate loss
* @param _totalDebt Total collateral debt of this strategy
* @return _loss Realized loss in collateral token
*/
function _realizeLoss(uint256 _totalDebt) internal virtual returns (uint256 _loss);
/**
* @notice Reinvest collateral.
* @dev Once we file report back in pool, we might have some collateral in hand
* which we want to reinvest aka deposit in lender/provider.
*/
function _reinvest() internal virtual;
}
// SPDX-License-Identifier: GNU LGPLv3
// Heavily inspired from CompoundLeverage strategy of Yearn. https://etherscan.io/address/0x4031afd3B0F71Bace9181E554A9E680Ee4AbE7dF#code
pragma solidity 0.8.3;
import "../Strategy.sol";
import "../../interfaces/compound/ICompound.sol";
import "../../interfaces/oracle/IUniswapV3Oracle.sol";
import "../../FlashLoanHelper.sol";
/// @title This strategy will deposit collateral token in Compound and based on position
/// it will borrow same collateral token. It will use borrowed asset as supply and borrow again.
contract CompoundLeverageStrategy is Strategy, FlashLoanHelper {
using SafeERC20 for IERC20;
// solhint-disable-next-line var-name-mixedcase
string public NAME;
string public constant VERSION = "4.0.0";
uint256 internal constant MAX_BPS = 10_000; //100%
uint256 public minBorrowRatio = 5_000; // 50%
uint256 public maxBorrowRatio = 6_000; // 60%
CToken internal cToken;
IUniswapV3Oracle internal constant ORACLE = IUniswapV3Oracle(0x0F1f5A87f99f0918e6C81F16E59F3518698221Ff);
uint32 internal constant TWAP_PERIOD = 3600;
Comptroller public immutable comptroller;
address public immutable rewardToken;
address public rewardDistributor;
event UpdatedBorrowRatio(
uint256 previousMinBorrowRatio,
uint256 newMinBorrowRatio,
uint256 previousMaxBorrowRatio,
uint256 newMaxBorrowRatio
);
constructor(
address _pool,
address _swapManager,
address _comptroller,
address _rewardDistributor,
address _rewardToken,
address _aaveAddressesProvider,
address _receiptToken,
string memory _name
) Strategy(_pool, _swapManager, _receiptToken) FlashLoanHelper(_aaveAddressesProvider) {
NAME = _name;
require(_comptroller != address(0), "comptroller-address-is-zero");
comptroller = Comptroller(_comptroller);
rewardToken = _rewardToken;
require(_receiptToken != address(0), "cToken-address-is-zero");
cToken = CToken(_receiptToken);
require(_rewardDistributor != address(0), "invalid-reward-distributor-addr");
rewardDistributor = _rewardDistributor;
}
/**
* @notice Update upper and lower borrow ratio
* @dev It is possible to set 0 as _minBorrowRatio to not borrow anything
* @param _minBorrowRatio Minimum % we want to borrow
* @param _maxBorrowRatio Maximum % we want to borrow
*/
function updateBorrowRatio(uint256 _minBorrowRatio, uint256 _maxBorrowRatio) external onlyGovernor {
(, uint256 _collateralFactor, ) = comptroller.markets(address(cToken));
require(_maxBorrowRatio < (_collateralFactor / 1e14), "invalid-max-borrow-limit");
require(_maxBorrowRatio > _minBorrowRatio, "max-should-be-higher-than-min");
emit UpdatedBorrowRatio(minBorrowRatio, _minBorrowRatio, maxBorrowRatio, _maxBorrowRatio);
minBorrowRatio = _minBorrowRatio;
maxBorrowRatio = _maxBorrowRatio;
}
function updateAaveStatus(bool _status) external onlyGovernor {
_updateAaveStatus(_status);
}
function updateDyDxStatus(bool _status) external virtual onlyGovernor {
_updateDyDxStatus(_status, address(collateralToken));
}
/**
* @notice Calculate total value based on rewardToken claimed, supply and borrow position
* @dev Report total value in collateral token
* @dev Claimed rewardToken will stay in strategy until next rebalance
*/
function totalValueCurrent() public override returns (uint256 _totalValue) {
cToken.exchangeRateCurrent();
_claimRewards();
_totalValue = _calculateTotalValue(IERC20(rewardToken).balanceOf(address(this)));
}
/**
* @notice Current borrow ratio, calculated as current borrow divide by max allowed borrow
* Return value is based on basis points, i.e. 7500 = 75% ratio
*/
function currentBorrowRatio() external view returns (uint256) {
(uint256 _supply, uint256 _borrow) = getPosition();
return _borrow == 0 ? 0 : (_borrow * MAX_BPS) / _supply;
}
/**
* @notice Calculate total value using rewardToken accrued, supply and borrow position
* @dev Compound calculate rewardToken accrued and store it when user interact with
* Compound contracts, i.e. deposit, withdraw or transfer tokens.
* So compAccrued() will return stored rewardToken accrued amount, which is older
* @dev For up to date value check totalValueCurrent()
*/
function totalValue() public view virtual override returns (uint256 _totalValue) {
_totalValue = _calculateTotalValue(_getRewardAccrued());
}
/**
* @notice Calculate current position using claimed rewardToken and current borrow.
*/
function isLossMaking() external returns (bool) {
// It's loss making if _totalValue < totalDebt
return totalValueCurrent() < IVesperPool(pool).totalDebtOf(address(this));
}
function isReservedToken(address _token) public view virtual override returns (bool) {
return _token == address(cToken) || _token == rewardToken || _token == address(collateralToken);
}
/// @notice Return supply and borrow position. Position may return few block old value
function getPosition() public view returns (uint256 _supply, uint256 _borrow) {
(, uint256 _cTokenBalance, uint256 _borrowBalance, uint256 _exchangeRate) =
cToken.getAccountSnapshot(address(this));
_supply = (_cTokenBalance * _exchangeRate) / 1e18;
_borrow = _borrowBalance;
}
/// @notice Approve all required tokens
function _approveToken(uint256 _amount) internal virtual override {
collateralToken.safeApprove(pool, _amount);
collateralToken.safeApprove(address(cToken), _amount);
for (uint256 i = 0; i < swapManager.N_DEX(); i++) {
IERC20(rewardToken).safeApprove(address(swapManager.ROUTERS(i)), _amount);
}
FlashLoanHelper._approveToken(address(collateralToken), _amount);
}
/**
* @notice Claim rewardToken and transfer to new strategy
* @param _newStrategy Address of new strategy.
*/
function _beforeMigration(address _newStrategy) internal virtual override {
require(IStrategy(_newStrategy).token() == address(cToken), "wrong-receipt-token");
minBorrowRatio = 0;
// It will calculate amount to repay based on borrow limit and payback all
_reinvest();
}
/**
* @notice Calculate borrow position based on borrow ratio, current supply, borrow, amount
* being deposited or withdrawn.
* @param _amount Collateral amount
* @param _isDeposit Flag indicating whether we are depositing _amount or withdrawing
* @return _position Amount of borrow that need to be adjusted
* @return _shouldRepay Flag indicating whether _position is borrow amount or repay amount
*/
function _calculateDesiredPosition(uint256 _amount, bool _isDeposit)
internal
returns (uint256 _position, bool _shouldRepay)
{
uint256 _totalSupply = cToken.balanceOfUnderlying(address(this));
uint256 _currentBorrow = cToken.borrowBalanceStored(address(this));
// If minimum borrow limit set to 0 then repay borrow
if (minBorrowRatio == 0) {
return (_currentBorrow, true);
}
uint256 _supply = _totalSupply - _currentBorrow;
// In case of withdraw, _amount can be greater than _supply
uint256 _newSupply = _isDeposit ? _supply + _amount : _supply > _amount ? _supply - _amount : 0;
// (supply * borrowRatio)/(BPS - borrowRatio)
uint256 _borrowUpperBound = (_newSupply * maxBorrowRatio) / (MAX_BPS - maxBorrowRatio);
uint256 _borrowLowerBound = (_newSupply * minBorrowRatio) / (MAX_BPS - minBorrowRatio);
// If our current borrow is greater than max borrow allowed, then we will have to repay
// some to achieve safe position else borrow more.
if (_currentBorrow > _borrowUpperBound) {
_shouldRepay = true;
// If borrow > upperBound then it is greater than lowerBound too.
_position = _currentBorrow - _borrowLowerBound;
} else if (_currentBorrow < _borrowLowerBound) {
_shouldRepay = false;
// We can borrow more.
_position = _borrowLowerBound - _currentBorrow;
}
}
/// @notice Get main Rewards accrued
function _getRewardAccrued() internal view virtual returns (uint256 _rewardAccrued) {
_rewardAccrued = comptroller.compAccrued(address(this));
}
/**
* @dev rewardToken is converted to collateral and if we have some borrow interest to pay,
* it will go come from collateral.
* @dev Report total value in collateral token
*/
function _calculateTotalValue(uint256 _rewardAccrued) internal view returns (uint256 _totalValue) {
uint256 _compAsCollateral;
if (_rewardAccrued != 0) {
(, _compAsCollateral, ) = swapManager.bestOutputFixedInput(
rewardToken,
address(collateralToken),
_rewardAccrued
);
}
(uint256 _supply, uint256 _borrow) = getPosition();
_totalValue = _compAsCollateral + collateralToken.balanceOf(address(this)) + _supply - _borrow;
}
/// @notice Claim comp
function _claimRewards() internal virtual {
address[] memory _markets = new address[](1);
_markets[0] = address(cToken);
comptroller.claimComp(address(this), _markets);
}
/// @notice Claim rewardToken and convert rewardToken into collateral token.
function _claimRewardsAndConvertTo(address _toToken) internal override {
_claimRewards();
uint256 _rewardAmount = IERC20(rewardToken).balanceOf(address(this));
if (_rewardAmount != 0) {
_safeSwap(rewardToken, _toToken, _rewardAmount);
}
}
/**
* @notice Generate report for pools accounting and also send profit and any payback to pool.
* @dev Claim rewardToken and convert to collateral.
*/
function _generateReport()
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _payback
)
{
uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this));
(, , , , uint256 _totalDebt, , , uint256 _debtRatio) = IVesperPool(pool).strategy(address(this));
// Claim rewardToken and convert to collateral token
_claimRewardsAndConvertTo(address(collateralToken));
uint256 _supply = cToken.balanceOfUnderlying(address(this));
uint256 _borrow = cToken.borrowBalanceStored(address(this));
uint256 _investedCollateral = _supply - _borrow;
uint256 _collateralHere = collateralToken.balanceOf(address(this));
uint256 _totalCollateral = _investedCollateral + _collateralHere;
uint256 _profitToWithdraw;
if (_totalCollateral > _totalDebt) {
_profit = _totalCollateral - _totalDebt;
if (_collateralHere <= _profit) {
_profitToWithdraw = _profit - _collateralHere;
} else if (_collateralHere >= (_profit + _excessDebt)) {
_payback = _excessDebt;
} else {
// _profit < CollateralHere < _profit + _excessDebt
_payback = _collateralHere - _profit;
}
} else {
_loss = _totalDebt - _totalCollateral;
}
uint256 _paybackToWithdraw = _excessDebt - _payback;
uint256 _totalAmountToWithdraw = _paybackToWithdraw + _profitToWithdraw;
if (_totalAmountToWithdraw != 0) {
uint256 _withdrawn = _withdrawHere(_totalAmountToWithdraw);
// Any amount withdrawn over _profitToWithdraw is payback for pool
if (_withdrawn > _profitToWithdraw) {
_payback += (_withdrawn - _profitToWithdraw);
}
}
// Handle scenario if debtRatio is zero and some supply left.
// Remaining tokens, after payback withdrawal, are profit
(_supply, _borrow) = getPosition();
if (_debtRatio == 0 && _supply != 0 && _borrow == 0) {
// This will redeem all cTokens this strategy has
_redeemUnderlying(MAX_UINT_VALUE);
_profit += _supply;
}
}
/**
* Adjust position by normal leverage and deleverage.
* @param _adjustBy Amount by which we want to increase or decrease _borrow
* @param _shouldRepay True indicate we want to deleverage
* @return amount Actual adjusted amount
*/
function _adjustPosition(uint256 _adjustBy, bool _shouldRepay) internal returns (uint256 amount) {
// We can get position via view function, as this function will be called after _calculateDesiredPosition
(uint256 _supply, uint256 _borrow) = getPosition();
// If no borrow then there is nothing to deleverage
if (_borrow == 0 && _shouldRepay) {
return 0;
}
(, uint256 collateralFactor, ) = comptroller.markets(address(cToken));
if (_shouldRepay) {
amount = _normalDeleverage(_adjustBy, _supply, _borrow, collateralFactor);
} else {
amount = _normalLeverage(_adjustBy, _supply, _borrow, collateralFactor);
}
}
/**
* Deleverage: Reduce borrow to achieve safe position
* @param _maxDeleverage Reduce borrow by this amount
* @return _deleveragedAmount Amount we actually reduced
*/
function _normalDeleverage(
uint256 _maxDeleverage,
uint256 _supply,
uint256 _borrow,
uint256 _collateralFactor
) internal returns (uint256 _deleveragedAmount) {
uint256 _theoreticalSupply;
if (_collateralFactor != 0) {
// Calculate minimum supply required to support _borrow
_theoreticalSupply = (_borrow * 1e18) / _collateralFactor;
}
_deleveragedAmount = _supply - _theoreticalSupply;
if (_deleveragedAmount >= _borrow) {
_deleveragedAmount = _borrow;
}
if (_deleveragedAmount >= _maxDeleverage) {
_deleveragedAmount = _maxDeleverage;
}
_redeemUnderlying(_deleveragedAmount);
_repayBorrow(_deleveragedAmount);
}
/**
* Leverage: Borrow more
* @param _maxLeverage Max amount to borrow
* @return _leveragedAmount Amount we actually borrowed
*/
function _normalLeverage(
uint256 _maxLeverage,
uint256 _supply,
uint256 _borrow,
uint256 _collateralFactor
) internal returns (uint256 _leveragedAmount) {
// Calculate maximum we can borrow at current _supply
uint256 theoreticalBorrow = (_supply * _collateralFactor) / 1e18;
_leveragedAmount = theoreticalBorrow - _borrow;
if (_leveragedAmount >= _maxLeverage) {
_leveragedAmount = _maxLeverage;
}
_borrowCollateral(_leveragedAmount);
_mint(collateralToken.balanceOf(address(this)));
}
/// @notice Deposit collateral in Compound and adjust borrow position
function _reinvest() internal virtual override {
uint256 _collateralBalance = collateralToken.balanceOf(address(this));
(uint256 _position, bool _shouldRepay) = _calculateDesiredPosition(_collateralBalance, true);
// Supply collateral to compound.
_mint(_collateralBalance);
// During reinvest, _shouldRepay will be false which indicate that we will borrow more.
_position -= _doFlashLoan(_position, _shouldRepay);
uint256 i = 0;
while (_position > 0 && i <= 6) {
_position -= _adjustPosition(_position, _shouldRepay);
i++;
}
}
/// @dev Withdraw collateral and transfer it to pool
function _withdraw(uint256 _amount) internal override {
collateralToken.safeTransfer(pool, _withdrawHere(_amount));
}
/// @dev Withdraw collateral here. Do not transfer to pool
function _withdrawHere(uint256 _amount) internal returns (uint256) {
(uint256 _position, bool _shouldRepay) = _calculateDesiredPosition(_amount, false);
if (_shouldRepay) {
// Do deleverage by flash loan
_position -= _doFlashLoan(_position, _shouldRepay);
// If we still have _position to deleverage do it via normal deleverage
uint256 i = 0;
while (_position > 0 && i <= 10) {
_position -= _adjustPosition(_position, true);
i++;
}
// There may be scenario where we are not able to deleverage enough
if (_position != 0) {
// Calculate redeemable at current borrow and supply.
(uint256 _supply, uint256 _borrow) = getPosition();
uint256 _supplyToSupportBorrow;
if (maxBorrowRatio != 0) {
_supplyToSupportBorrow = (_borrow * MAX_BPS) / maxBorrowRatio;
}
// Current supply minus supply required to support _borrow at _maxBorrowRatio
uint256 _redeemable = _supply - _supplyToSupportBorrow;
if (_amount > _redeemable) {
_amount = _redeemable;
}
}
}
uint256 _collateralBefore = collateralToken.balanceOf(address(this));
// If we do not have enough collateral, try to get some via COMP
// This scenario is rare and will happen during last withdraw
if (_amount > cToken.balanceOfUnderlying(address(this))) {
// Use all collateral for withdraw
_collateralBefore = 0;
_claimRewardsAndConvertTo(address(collateralToken));
// Updated amount
_amount = _amount - collateralToken.balanceOf(address(this));
}
_redeemUnderlying(_amount);
uint256 _collateralAfter = collateralToken.balanceOf(address(this));
return _collateralAfter - _collateralBefore;
}
/**
* @dev Aave flash is used only for withdrawal due to high fee compare to DyDx
* @param _flashAmount Amount for flash loan
* @param _shouldRepay Flag indicating we want to leverage or deleverage
* @return Total amount we leverage or deleverage using flash loan
*/
function _doFlashLoan(uint256 _flashAmount, bool _shouldRepay) internal returns (uint256) {
uint256 _totalFlashAmount;
// Due to less fee DyDx is our primary flash loan provider
if (isDyDxActive && _flashAmount > 0) {
bytes memory _data = abi.encode(_flashAmount, _shouldRepay);
_totalFlashAmount = _doDyDxFlashLoan(address(collateralToken), _flashAmount, _data);
_flashAmount -= _totalFlashAmount;
}
if (isAaveActive && _shouldRepay && _flashAmount > 0) {
bytes memory _data = abi.encode(_flashAmount, _shouldRepay);
_totalFlashAmount += _doAaveFlashLoan(address(collateralToken), _flashAmount, _data);
}
return _totalFlashAmount;
}
/**
* @notice This function will be called by flash loan
* @dev In case of borrow, DyDx is preferred as fee is so low that it does not effect
* our collateralRatio and liquidation risk.
*/
function _flashLoanLogic(bytes memory _data, uint256 _repayAmount) internal override {
(uint256 _amount, bool _deficit) = abi.decode(_data, (uint256, bool));
uint256 _collateralHere = collateralToken.balanceOf(address(this));
require(_collateralHere >= _amount, "FLASH_FAILED"); // to stop malicious calls
//if in deficit we repay amount and then withdraw
if (_deficit) {
_repayBorrow(_amount);
//if we are withdrawing we take more to cover fee
_redeemUnderlying(_repayAmount);
} else {
_mint(_collateralHere);
//borrow more to cover fee
_borrowCollateral(_repayAmount);
}
}
/**
* @dev If swap slippage is defined then use oracle to get amountOut and calculate minAmountOut
*/
function _safeSwap(
address _tokenIn,
address _tokenOut,
uint256 _amountIn
) internal virtual {
uint256 _minAmountOut =
swapSlippage != 10000
? _calcAmtOutAfterSlippage(
ORACLE.assetToAsset(_tokenIn, _amountIn, _tokenOut, TWAP_PERIOD),
swapSlippage
)
: 1;
_safeSwap(_tokenIn, _tokenOut, _amountIn, _minAmountOut);
}
//////////////////// Compound wrapper functions //////////////////////////////
/**
* @dev Compound support ETH as collateral not WETH. So ETH strategy can override
* below functions and handle wrap/unwrap of WETH.
*/
function _mint(uint256 _amount) internal virtual {
require(cToken.mint(_amount) == 0, "supply-to-compound-failed");
}
function _redeemUnderlying(uint256 _amount) internal virtual {
if (_amount == MAX_UINT_VALUE) {
// Withdraw all cTokens
require(cToken.redeem(cToken.balanceOf(address(this))) == 0, "withdraw-from-compound-failed");
} else {
// Withdraw underlying
require(cToken.redeemUnderlying(_amount) == 0, "withdraw-from-compound-failed");
}
}
function _borrowCollateral(uint256 _amount) internal virtual {
require(cToken.borrow(_amount) == 0, "borrow-from-compound-failed");
}
function _repayBorrow(uint256 _amount) internal virtual {
require(cToken.repayBorrow(_amount) == 0, "repay-to-compound-failed");
}
//////////////////////////////////////////////////////////////////////////////
/* solhint-disable no-empty-blocks */
// We overridden _generateReport which eliminates need of below function.
function _liquidate(uint256 _excessDebt) internal override returns (uint256 _payback) {}
function _realizeProfit(uint256 _totalDebt) internal virtual override returns (uint256) {}
function _realizeLoss(uint256 _totalDebt) internal view override returns (uint256 _loss) {}
/* solhint-enable no-empty-blocks */
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./CompoundLeverageStrategy.sol";
import "../../interfaces/token/IToken.sol";
// solhint-disable no-empty-blocks
/// @title Deposit ETH in Compound and earn interest.
contract CompoundLeverageStrategyETH is CompoundLeverageStrategy {
constructor(
address _pool,
address _swapManager,
address _comptroller,
address _rewardDistributor,
address _rewardToken,
address _aaveAddressesProvider,
address _receiptToken,
string memory _name
)
CompoundLeverageStrategy(
_pool,
_swapManager,
_comptroller,
_rewardDistributor,
_rewardToken,
_aaveAddressesProvider,
_receiptToken,
_name
)
{}
/// @dev Only receive ETH from either cToken or WETH
receive() external payable {
require(msg.sender == address(cToken) || msg.sender == WETH, "not-allowed-to-send-ether");
}
/// @dev Compound support ETH as collateral. Convert WETH to ETH and mint cETH
function _mint(uint256 _amount) internal override {
_withdrawETH(_amount);
cToken.mint{value: _amount}();
}
/// @dev On redeem we will receive ETH. Convert received ETH into WETH
function _redeemUnderlying(uint256 _amount) internal override {
super._redeemUnderlying(_amount);
_depositETH();
}
/// @dev On borrow we will receive ETH. Convert received ETH into WETH
function _borrowCollateral(uint256 _amount) internal override {
super._borrowCollateral(_amount);
_depositETH();
}
/// @dev Repay will take ETH. Convert WETH to ETH and call payable repay function
function _repayBorrow(uint256 _amount) internal override {
_withdrawETH(_amount);
cToken.repayBorrow{value: _amount}();
}
/// @dev Deposit ETH and get WETH in return
function _depositETH() internal {
TokenLike(WETH).deposit{value: address(this).balance}();
}
/// @dev Withdraw ETH by burning similar amount of WETH
function _withdrawETH(uint256 _amount) internal {
TokenLike(WETH).withdraw(_amount);
}
} | (supply * borrowRatio)/(BPS - borrowRatio) | uint256 _borrowUpperBound = (_newSupply * maxBorrowRatio) / (MAX_BPS - maxBorrowRatio);
| 1,539,091 | [
1,
12,
2859,
1283,
225,
29759,
8541,
13176,
12,
38,
5857,
300,
29759,
8541,
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
]
| [
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,
389,
70,
15318,
21328,
273,
261,
67,
2704,
3088,
1283,
380,
943,
38,
15318,
8541,
13,
342,
261,
6694,
67,
38,
5857,
300,
943,
38,
15318,
8541,
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
]
|
contract Token {
/* Public variables of the token */
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
function Token() {
totalSupply = 15*(10**8)*(10**18);
balanceOf[msg.sender] = 15*(10**8)*(10**18); // Give the creator all initial tokens
name = "GM"; // Set the name for display purposes
symbol = "ngm"; // Set the symbol for display purposes
decimals = 18; // Amount of decimals for display purposes
}
function transfer(address _to, uint256 _value) {
/* Check if sender has balance and for overflows */
if (balanceOf[msg.sender] < _value || balanceOf[_to] + _value < balanceOf[_to])
revert();
/* Add and subtract new balances */
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
/* Notifiy anyone listening that this transfer took place */
Transfer(msg.sender, _to, _value);
}
/* This unnamed function is called whenever someone tries to send ether to it */
function () {
revert(); // Prevents accidental sending of ether
}
} | Set the symbol for display purposes
| symbol = "ngm"; | 14,749,827 | [
1,
694,
326,
3273,
364,
2562,
13694,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
202,
7175,
273,
315,
3368,
81,
14432,
27573,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( (@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@%@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@%%%%@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@&%%%%%%%&@( (@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@%%%%% %%%%@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@( (@@@@@@@@@@@@@@@@@( (@%%%* *%%%%%* *%%@@(. @@@@@@@@@@@@@@@@@@( (@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@ @@%%% %%% %%% %%@@ @@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@( (@@@@@@@@( (&%%%%%* *%%%***%%%* *%%%&@@( (@@@@@@@@@( (@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@%%%%%%%%%% %%%%%%%%%@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@ @@ (@&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&@@@ .(@@@ @@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@, , ,@ ,, @ @@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@ .. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.. @@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@ * * * * * * * * * * * @@@@@@@@@@@@
// @@@@@@@@@@@@@@@% @@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@% @@@@@@@@ @@@@@@@@@ @@@@@@@@ @@@@@@@@@%@@@@@@@@ @@@@@@@@ %@@@@@@@@ @@@@@@@@ %@@@@@@@@% @@@@@@@@@@@@@@@
// @@@@@@@@@@@@@ @@(((((@ @@(((((@@ @@((((@@ @@(((((@@%@@((((@@ @@(((((@ %@#((((@@ @@((((@@ %@(((((@@% @@@@@@@@@@@@
// @@@@@@@@@@@@@ . @@(@@@(@ @@(@@@(@@ @@@@@@@@ @@(@@@(@@%@@@@@(@@ @@(@@@(@ %@(@@@(@@ @@@@@@@@ %@(@@@(@@%/ @@@@@@@@@@@@@
// @@@@@@@@@@@@@* ( @ */ @ @@ */. @ @ **. @ @@ */ @@%@ **. @ @ */ @ %@ */. @ @ **. @ %@ */ @@%. @@@@@@@@@@@@@
// @@@@@@@@@@@@@ @ @& @ && @ @& @ @& @% @& @ @ @& % && @ @& % @& @% @@@@@@@@@@@@@
// @@@@@@@@@@@@@ **. @@((((#@*@@((((#@@*@@((((@@*@@((((#@@%@@(((#@@*@@((((#@*%@((((#@@*@@((((@@*%@((((#@@%# *@@@@@@@@@@@@@
// @@@@@@@@@@@@@ @@@@@@@@ @@@@@@@@@ @@@@@@@@ @@@@@@@@@%@@@@@@@@ @@@@@@@@ %@@@@@@@@ @@@@@@@@ %@@@@@@@@% @@@@@@@@@@@@@
// @@@@@@@@@@@@@ . . &&&&&&&&*&&&&&&&&&*********/************///****//***((/*******/**%&&&&&&&&*%&&&&&&&&%* *@@@@@@@@@@@@@
// @@@@@@@@@@@@@ / @@@@@@@@ @@@@@@@@@ %%%%%%%%%. , % , %%%%%%%% %@@@@@@@@ %@@@@@@@@%, @@@@@@@@@@@@@
// @@@@@@@@@@@@@ @@ (@([email protected] @@ #@@[email protected]@ . %%%%%%. . .(((((((((( . %%%%% %@@(@@(@@ %@ @@([email protected]@%. @@@@@@@@@@@@@
// @@@@@@@@@@@@@ @ ( @ @@ *( @ %%%% [email protected]@@@@@@@@@@@@@@@@@ ,.%%% %@ * @ %@ ( @@%% %@@@@@@@@@@@@@
// @@@@@@@@@@@@@* * @ (( [email protected] (/ @. %# (@@@@@@@@@@@@@@@@@@@@@@@(( ,.% % (/ .% (( @% @@@@@@@@@@@@@
// @@@@@@@@@@@@@ , @@ ** @*@@ ** @@* , @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ . %@@ ** @@*%@ ** @@% @@@@@@@@@@@@@
// @@@@@@@@@@@@@ . , @@@@@@@@*@@@@@@@@@* / (@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ . %@@@@@@@@*%@@@@@@@@%* [email protected]@@@@@@@@@@@@
// @@@@@@@@@@@@@ %%%%%%%%%%%%%%%%%%% % [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ %%%%%%%%%%%%%%%%%%%% @@@@@@@@@@@@
// @@@@@@@@@@@@@**** @@@@@@@@ @@@@@@@@@ ****% @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ *****%@@@@@@@@ %@@@@@@@@%*****@@@@@@@@@@@@
// @@@@@@@@@@@@@ / @@* (@ @@ @@ , % @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ % %@@ @@ %@* (@@%% %@@@@@@@@@@@@@
// @@@@@@@@@@@@@ . @(/(%(/@ @@/(%(/#@ % @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ %@(((((#@ %@/(%(/@@%. @@@@@@@@@@@@@
// @@@@@@@@@@@@@% % @ ( @ @@ *( @ % % @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ %@ * @ %@ ( @@%, @@@@@@@@@@@@@
// @@@@@@@@@@@@@ @ @& ([email protected]( && @. % @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * %( @& (.%( @& (@%* *@@@@@@@@@@@@@
// @@@@@@@@@@@@@ %% @@@@@@@@*@@@@@@@@@* % % @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ %@@@@@@@@*%@@@@@@@@% @@@@@@@@@@@@@
// @@@@@@@@@@@@@ , &&&&&&&&*&&&&&&&&&* % @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ** %&&@@@&&&*%&&&&&&&&%( *@@@@@@@@@@@@@
// @@@@@@@@@@@@@ , @@@@@@@@ @@@@@@@@@ % @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ %@@@@@@@@ %@@@@@@@@% @@@@@@@@@@@@@
// @@@@@@@@@@@@@* * @@@@@@@@ @@@@@@@@@ ** (% @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ %@@((((@@ %@@(((@@@%. @@@@@@@@@@@@@
// @@@@@@@@@@@@@ , @@ @@@*@ @@ @@@*@@ % @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ % %@@@@@@@@ %@ @@@*@@%% %@@@@@@@@@@@@@
// @@@@@@@@@@@@@ **. @ ** @ @@ **, @ * % @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ %@ **, @ %@ ** @@% @@@@@@@@@@@@@
// @@@@@@@@@@@@@ . @ @@ @ @& @ % @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ % % @& % @@ @%, @@@@@@@@@@@@@
// @@@@@@@@@@@@@ . @@(##((@*@@((##(@@* % @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * *%@@(##(@@*%@(##((@@% @@@@@@@@@@@@@
// @@@@@@@@@@@@@ @@@@@@@@*@@@@@@@@@* % %% @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ %@@@@@@@@*%@@@@@@@@% , @@@@@@@@@@@@@
// @@@@@@@@@@@@@,..( %%%%%%%%%%%%%%%%%%% % @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ %%%%%%%%%%%%%%%%%%%, [email protected]@@@@@@@@@@@@
// @@@@@@@@@@@@@...( .................. . % @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ .... , .....([email protected]@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//
// Forgotten Runes Gate to The Seventh Realm
// https://forgottenrunes.com
// Twitter: @forgottenrunes
pragma solidity ^0.8.0;
import '../util/Ownablearama.sol';
import '../interfaces/IBookOfLore.sol';
import './interfaces/IBeastsAuctionHouse.sol';
import '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol';
import '@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol';
import '@openzeppelin/contracts/utils/cryptography/MerkleProof.sol';
interface IMintable {
function mint(address recipient, uint256 tokenId) external;
}
contract GateToTheSeventhRealmMinter is Ownablearama, ReentrancyGuard, EIP712 {
/// @notice The start block for minting
uint256 public startBlock =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/// @notice The Merkle root for keyholders
bytes32 public keysMerkleRoot;
/// @notice The Merkle root for spellholders
bytes32 public spellsMerkleRoot;
/// @notice The number of locks on this gate
uint256 public constant NUM_LOCKS = 21;
/// @notice The number of locks unlocked
uint256 public numUnlocked = 0;
/// @notice The address to the Book of Lore
address public bookOfLoreAddress;
/// @notice The address of the Wizards contract
address public wizardsAddress;
/// @notice The address of the Souls contract
address public soulsAddress;
/// @notice The address to the Gate of the Seventh Realm token contract
address public gateOfTheSeventhRealmAddress;
/// @notice The address to the Beasts Auction House token contract
address public auctionHouseAddress;
/// @notice The EIP-712 typehash for the unlock struct used by the contract
bytes32 public constant UNLOCK_TYPEHASH =
keccak256('Unlock(address ownerA,uint256 wizardIdA,address ownerB)');
/// @notice A mapping of the addresses of those who participated in the unlock ceremony
mapping(address => bool) public unlockers;
/// @notice A mapping of wizard (or soul) IDs who participated in the unlock ceremony
mapping(uint256 => bool) public unlockerWizards;
/// @notice The Unlock event is emitted when a lock is unlocked
event Unlocked(
address wizA,
uint256 tokenIdA,
address wizB,
uint256 tokenIdB,
uint256 lockIdx
);
/**
* @dev Create the contract and set initial configuration
* @param _bookOfLoreAddress address to the Book of Lore
* @param _wizardsAddress address to the Wizards token
* @param _soulsAddress address to the Souls token
*/
constructor(
address _bookOfLoreAddress,
address _wizardsAddress,
address _soulsAddress
) EIP712('GateToTheSeventhRealmMinter', '1') {
setBookOfLoreAddress(_bookOfLoreAddress);
setWizardsAddress(_wizardsAddress);
setSoulsAddress(_soulsAddress);
}
/**
* @dev Convenient way to initialize the post-constructor configuration
*/
function initialize(
uint256 newStartBlock,
bytes32 newKeysMerkleRoot,
bytes32 newSpellsMerkleRoot,
address newGateOfTheSeventhRealmAddress,
address newAuctionHouseAddress
) public onlyOwner {
setStartBlock(newStartBlock);
setKeysMerkleRoot(newKeysMerkleRoot);
setSpellsMerkleRoot(newSpellsMerkleRoot);
setGateOfTheSeventhRealmAddress(newGateOfTheSeventhRealmAddress);
setAuctionHouseAddress(newAuctionHouseAddress);
}
/**
* @notice Returns if the minting has started
* @return bool if the minting has started
*/
function started() public view returns (bool) {
return block.number >= startBlock;
}
/**
* @notice Unlock a lock from the gate
* @dev Unlocking the gate is a collaboration between two wizards: one with a key and one with a spell. ownerA signs a message and gives that signature to ownerB. ownerB must be the msg.sender. The frontend needs to submit proper proofs matching wizard A and B with a key or spell - this means the frontend needs to know a mapping of wizard (or soul) ids to keys and spells.
* @param ownerA address the partner's address and signer of `signatureA`
* @param wizIdA uint256 the ID of the partner's wizard
* @param wizIdB uint256 the ID of the sender's wizard
* @param wizAMerkleProof bytes32 the proof that wizIdA holds a key or a spell
* @param wizBMerkleProof bytes32 the proof that wizIdB holds a key or a spell
* @param signatureA bytes the signature from the partner
*/
function unlock(
address ownerA,
uint256 wizIdA,
uint256 wizIdB,
bytes32[] calldata wizAMerkleProof,
bytes32[] calldata wizBMerkleProof,
bytes memory signatureA
) public nonReentrant {
require(started(), 'Not started');
require(numUnlocked < NUM_LOCKS, 'Already unlocked');
require(_ownsWizardOrSoul(ownerA, wizIdA), 'Invalid Wiz A Owner');
require(_ownsWizardOrSoul(msg.sender, wizIdB), 'Invalid Wiz B Owner');
require(!unlockers[ownerA], 'Partner already unlocked');
require(!unlockers[msg.sender], 'You already unlocked');
require(!unlockerWizards[wizIdA], 'Wizard A already unlocked');
require(!unlockerWizards[wizIdB], 'Wizard B already unlocked');
require(
(_wizardHoldsKey(wizIdA, wizAMerkleProof) &&
_wizardHoldsSpell(wizIdB, wizBMerkleProof)) ||
(_wizardHoldsKey(wizIdB, wizBMerkleProof) &&
_wizardHoldsSpell(wizIdA, wizAMerkleProof)),
'Wizard pairing failed'
);
// construct an expected hash, given the parameters
bytes32 digest = _hashTypedDataV4(
keccak256(abi.encode(UNLOCK_TYPEHASH, ownerA, wizIdA, msg.sender))
);
// now recover the signer from the provided signature
address signer = ECDSA.recover(digest, signatureA);
// make sure the recover extracted a signer, but beware, because this
// can return non-zero for some invalid cases (apparently?)
require(signer != address(0), 'ECDSA: invalid signature');
require(signer == ownerA, 'unlock: signature is not the partner owner');
require(ownerA != msg.sender, 'nice try');
unlockers[msg.sender] = true;
unlockers[ownerA] = true;
unlockerWizards[wizIdA] = true;
unlockerWizards[wizIdB] = true;
IMintable(gateOfTheSeventhRealmAddress).mint(
msg.sender,
numUnlocked * 2
);
IMintable(gateOfTheSeventhRealmAddress).mint(
ownerA,
(numUnlocked * 2) + 1
);
// write the Lore
if (bookOfLoreAddress != address(0)) {
IBookOfLore(bookOfLoreAddress).addLoreWithScribe(
_loreContractAddress(wizIdB),
wizIdB,
0,
false,
''
);
}
emit Unlocked(ownerA, wizIdA, msg.sender, wizIdB, numUnlocked);
numUnlocked += 1;
if (numUnlocked == NUM_LOCKS) {
IBeastsAuctionHouse(auctionHouseAddress).openTheGate();
}
}
function _wizardHoldsSpell(uint256 wizId, bytes32[] calldata _merkleProof)
private
view
returns (bool)
{
return
MerkleProof.verify(
_merkleProof,
spellsMerkleRoot,
keccak256(abi.encodePacked(wizId))
);
}
function _wizardHoldsKey(uint256 wizId, bytes32[] calldata _merkleProof)
private
view
returns (bool)
{
return
MerkleProof.verify(
_merkleProof,
keysMerkleRoot,
keccak256(abi.encodePacked(wizId))
);
}
function _loreContractAddress(uint256 wizId)
private
view
returns (address)
{
try IERC721(wizardsAddress).ownerOf(wizId) returns (address) {
return wizardsAddress;
} catch Error(string memory) {
// try a soul
}
try IERC721(soulsAddress).ownerOf(wizId) returns (address) {
return soulsAddress;
} catch Error(string memory) {
// not soul either
}
return wizardsAddress;
}
function _ownsWizardOrSoul(address owner, uint256 wizId)
private
view
returns (bool)
{
require(owner != address(0), 'invalid owner');
try IERC721(wizardsAddress).ownerOf(wizId) returns (
address wizardOwner
) {
if (wizardOwner == owner) {
return true;
}
} catch Error(string memory) {
// try a soul
}
try IERC721(soulsAddress).ownerOf(wizId) returns (address soulOwner) {
if (soulOwner == owner) {
return true;
}
} catch Error(string memory) {
// not soul either
}
return false;
}
function domainSeparator() external view returns (bytes32) {
return _domainSeparatorV4();
}
/**
* Owner Controls
*/
/**
* @dev Set the start block
* @param newStartBlock uint256 the block to start at
*/
function setStartBlock(uint256 newStartBlock) public onlyOwner {
startBlock = newStartBlock;
}
/**
* @dev Set the merkle root for key-holder IDs
* @param newMerkleRoot bytes32 the merkle root
*/
function setKeysMerkleRoot(bytes32 newMerkleRoot) public onlyOwner {
keysMerkleRoot = newMerkleRoot;
}
/**
* @dev Set the merkle root for spell-holder IDs
* @param newMerkleRoot bytes32 the merkle root
*/
function setSpellsMerkleRoot(bytes32 newMerkleRoot) public onlyOwner {
spellsMerkleRoot = newMerkleRoot;
}
/**
* @dev Set the address of the Gate of the Seventh Realm
* @param newGateOfTheSeventhRealmAddress address the address to the contract
*/
function setGateOfTheSeventhRealmAddress(
address newGateOfTheSeventhRealmAddress
) public onlyOwner {
gateOfTheSeventhRealmAddress = newGateOfTheSeventhRealmAddress;
}
/**
* @dev Set the address of the Auction House
* @param newAuctionHouseAddress address the address to the contract
*/
function setAuctionHouseAddress(address newAuctionHouseAddress)
public
onlyOwner
{
auctionHouseAddress = newAuctionHouseAddress;
}
/**
* @dev Set the address of the Book of Lore contract
* @param newBookOfLoreAddress address the address to the contract
*/
function setBookOfLoreAddress(address newBookOfLoreAddress)
public
onlyOwner
{
bookOfLoreAddress = newBookOfLoreAddress;
}
/**
* @dev Set the address of the Forgotten Runes Wizards Cult tokens
* @param newWizardsAddress address the address to the contract
*/
function setWizardsAddress(address newWizardsAddress) public onlyOwner {
wizardsAddress = newWizardsAddress;
}
/**
* @dev Set the address of Forgotten Souls contract
* @param newSoulsAddress address the address to the contract
*/
function setSoulsAddress(address newSoulsAddress) public onlyOwner {
soulsAddress = newSoulsAddress;
}
/**
* @dev Recover ERC721's accidentally sent to this contract
* @param token IERC721 the address of the token
* @param to address where to send the token
* @param tokenId uint256 the token ID
*/
function transferFrom(
IERC721 token,
address to,
uint256 tokenId
) public onlyOwner {
token.transferFrom(address(this), to, tokenId);
}
/**
* @dev Set approval for an operator to manage our ERC721s, again, for emergencies
* @param token IERC721 the address of the token
* @param operator address the operator's address
* @param approved bool operator approval
*/
function setApprovalForAll(
IERC721 token,
address operator,
bool approved
) public onlyOwner {
token.setApprovalForAll(operator, approved);
}
function __remove(address unlocker, uint256 tokenId) public onlyOwner {
delete unlockers[unlocker];
delete unlockerWizards[tokenId];
}
}
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
/**
* @dev This implements Ownable plus a few utilities
*/
contract Ownablearama is Ownable {
/**
* @dev ETH should not be sent to this contract, but in the case that it is
* sent by accident, this function allows the owner to withdraw it.
*/
function withdrawAll() public payable onlyOwner {
require(payable(msg.sender).send(address(this).balance));
}
/**
* @dev Again, ERC20s should not be sent to this contract, but if someone
* does, it's nice to be able to recover them
* @param token IERC20 the token address
* @param amount uint256 the amount to send
*/
function forwardERC20s(IERC20 token, uint256 amount) public onlyOwner {
require(address(msg.sender) != address(0));
token.transfer(msg.sender, amount);
}
// disable renouncing ownership
function renounceOwnership() public override onlyOwner {}
}
interface IBookOfLore {
function addLoreWithScribe(
address tokenContract,
uint256 tokenId,
uint256 parentLoreId,
bool nsfw,
string memory loreMetadataURI
) external;
function addLore(
address tokenContract,
uint256 tokenId,
uint256 parentLoreId,
bool nsfw,
string memory loreMetadataURI
) external;
}
// SPDX-License-Identifier: GPL-3.0
/// @title Interface for Beasts Auction Houses
pragma solidity ^0.8.6;
interface IBeastsAuctionHouse {
struct Auction {
// ID for the Beast (ERC721 token ID)
uint256 beastId;
// The current highest bid amount
uint256 amount;
// The time that the auction started
uint256 startTime;
// The time that the auction is scheduled to end
uint256 endTime;
// The address of the current highest bid
address payable bidder;
// Whether or not the auction has been settled
bool settled;
}
event AuctionCreated(
uint256 indexed beastId,
uint256 startTime,
uint256 endTime
);
event AuctionBid(
uint256 indexed beastId,
address sender,
uint256 value,
bool extended
);
event AuctionExtended(uint256 indexed beastId, uint256 endTime);
event AuctionSettled(
uint256 indexed beastId,
address winner,
uint256 amount
);
event AuctionTimeBufferUpdated(uint256 timeBuffer);
event AuctionReservePriceUpdated(uint256 reservePrice);
event AuctionMinBidIncrementPercentageUpdated(
uint256 minBidIncrementPercentage
);
function settleAuction() external;
function settleCurrentAndCreateNewAuction() external;
function createBid(uint256 beastId) external payable;
function pause() external;
function unpause() external;
function openTheGate() external;
function setTimeBuffer(uint256 timeBuffer) external;
function setReservePrice(uint256 reservePrice) external;
function setMinBidIncrementPercentage(uint8 minBidIncrementPercentage)
external;
function setTreasury(address newTreasury) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../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;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return recover(hash, r, vs);
} else {
revert("ECDSA: invalid signature length");
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(
uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"ECDSA: invalid signature 's' value"
);
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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;
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);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @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: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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;
/*
* @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 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 Unlock a lock from the gate @dev Unlocking the gate is a collaboration between two wizards: one with a key and one with a spell. ownerA signs a message and gives that signature to ownerB. ownerB must be the msg.sender. The frontend needs to submit proper proofs matching wizard A and B with a key or spell - this means the frontend needs to know a mapping of wizard (or soul) ids to keys and spells. @param ownerA address the partner's address and signer of `signatureA` @param wizIdA uint256 the ID of the partner's wizard @param wizIdB uint256 the ID of the sender's wizard @param wizAMerkleProof bytes32 the proof that wizIdA holds a key or a spell @param wizBMerkleProof bytes32 the proof that wizIdB holds a key or a spell @param signatureA bytes the signature from the partner/ construct an expected hash, given the parameters now recover the signer from the provided signature make sure the recover extracted a signer, but beware, because this can return non-zero for some invalid cases (apparently?) write the Lore | function unlock(
address ownerA,
uint256 wizIdA,
uint256 wizIdB,
bytes32[] calldata wizAMerkleProof,
bytes32[] calldata wizBMerkleProof,
bytes memory signatureA
) public nonReentrant {
require(started(), 'Not started');
require(numUnlocked < NUM_LOCKS, 'Already unlocked');
require(_ownsWizardOrSoul(ownerA, wizIdA), 'Invalid Wiz A Owner');
require(_ownsWizardOrSoul(msg.sender, wizIdB), 'Invalid Wiz B Owner');
require(!unlockers[ownerA], 'Partner already unlocked');
require(!unlockers[msg.sender], 'You already unlocked');
require(!unlockerWizards[wizIdA], 'Wizard A already unlocked');
require(!unlockerWizards[wizIdB], 'Wizard B already unlocked');
require(
(_wizardHoldsKey(wizIdA, wizAMerkleProof) &&
_wizardHoldsSpell(wizIdB, wizBMerkleProof)) ||
(_wizardHoldsKey(wizIdB, wizBMerkleProof) &&
_wizardHoldsSpell(wizIdA, wizAMerkleProof)),
'Wizard pairing failed'
);
bytes32 digest = _hashTypedDataV4(
keccak256(abi.encode(UNLOCK_TYPEHASH, ownerA, wizIdA, msg.sender))
);
address signer = ECDSA.recover(digest, signatureA);
require(signer != address(0), 'ECDSA: invalid signature');
require(signer == ownerA, 'unlock: signature is not the partner owner');
require(ownerA != msg.sender, 'nice try');
unlockers[msg.sender] = true;
unlockers[ownerA] = true;
unlockerWizards[wizIdA] = true;
unlockerWizards[wizIdB] = true;
IMintable(gateOfTheSeventhRealmAddress).mint(
msg.sender,
numUnlocked * 2
);
IMintable(gateOfTheSeventhRealmAddress).mint(
ownerA,
(numUnlocked * 2) + 1
);
if (bookOfLoreAddress != address(0)) {
IBookOfLore(bookOfLoreAddress).addLoreWithScribe(
_loreContractAddress(wizIdB),
wizIdB,
0,
false,
''
);
}
emit Unlocked(ownerA, wizIdA, msg.sender, wizIdB, numUnlocked);
numUnlocked += 1;
if (numUnlocked == NUM_LOCKS) {
IBeastsAuctionHouse(auctionHouseAddress).openTheGate();
}
}
| 332,061 | [
1,
7087,
279,
2176,
628,
326,
12611,
225,
3967,
310,
326,
12611,
353,
279,
21326,
22226,
3086,
2795,
24204,
87,
30,
1245,
598,
279,
498,
471,
1245,
598,
279,
22377,
18,
3410,
37,
21588,
279,
883,
471,
14758,
716,
3372,
358,
3410,
38,
18,
3410,
38,
1297,
506,
326,
1234,
18,
15330,
18,
1021,
15442,
4260,
358,
4879,
5338,
14601,
87,
3607,
24204,
432,
471,
605,
598,
279,
498,
578,
22377,
300,
333,
4696,
326,
15442,
4260,
358,
5055,
279,
2874,
434,
24204,
261,
280,
272,
1003,
13,
3258,
358,
1311,
471,
22377,
87,
18,
225,
3410,
37,
1758,
326,
19170,
1807,
1758,
471,
10363,
434,
1375,
8195,
37,
68,
225,
341,
452,
548,
37,
2254,
5034,
326,
1599,
434,
326,
19170,
1807,
24204,
225,
341,
452,
548,
38,
2254,
5034,
326,
1599,
434,
326,
5793,
1807,
24204,
225,
341,
452,
2192,
264,
15609,
20439,
1731,
1578,
326,
14601,
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,
203,
3639,
1758,
3410,
37,
16,
203,
3639,
2254,
5034,
341,
452,
548,
37,
16,
203,
3639,
2254,
5034,
341,
452,
548,
38,
16,
203,
3639,
1731,
1578,
8526,
745,
892,
341,
452,
2192,
264,
15609,
20439,
16,
203,
3639,
1731,
1578,
8526,
745,
892,
341,
452,
38,
8478,
15609,
20439,
16,
203,
3639,
1731,
3778,
3372,
37,
203,
565,
262,
1071,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
12,
14561,
9334,
296,
1248,
5746,
8284,
203,
3639,
2583,
12,
2107,
7087,
329,
411,
9443,
67,
6589,
55,
16,
296,
9430,
25966,
8284,
203,
3639,
2583,
24899,
995,
87,
27130,
1162,
55,
1003,
12,
8443,
37,
16,
341,
452,
548,
37,
3631,
296,
1941,
678,
452,
432,
16837,
8284,
203,
3639,
2583,
24899,
995,
87,
27130,
1162,
55,
1003,
12,
3576,
18,
15330,
16,
341,
452,
548,
38,
3631,
296,
1941,
678,
452,
605,
16837,
8284,
203,
3639,
2583,
12,
5,
26226,
414,
63,
8443,
37,
6487,
296,
1988,
1224,
1818,
25966,
8284,
203,
3639,
2583,
12,
5,
26226,
414,
63,
3576,
18,
15330,
6487,
296,
6225,
1818,
25966,
8284,
203,
3639,
2583,
12,
5,
26226,
264,
27130,
87,
63,
91,
452,
548,
37,
6487,
296,
27130,
432,
1818,
25966,
8284,
203,
3639,
2583,
12,
5,
26226,
264,
27130,
87,
63,
91,
452,
548,
38,
6487,
296,
27130,
605,
1818,
25966,
8284,
203,
203,
3639,
2583,
12,
203,
5411,
261,
67,
31837,
20586,
87,
653,
12,
91,
452,
548,
37,
16,
341,
452,
2192,
264,
15609,
20439,
13,
597,
2
]
|
./full_match/137/0x61ff724E829FA52D5Cc7D74324437E6bD1d0ce56/sources/KlimaZap_flat.sol | * @dev Unstake KLIMA tokens from msg.sender, to this contract/ | function unstakeKLIMA() internal {
uint256 balancesKLIMA = IERC20(sKLIMA).balanceOf(msg.sender);
require(balancesKLIMA > 0, "KLIMAZap : 0 sKLIMA to unstake");
IERC20(sKLIMA).safeTransferFrom(msg.sender, address(this), balancesKLIMA);
IKLIMAStaking(KLIMAStaking).unstake(balancesKLIMA,false);
}
| 4,672,413 | [
1,
984,
334,
911,
1475,
2053,
5535,
2430,
628,
1234,
18,
15330,
16,
358,
333,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
640,
334,
911,
47,
2053,
5535,
1435,
2713,
288,
203,
3639,
2254,
5034,
324,
26488,
47,
2053,
5535,
273,
467,
654,
39,
3462,
12,
87,
47,
2053,
5535,
2934,
12296,
951,
12,
3576,
18,
15330,
1769,
203,
3639,
2583,
12,
70,
26488,
47,
2053,
5535,
405,
374,
16,
315,
47,
2053,
5535,
62,
438,
294,
374,
272,
47,
2053,
5535,
358,
640,
334,
911,
8863,
203,
203,
3639,
467,
654,
39,
3462,
12,
87,
47,
2053,
5535,
2934,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
324,
26488,
47,
2053,
5535,
1769,
203,
203,
3639,
467,
47,
2053,
5535,
510,
6159,
12,
47,
2053,
5535,
510,
6159,
2934,
23412,
911,
12,
70,
26488,
47,
2053,
5535,
16,
5743,
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
]
|
pragma solidity ^0.4.24;
// 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.
*/
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: 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: contracts/controller/Reputation.sol
/**
* @title Reputation system
* @dev A DAO has Reputation System which allows peers to rate other peers in order to build trust .
* A reputation is use to assign influence measure to a DAO'S peers.
* Reputation is similar to regular tokens but with one crucial difference: It is non-transferable.
* The Reputation contract maintain a map of address to reputation value.
* It provides an onlyOwner functions to mint and burn reputation _to (or _from) a specific address.
*/
contract Reputation is Ownable {
using SafeMath for uint;
mapping (address => uint256) public balances;
uint256 public totalSupply;
uint public decimals = 18;
// Event indicating minting of reputation to an address.
event Mint(address indexed _to, uint256 _amount);
// Event indicating burning of reputation for an address.
event Burn(address indexed _from, uint256 _amount);
/**
* @dev return the reputation amount of a given owner
* @param _owner an address of the owner which we want to get his reputation
*/
function reputationOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Generates `_amount` of reputation that are assigned to `_to`
* @param _to The address that will be assigned the new reputation
* @param _amount The quantity of reputation to be generated
* @return True if the reputation are generated correctly
*/
function mint(address _to, uint _amount)
public
onlyOwner
returns (bool)
{
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
return true;
}
/**
* @dev Burns `_amount` of reputation from `_from`
* if _amount tokens to burn > balances[_from] the balance of _from will turn to zero.
* @param _from The address that will lose the reputation
* @param _amount The quantity of reputation to burn
* @return True if the reputation are burned correctly
*/
function burn(address _from, uint _amount)
public
onlyOwner
returns (bool)
{
uint amountMinted = _amount;
if (balances[_from] < _amount) {
amountMinted = balances[_from];
}
totalSupply = totalSupply.sub(amountMinted);
balances[_from] = balances[_from].sub(amountMinted);
emit Burn(_from, amountMinted);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: 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) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: 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: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @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
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.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() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
// File: contracts/token/ERC827/ERC827.sol
/**
* @title ERC827 interface, an extension of ERC20 token standard
*
* @dev Interface of a ERC827 token, following the ERC20 standard with extra
* methods to transfer value and data and execute calls in transfers and
* approvals.
*/
contract ERC827 is ERC20 {
function approveAndCall(address _spender,uint256 _value,bytes _data) public payable returns(bool);
function transferAndCall(address _to,uint256 _value,bytes _data) public payable returns(bool);
function transferFromAndCall(address _from,address _to,uint256 _value,bytes _data) public payable returns(bool);
}
// File: contracts/token/ERC827/ERC827Token.sol
/* solium-disable security/no-low-level-calls */
pragma solidity ^0.4.24;
/**
* @title ERC827, an extension of ERC20 token standard
*
* @dev Implementation the ERC827, following the ERC20 standard with extra
* methods to transfer value and data and execute calls in transfers and
* approvals. Uses OpenZeppelin StandardToken.
*/
contract ERC827Token is ERC827, StandardToken {
/**
* @dev Addition to ERC20 token methods. It allows to
* approve the transfer of value and execute a call with the sent data.
* Beware that changing an allowance with this method brings the risk that
* someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race condition
* is to first reduce the spender's allowance to 0 and set the desired value
* afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address that will spend the funds.
* @param _value The amount of tokens to be spent.
* @param _data ABI-encoded contract call to call `_spender` address.
* @return true if the call function was executed successfully
*/
function approveAndCall(
address _spender,
uint256 _value,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.approve(_spender, _value);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to ERC20 token methods. Transfer tokens to a specified
* address and execute a call with the sent data on the same transaction
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
* @param _data ABI-encoded contract call to call `_to` address.
* @return true if the call function was executed successfully
*/
function transferAndCall(
address _to,
uint256 _value,
bytes _data
)
public
payable
returns (bool)
{
require(_to != address(this));
super.transfer(_to, _value);
// solium-disable-next-line security/no-call-value
require(_to.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to ERC20 token methods. Transfer tokens from one address to
* another and make a contract call on the same transaction
* @param _from The address which you want to send tokens from
* @param _to The address which you want to transfer to
* @param _value The amout of tokens to be transferred
* @param _data ABI-encoded contract call to call `_to` address.
* @return true if the call function was executed successfully
*/
function transferFromAndCall(
address _from,
address _to,
uint256 _value,
bytes _data
)
public payable returns (bool)
{
require(_to != address(this));
super.transferFrom(_from, _to, _value);
// solium-disable-next-line security/no-call-value
require(_to.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to StandardToken methods. Increase the amount of tokens that
* an owner allowed to a spender and execute a call with the sent data.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function increaseApprovalAndCall(
address _spender,
uint _addedValue,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.increaseApproval(_spender, _addedValue);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to StandardToken methods. Decrease the amount of tokens that
* an owner allowed to a spender and execute a call with the sent data.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function decreaseApprovalAndCall(
address _spender,
uint _subtractedValue,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.decreaseApproval(_spender, _subtractedValue);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
}
// File: contracts/controller/DAOToken.sol
/**
* @title DAOToken, base on zeppelin contract.
* @dev ERC20 compatible token. It is a mintable, destructible, burnable token.
*/
contract DAOToken is ERC827Token,MintableToken,BurnableToken {
string public name;
string public symbol;
// solium-disable-next-line uppercase
uint8 public constant decimals = 18;
uint public cap;
/**
* @dev Constructor
* @param _name - token name
* @param _symbol - token symbol
* @param _cap - token cap - 0 value means no cap
*/
constructor(string _name, string _symbol,uint _cap) public {
name = _name;
symbol = _symbol;
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) {
if (cap > 0)
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
// File: contracts/controller/Avatar.sol
/**
* @title An Avatar holds tokens, reputation and ether for a controller
*/
contract Avatar is Ownable {
bytes32 public orgName;
DAOToken public nativeToken;
Reputation public nativeReputation;
event GenericAction(address indexed _action, bytes32[] _params);
event SendEther(uint _amountInWei, address indexed _to);
event ExternalTokenTransfer(address indexed _externalToken, address indexed _to, uint _value);
event ExternalTokenTransferFrom(address indexed _externalToken, address _from, address _to, uint _value);
event ExternalTokenIncreaseApproval(StandardToken indexed _externalToken, address _spender, uint _addedValue);
event ExternalTokenDecreaseApproval(StandardToken indexed _externalToken, address _spender, uint _subtractedValue);
event ReceiveEther(address indexed _sender, uint _value);
/**
* @dev the constructor takes organization name, native token and reputation system
and creates an avatar for a controller
*/
constructor(bytes32 _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public {
orgName = _orgName;
nativeToken = _nativeToken;
nativeReputation = _nativeReputation;
}
/**
* @dev enables an avatar to receive ethers
*/
function() public payable {
emit ReceiveEther(msg.sender, msg.value);
}
/**
* @dev perform a generic call to an arbitrary contract
* @param _contract the contract's address to call
* @param _data ABI-encoded contract call to call `_contract` address.
* @return the return bytes of the called contract's function.
*/
function genericCall(address _contract,bytes _data) public onlyOwner {
// solium-disable-next-line security/no-low-level-calls
bool result = _contract.call(_data);
// solium-disable-next-line security/no-inline-assembly
assembly {
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// call returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
/**
* @dev send ethers from the avatar's wallet
* @param _amountInWei amount to send in Wei units
* @param _to send the ethers to this address
* @return bool which represents success
*/
function sendEther(uint _amountInWei, address _to) public onlyOwner returns(bool) {
_to.transfer(_amountInWei);
emit SendEther(_amountInWei, _to);
return true;
}
/**
* @dev external token transfer
* @param _externalToken the token contract
* @param _to the destination address
* @param _value the amount of tokens to transfer
* @return bool which represents success
*/
function externalTokenTransfer(StandardToken _externalToken, address _to, uint _value)
public onlyOwner returns(bool)
{
_externalToken.transfer(_to, _value);
emit ExternalTokenTransfer(_externalToken, _to, _value);
return true;
}
/**
* @dev external token transfer from a specific account
* @param _externalToken the token contract
* @param _from the account to spend token from
* @param _to the destination address
* @param _value the amount of tokens to transfer
* @return bool which represents success
*/
function externalTokenTransferFrom(
StandardToken _externalToken,
address _from,
address _to,
uint _value
)
public onlyOwner returns(bool)
{
_externalToken.transferFrom(_from, _to, _value);
emit ExternalTokenTransferFrom(_externalToken, _from, _to, _value);
return true;
}
/**
* @dev increase approval for the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _addedValue the amount of ether (in Wei) which the approval is referring to.
* @return bool which represents a success
*/
function externalTokenIncreaseApproval(StandardToken _externalToken, address _spender, uint _addedValue)
public onlyOwner returns(bool)
{
_externalToken.increaseApproval(_spender, _addedValue);
emit ExternalTokenIncreaseApproval(_externalToken, _spender, _addedValue);
return true;
}
/**
* @dev decrease approval for the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _subtractedValue the amount of ether (in Wei) which the approval is referring to.
* @return bool which represents a success
*/
function externalTokenDecreaseApproval(StandardToken _externalToken, address _spender, uint _subtractedValue )
public onlyOwner returns(bool)
{
_externalToken.decreaseApproval(_spender, _subtractedValue);
emit ExternalTokenDecreaseApproval(_externalToken,_spender, _subtractedValue);
return true;
}
}
// File: contracts/globalConstraints/GlobalConstraintInterface.sol
contract GlobalConstraintInterface {
enum CallPhase { Pre, Post,PreAndPost }
function pre( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function post( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
/**
* @dev when return if this globalConstraints is pre, post or both.
* @return CallPhase enum indication Pre, Post or PreAndPost.
*/
function when() public returns(CallPhase);
}
// File: contracts/controller/ControllerInterface.sol
/**
* @title Controller contract
* @dev A controller controls the organizations tokens ,reputation and avatar.
* It is subject to a set of schemes and constraints that determine its behavior.
* Each scheme has it own parameters and operation permissions.
*/
interface ControllerInterface {
/**
* @dev Mint `_amount` of reputation that are assigned to `_to` .
* @param _amount amount of reputation to mint
* @param _to beneficiary address
* @return bool which represents a success
*/
function mintReputation(uint256 _amount, address _to,address _avatar)
external
returns(bool);
/**
* @dev Burns `_amount` of reputation from `_from`
* @param _amount amount of reputation to burn
* @param _from The address that will lose the reputation
* @return bool which represents a success
*/
function burnReputation(uint256 _amount, address _from,address _avatar)
external
returns(bool);
/**
* @dev mint tokens .
* @param _amount amount of token to mint
* @param _beneficiary beneficiary address
* @param _avatar address
* @return bool which represents a success
*/
function mintTokens(uint256 _amount, address _beneficiary,address _avatar)
external
returns(bool);
/**
* @dev register or update a scheme
* @param _scheme the address of the scheme
* @param _paramsHash a hashed configuration of the usage of the scheme
* @param _permissions the permissions the new scheme will have
* @param _avatar address
* @return bool which represents a success
*/
function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions,address _avatar)
external
returns(bool);
/**
* @dev unregister a scheme
* @param _avatar address
* @param _scheme the address of the scheme
* @return bool which represents a success
*/
function unregisterScheme(address _scheme,address _avatar)
external
returns(bool);
/**
* @dev unregister the caller's scheme
* @param _avatar address
* @return bool which represents a success
*/
function unregisterSelf(address _avatar) external returns(bool);
function isSchemeRegistered( address _scheme,address _avatar) external view returns(bool);
function getSchemeParameters(address _scheme,address _avatar) external view returns(bytes32);
function getGlobalConstraintParameters(address _globalConstraint,address _avatar) external view returns(bytes32);
function getSchemePermissions(address _scheme,address _avatar) external view returns(bytes4);
/**
* @dev globalConstraintsCount return the global constraint pre and post count
* @return uint globalConstraintsPre count.
* @return uint globalConstraintsPost count.
*/
function globalConstraintsCount(address _avatar) external view returns(uint,uint);
function isGlobalConstraintRegistered(address _globalConstraint,address _avatar) external view returns(bool);
/**
* @dev add or update Global Constraint
* @param _globalConstraint the address of the global constraint to be added.
* @param _params the constraint parameters hash.
* @param _avatar the avatar of the organization
* @return bool which represents a success
*/
function addGlobalConstraint(address _globalConstraint, bytes32 _params,address _avatar)
external returns(bool);
/**
* @dev remove Global Constraint
* @param _globalConstraint the address of the global constraint to be remove.
* @param _avatar the organization avatar.
* @return bool which represents a success
*/
function removeGlobalConstraint (address _globalConstraint,address _avatar)
external returns(bool);
/**
* @dev upgrade the Controller
* The function will trigger an event 'UpgradeController'.
* @param _newController the address of the new controller.
* @param _avatar address
* @return bool which represents a success
*/
function upgradeController(address _newController,address _avatar)
external returns(bool);
/**
* @dev perform a generic call to an arbitrary contract
* @param _contract the contract's address to call
* @param _data ABI-encoded contract call to call `_contract` address.
* @param _avatar the controller's avatar address
* @return bytes32 - the return value of the called _contract's function.
*/
function genericCall(address _contract,bytes _data,address _avatar)
external
returns(bytes32);
/**
* @dev send some ether
* @param _amountInWei the amount of ether (in Wei) to send
* @param _to address of the beneficiary
* @param _avatar address
* @return bool which represents a success
*/
function sendEther(uint _amountInWei, address _to,address _avatar)
external returns(bool);
/**
* @dev send some amount of arbitrary ERC20 Tokens
* @param _externalToken the address of the Token Contract
* @param _to address of the beneficiary
* @param _value the amount of ether (in Wei) to send
* @param _avatar address
* @return bool which represents a success
*/
function externalTokenTransfer(StandardToken _externalToken, address _to, uint _value,address _avatar)
external
returns(bool);
/**
* @dev transfer token "from" address "to" address
* One must to approve the amount of tokens which can be spend from the
* "from" account.This can be done using externalTokenApprove.
* @param _externalToken the address of the Token Contract
* @param _from address of the account to send from
* @param _to address of the beneficiary
* @param _value the amount of ether (in Wei) to send
* @param _avatar address
* @return bool which represents a success
*/
function externalTokenTransferFrom(StandardToken _externalToken, address _from, address _to, uint _value,address _avatar)
external
returns(bool);
/**
* @dev increase approval for the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _addedValue the amount of ether (in Wei) which the approval is referring to.
* @param _avatar address
* @return bool which represents a success
*/
function externalTokenIncreaseApproval(StandardToken _externalToken, address _spender, uint _addedValue,address _avatar)
external
returns(bool);
/**
* @dev decrease approval for the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _subtractedValue the amount of ether (in Wei) which the approval is referring to.
* @param _avatar address
* @return bool which represents a success
*/
function externalTokenDecreaseApproval(StandardToken _externalToken, address _spender, uint _subtractedValue,address _avatar)
external
returns(bool);
/**
* @dev getNativeReputation
* @param _avatar the organization avatar.
* @return organization native reputation
*/
function getNativeReputation(address _avatar)
external
view
returns(address);
}
// File: contracts/controller/Controller.sol
/**
* @title Controller contract
* @dev A controller controls the organizations tokens,reputation and avatar.
* It is subject to a set of schemes and constraints that determine its behavior.
* Each scheme has it own parameters and operation permissions.
*/
contract Controller is ControllerInterface {
struct Scheme {
bytes32 paramsHash; // a hash "configuration" of the scheme
bytes4 permissions; // A bitwise flags of permissions,
// All 0: Not registered,
// 1st bit: Flag if the scheme is registered,
// 2nd bit: Scheme can register other schemes
// 3rd bit: Scheme can add/remove global constraints
// 4th bit: Scheme can upgrade the controller
// 5th bit: Scheme can call genericCall on behalf of
// the organization avatar
}
struct GlobalConstraint {
address gcAddress;
bytes32 params;
}
struct GlobalConstraintRegister {
bool isRegistered; //is registered
uint index; //index at globalConstraints
}
mapping(address=>Scheme) public schemes;
Avatar public avatar;
DAOToken public nativeToken;
Reputation public nativeReputation;
// newController will point to the new controller after the present controller is upgraded
address public newController;
// globalConstraintsPre that determine pre conditions for all actions on the controller
GlobalConstraint[] public globalConstraintsPre;
// globalConstraintsPost that determine post conditions for all actions on the controller
GlobalConstraint[] public globalConstraintsPost;
// globalConstraintsRegisterPre indicate if a globalConstraints is registered as a pre global constraint
mapping(address=>GlobalConstraintRegister) public globalConstraintsRegisterPre;
// globalConstraintsRegisterPost indicate if a globalConstraints is registered as a post global constraint
mapping(address=>GlobalConstraintRegister) public globalConstraintsRegisterPost;
event MintReputation (address indexed _sender, address indexed _to, uint256 _amount);
event BurnReputation (address indexed _sender, address indexed _from, uint256 _amount);
event MintTokens (address indexed _sender, address indexed _beneficiary, uint256 _amount);
event RegisterScheme (address indexed _sender, address indexed _scheme);
event UnregisterScheme (address indexed _sender, address indexed _scheme);
event GenericAction (address indexed _sender, bytes32[] _params);
event SendEther (address indexed _sender, uint _amountInWei, address indexed _to);
event ExternalTokenTransfer (address indexed _sender, address indexed _externalToken, address indexed _to, uint _value);
event ExternalTokenTransferFrom (address indexed _sender, address indexed _externalToken, address _from, address _to, uint _value);
event ExternalTokenIncreaseApproval (address indexed _sender, StandardToken indexed _externalToken, address _spender, uint _value);
event ExternalTokenDecreaseApproval (address indexed _sender, StandardToken indexed _externalToken, address _spender, uint _value);
event UpgradeController(address indexed _oldController,address _newController);
event AddGlobalConstraint(address indexed _globalConstraint, bytes32 _params,GlobalConstraintInterface.CallPhase _when);
event RemoveGlobalConstraint(address indexed _globalConstraint ,uint256 _index,bool _isPre);
event GenericCall(address indexed _contract,bytes _data);
constructor( Avatar _avatar) public
{
avatar = _avatar;
nativeToken = avatar.nativeToken();
nativeReputation = avatar.nativeReputation();
schemes[msg.sender] = Scheme({paramsHash: bytes32(0),permissions: bytes4(0x1F)});
}
// Do not allow mistaken calls:
function() external {
revert();
}
// Modifiers:
modifier onlyRegisteredScheme() {
require(schemes[msg.sender].permissions&bytes4(1) == bytes4(1));
_;
}
modifier onlyRegisteringSchemes() {
require(schemes[msg.sender].permissions&bytes4(2) == bytes4(2));
_;
}
modifier onlyGlobalConstraintsScheme() {
require(schemes[msg.sender].permissions&bytes4(4) == bytes4(4));
_;
}
modifier onlyUpgradingScheme() {
require(schemes[msg.sender].permissions&bytes4(8) == bytes4(8));
_;
}
modifier onlyGenericCallScheme() {
require(schemes[msg.sender].permissions&bytes4(16) == bytes4(16));
_;
}
modifier onlySubjectToConstraint(bytes32 func) {
uint idx;
for (idx = 0;idx<globalConstraintsPre.length;idx++) {
require((GlobalConstraintInterface(globalConstraintsPre[idx].gcAddress)).pre(msg.sender,globalConstraintsPre[idx].params,func));
}
_;
for (idx = 0;idx<globalConstraintsPost.length;idx++) {
require((GlobalConstraintInterface(globalConstraintsPost[idx].gcAddress)).post(msg.sender,globalConstraintsPost[idx].params,func));
}
}
modifier isAvatarValid(address _avatar) {
require(_avatar == address(avatar));
_;
}
/**
* @dev Mint `_amount` of reputation that are assigned to `_to` .
* @param _amount amount of reputation to mint
* @param _to beneficiary address
* @return bool which represents a success
*/
function mintReputation(uint256 _amount, address _to,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("mintReputation")
isAvatarValid(_avatar)
returns(bool)
{
emit MintReputation(msg.sender, _to, _amount);
return nativeReputation.mint(_to, _amount);
}
/**
* @dev Burns `_amount` of reputation from `_from`
* @param _amount amount of reputation to burn
* @param _from The address that will lose the reputation
* @return bool which represents a success
*/
function burnReputation(uint256 _amount, address _from,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("burnReputation")
isAvatarValid(_avatar)
returns(bool)
{
emit BurnReputation(msg.sender, _from, _amount);
return nativeReputation.burn(_from, _amount);
}
/**
* @dev mint tokens .
* @param _amount amount of token to mint
* @param _beneficiary beneficiary address
* @return bool which represents a success
*/
function mintTokens(uint256 _amount, address _beneficiary,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("mintTokens")
isAvatarValid(_avatar)
returns(bool)
{
emit MintTokens(msg.sender, _beneficiary, _amount);
return nativeToken.mint(_beneficiary, _amount);
}
/**
* @dev register a scheme
* @param _scheme the address of the scheme
* @param _paramsHash a hashed configuration of the usage of the scheme
* @param _permissions the permissions the new scheme will have
* @return bool which represents a success
*/
function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions,address _avatar)
external
onlyRegisteringSchemes
onlySubjectToConstraint("registerScheme")
isAvatarValid(_avatar)
returns(bool)
{
Scheme memory scheme = schemes[_scheme];
// Check scheme has at least the permissions it is changing, and at least the current permissions:
// Implementation is a bit messy. One must recall logic-circuits ^^
// produces non-zero if sender does not have all of the perms that are changing between old and new
require(bytes4(0x1F)&(_permissions^scheme.permissions)&(~schemes[msg.sender].permissions) == bytes4(0));
// produces non-zero if sender does not have all of the perms in the old scheme
require(bytes4(0x1F)&(scheme.permissions&(~schemes[msg.sender].permissions)) == bytes4(0));
// Add or change the scheme:
schemes[_scheme].paramsHash = _paramsHash;
schemes[_scheme].permissions = _permissions|bytes4(1);
emit RegisterScheme(msg.sender, _scheme);
return true;
}
/**
* @dev unregister a scheme
* @param _scheme the address of the scheme
* @return bool which represents a success
*/
function unregisterScheme( address _scheme,address _avatar)
external
onlyRegisteringSchemes
onlySubjectToConstraint("unregisterScheme")
isAvatarValid(_avatar)
returns(bool)
{
//check if the scheme is registered
if (schemes[_scheme].permissions&bytes4(1) == bytes4(0)) {
return false;
}
// Check the unregistering scheme has enough permissions:
require(bytes4(0x1F)&(schemes[_scheme].permissions&(~schemes[msg.sender].permissions)) == bytes4(0));
// Unregister:
emit UnregisterScheme(msg.sender, _scheme);
delete schemes[_scheme];
return true;
}
/**
* @dev unregister the caller's scheme
* @return bool which represents a success
*/
function unregisterSelf(address _avatar) external isAvatarValid(_avatar) returns(bool) {
if (_isSchemeRegistered(msg.sender,_avatar) == false) {
return false;
}
delete schemes[msg.sender];
emit UnregisterScheme(msg.sender, msg.sender);
return true;
}
function isSchemeRegistered(address _scheme,address _avatar) external isAvatarValid(_avatar) view returns(bool) {
return _isSchemeRegistered(_scheme,_avatar);
}
function getSchemeParameters(address _scheme,address _avatar) external isAvatarValid(_avatar) view returns(bytes32) {
return schemes[_scheme].paramsHash;
}
function getSchemePermissions(address _scheme,address _avatar) external isAvatarValid(_avatar) view returns(bytes4) {
return schemes[_scheme].permissions;
}
function getGlobalConstraintParameters(address _globalConstraint,address) external view returns(bytes32) {
GlobalConstraintRegister memory register = globalConstraintsRegisterPre[_globalConstraint];
if (register.isRegistered) {
return globalConstraintsPre[register.index].params;
}
register = globalConstraintsRegisterPost[_globalConstraint];
if (register.isRegistered) {
return globalConstraintsPost[register.index].params;
}
}
/**
* @dev globalConstraintsCount return the global constraint pre and post count
* @return uint globalConstraintsPre count.
* @return uint globalConstraintsPost count.
*/
function globalConstraintsCount(address _avatar)
external
isAvatarValid(_avatar)
view
returns(uint,uint)
{
return (globalConstraintsPre.length,globalConstraintsPost.length);
}
function isGlobalConstraintRegistered(address _globalConstraint,address _avatar)
external
isAvatarValid(_avatar)
view
returns(bool)
{
return (globalConstraintsRegisterPre[_globalConstraint].isRegistered || globalConstraintsRegisterPost[_globalConstraint].isRegistered);
}
/**
* @dev add or update Global Constraint
* @param _globalConstraint the address of the global constraint to be added.
* @param _params the constraint parameters hash.
* @return bool which represents a success
*/
function addGlobalConstraint(address _globalConstraint, bytes32 _params,address _avatar)
external
onlyGlobalConstraintsScheme
isAvatarValid(_avatar)
returns(bool)
{
GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when();
if ((when == GlobalConstraintInterface.CallPhase.Pre)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) {
if (!globalConstraintsRegisterPre[_globalConstraint].isRegistered) {
globalConstraintsPre.push(GlobalConstraint(_globalConstraint,_params));
globalConstraintsRegisterPre[_globalConstraint] = GlobalConstraintRegister(true,globalConstraintsPre.length-1);
}else {
globalConstraintsPre[globalConstraintsRegisterPre[_globalConstraint].index].params = _params;
}
}
if ((when == GlobalConstraintInterface.CallPhase.Post)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) {
if (!globalConstraintsRegisterPost[_globalConstraint].isRegistered) {
globalConstraintsPost.push(GlobalConstraint(_globalConstraint,_params));
globalConstraintsRegisterPost[_globalConstraint] = GlobalConstraintRegister(true,globalConstraintsPost.length-1);
}else {
globalConstraintsPost[globalConstraintsRegisterPost[_globalConstraint].index].params = _params;
}
}
emit AddGlobalConstraint(_globalConstraint, _params,when);
return true;
}
/**
* @dev remove Global Constraint
* @param _globalConstraint the address of the global constraint to be remove.
* @return bool which represents a success
*/
function removeGlobalConstraint (address _globalConstraint,address _avatar)
external
onlyGlobalConstraintsScheme
isAvatarValid(_avatar)
returns(bool)
{
GlobalConstraintRegister memory globalConstraintRegister;
GlobalConstraint memory globalConstraint;
GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when();
bool retVal = false;
if ((when == GlobalConstraintInterface.CallPhase.Pre)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) {
globalConstraintRegister = globalConstraintsRegisterPre[_globalConstraint];
if (globalConstraintRegister.isRegistered) {
if (globalConstraintRegister.index < globalConstraintsPre.length-1) {
globalConstraint = globalConstraintsPre[globalConstraintsPre.length-1];
globalConstraintsPre[globalConstraintRegister.index] = globalConstraint;
globalConstraintsRegisterPre[globalConstraint.gcAddress].index = globalConstraintRegister.index;
}
globalConstraintsPre.length--;
delete globalConstraintsRegisterPre[_globalConstraint];
retVal = true;
}
}
if ((when == GlobalConstraintInterface.CallPhase.Post)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) {
globalConstraintRegister = globalConstraintsRegisterPost[_globalConstraint];
if (globalConstraintRegister.isRegistered) {
if (globalConstraintRegister.index < globalConstraintsPost.length-1) {
globalConstraint = globalConstraintsPost[globalConstraintsPost.length-1];
globalConstraintsPost[globalConstraintRegister.index] = globalConstraint;
globalConstraintsRegisterPost[globalConstraint.gcAddress].index = globalConstraintRegister.index;
}
globalConstraintsPost.length--;
delete globalConstraintsRegisterPost[_globalConstraint];
retVal = true;
}
}
if (retVal) {
emit RemoveGlobalConstraint(_globalConstraint,globalConstraintRegister.index,when == GlobalConstraintInterface.CallPhase.Pre);
}
return retVal;
}
/**
* @dev upgrade the Controller
* The function will trigger an event 'UpgradeController'.
* @param _newController the address of the new controller.
* @return bool which represents a success
*/
function upgradeController(address _newController,address _avatar)
external
onlyUpgradingScheme
isAvatarValid(_avatar)
returns(bool)
{
require(newController == address(0)); // so the upgrade could be done once for a contract.
require(_newController != address(0));
newController = _newController;
avatar.transferOwnership(_newController);
require(avatar.owner()==_newController);
if (nativeToken.owner() == address(this)) {
nativeToken.transferOwnership(_newController);
require(nativeToken.owner()==_newController);
}
if (nativeReputation.owner() == address(this)) {
nativeReputation.transferOwnership(_newController);
require(nativeReputation.owner()==_newController);
}
emit UpgradeController(this,newController);
return true;
}
/**
* @dev perform a generic call to an arbitrary contract
* @param _contract the contract's address to call
* @param _data ABI-encoded contract call to call `_contract` address.
* @param _avatar the controller's avatar address
* @return bytes32 - the return value of the called _contract's function.
*/
function genericCall(address _contract,bytes _data,address _avatar)
external
onlyGenericCallScheme
onlySubjectToConstraint("genericCall")
isAvatarValid(_avatar)
returns (bytes32)
{
emit GenericCall(_contract, _data);
avatar.genericCall(_contract, _data);
// solium-disable-next-line security/no-inline-assembly
assembly {
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
return(0, returndatasize)
}
}
/**
* @dev send some ether
* @param _amountInWei the amount of ether (in Wei) to send
* @param _to address of the beneficiary
* @return bool which represents a success
*/
function sendEther(uint _amountInWei, address _to,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("sendEther")
isAvatarValid(_avatar)
returns(bool)
{
emit SendEther(msg.sender, _amountInWei, _to);
return avatar.sendEther(_amountInWei, _to);
}
/**
* @dev send some amount of arbitrary ERC20 Tokens
* @param _externalToken the address of the Token Contract
* @param _to address of the beneficiary
* @param _value the amount of ether (in Wei) to send
* @return bool which represents a success
*/
function externalTokenTransfer(StandardToken _externalToken, address _to, uint _value,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("externalTokenTransfer")
isAvatarValid(_avatar)
returns(bool)
{
emit ExternalTokenTransfer(msg.sender, _externalToken, _to, _value);
return avatar.externalTokenTransfer(_externalToken, _to, _value);
}
/**
* @dev transfer token "from" address "to" address
* One must to approve the amount of tokens which can be spend from the
* "from" account.This can be done using externalTokenApprove.
* @param _externalToken the address of the Token Contract
* @param _from address of the account to send from
* @param _to address of the beneficiary
* @param _value the amount of ether (in Wei) to send
* @return bool which represents a success
*/
function externalTokenTransferFrom(StandardToken _externalToken, address _from, address _to, uint _value,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("externalTokenTransferFrom")
isAvatarValid(_avatar)
returns(bool)
{
emit ExternalTokenTransferFrom(msg.sender, _externalToken, _from, _to, _value);
return avatar.externalTokenTransferFrom(_externalToken, _from, _to, _value);
}
/**
* @dev increase approval for the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _addedValue the amount of ether (in Wei) which the approval is referring to.
* @return bool which represents a success
*/
function externalTokenIncreaseApproval(StandardToken _externalToken, address _spender, uint _addedValue,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("externalTokenIncreaseApproval")
isAvatarValid(_avatar)
returns(bool)
{
emit ExternalTokenIncreaseApproval(msg.sender,_externalToken,_spender,_addedValue);
return avatar.externalTokenIncreaseApproval(_externalToken, _spender, _addedValue);
}
/**
* @dev decrease approval for the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _subtractedValue the amount of ether (in Wei) which the approval is referring to.
* @return bool which represents a success
*/
function externalTokenDecreaseApproval(StandardToken _externalToken, address _spender, uint _subtractedValue,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("externalTokenDecreaseApproval")
isAvatarValid(_avatar)
returns(bool)
{
emit ExternalTokenDecreaseApproval(msg.sender,_externalToken,_spender,_subtractedValue);
return avatar.externalTokenDecreaseApproval(_externalToken, _spender, _subtractedValue);
}
/**
* @dev getNativeReputation
* @param _avatar the organization avatar.
* @return organization native reputation
*/
function getNativeReputation(address _avatar) external isAvatarValid(_avatar) view returns(address) {
return address(nativeReputation);
}
function _isSchemeRegistered(address _scheme,address _avatar) private isAvatarValid(_avatar) view returns(bool) {
return (schemes[_scheme].permissions&bytes4(1) != bytes4(0));
}
}
// File: contracts/universalSchemes/ExecutableInterface.sol
contract ExecutableInterface {
function execute(bytes32 _proposalId, address _avatar, int _param) public returns(bool);
}
// File: contracts/VotingMachines/IntVoteInterface.sol
interface IntVoteInterface {
//When implementing this interface please do not only override function and modifier,
//but also to keep the modifiers on the overridden functions.
modifier onlyProposalOwner(bytes32 _proposalId) {revert(); _;}
modifier votable(bytes32 _proposalId) {revert(); _;}
event NewProposal(bytes32 indexed _proposalId, address indexed _avatar, uint _numOfChoices, address _proposer, bytes32 _paramsHash);
event ExecuteProposal(bytes32 indexed _proposalId, address indexed _avatar, uint _decision, uint _totalReputation);
event VoteProposal(bytes32 indexed _proposalId, address indexed _avatar, address indexed _voter, uint _vote, uint _reputation);
event CancelProposal(bytes32 indexed _proposalId, address indexed _avatar );
event CancelVoting(bytes32 indexed _proposalId, address indexed _avatar, address indexed _voter);
/**
* @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being
* generated by calculating keccak256 of a incremented counter.
* @param _numOfChoices number of voting choices
* @param _proposalParameters defines the parameters of the voting machine used for this proposal
* @param _avatar an address to be sent as the payload to the _executable contract.
* @param _executable This contract will be executed when vote is over.
* @param _proposer address
* @return proposal's id.
*/
function propose(
uint _numOfChoices,
bytes32 _proposalParameters,
address _avatar,
ExecutableInterface _executable,
address _proposer
) external returns(bytes32);
// Only owned proposals and only the owner:
function cancelProposal(bytes32 _proposalId) external returns(bool);
// Only owned proposals and only the owner:
function ownerVote(bytes32 _proposalId, uint _vote, address _voter) external returns(bool);
function vote(bytes32 _proposalId, uint _vote) external returns(bool);
function voteWithSpecifiedAmounts(
bytes32 _proposalId,
uint _vote,
uint _rep,
uint _token) external returns(bool);
function cancelVote(bytes32 _proposalId) external;
//@dev execute check if the proposal has been decided, and if so, execute the proposal
//@param _proposalId the id of the proposal
//@return bool true - the proposal has been executed
// false - otherwise.
function execute(bytes32 _proposalId) external returns(bool);
function getNumberOfChoices(bytes32 _proposalId) external view returns(uint);
function isVotable(bytes32 _proposalId) external view returns(bool);
/**
* @dev voteStatus returns the reputation voted for a proposal for a specific voting choice.
* @param _proposalId the ID of the proposal
* @param _choice the index in the
* @return voted reputation for the given choice
*/
function voteStatus(bytes32 _proposalId,uint _choice) external view returns(uint);
/**
* @dev isAbstainAllow returns if the voting machine allow abstain (0)
* @return bool true or false
*/
function isAbstainAllow() external pure returns(bool);
/**
* @dev getAllowedRangeOfChoices returns the allowed range of choices for a voting machine.
* @return min - minimum number of choices
max - maximum number of choices
*/
function getAllowedRangeOfChoices() external pure returns(uint min,uint max);
}
// File: contracts/universalSchemes/UniversalSchemeInterface.sol
contract UniversalSchemeInterface {
function updateParameters(bytes32 _hashedParameters) public;
function getParametersFromController(Avatar _avatar) internal view returns(bytes32);
}
// File: contracts/universalSchemes/UniversalScheme.sol
contract UniversalScheme is Ownable, UniversalSchemeInterface {
bytes32 public hashedParameters; // For other parameters.
function updateParameters(
bytes32 _hashedParameters
)
public
onlyOwner
{
hashedParameters = _hashedParameters;
}
/**
* @dev get the parameters for the current scheme from the controller
*/
function getParametersFromController(Avatar _avatar) internal view returns(bytes32) {
return ControllerInterface(_avatar.owner()).getSchemeParameters(this,address(_avatar));
}
}
// File: contracts/libs/RealMath.sol
/**
* RealMath: fixed-point math library, based on fractional and integer parts.
* Using int256 as real216x40, which isn't in Solidity yet.
* 40 fractional bits gets us down to 1E-12 precision, while still letting us
* go up to galaxy scale counting in meters.
* Internally uses the wider int256 for some math.
*
* Note that for addition, subtraction, and mod (%), you should just use the
* built-in Solidity operators. Functions for these operations are not provided.
*
* Note that the fancy functions like sqrt, atan2, etc. aren't as accurate as
* they should be. They are (hopefully) Good Enough for doing orbital mechanics
* on block timescales in a game context, but they may not be good enough for
* other applications.
*/
library RealMath {
/**
* How many total bits are there?
*/
int256 constant REAL_BITS = 256;
/**
* How many fractional bits are there?
*/
int256 constant REAL_FBITS = 40;
/**
* How many integer bits are there?
*/
int256 constant REAL_IBITS = REAL_BITS - REAL_FBITS;
/**
* What's the first non-fractional bit
*/
int256 constant REAL_ONE = int256(1) << REAL_FBITS;
/**
* What's the last fractional bit?
*/
int256 constant REAL_HALF = REAL_ONE >> 1;
/**
* What's two? Two is pretty useful.
*/
int256 constant REAL_TWO = REAL_ONE << 1;
/**
* And our logarithms are based on ln(2).
*/
int256 constant REAL_LN_TWO = 762123384786;
/**
* It is also useful to have Pi around.
*/
int256 constant REAL_PI = 3454217652358;
/**
* And half Pi, to save on divides.
* TODO: That might not be how the compiler handles constants.
*/
int256 constant REAL_HALF_PI = 1727108826179;
/**
* And two pi, which happens to be odd in its most accurate representation.
*/
int256 constant REAL_TWO_PI = 6908435304715;
/**
* What's the sign bit?
*/
int256 constant SIGN_MASK = int256(1) << 255;
/**
* Convert an integer to a real. Preserves sign.
*/
function toReal(int216 ipart) internal pure returns (int256) {
return int256(ipart) * REAL_ONE;
}
/**
* Convert a real to an integer. Preserves sign.
*/
function fromReal(int256 realValue) internal pure returns (int216) {
return int216(realValue / REAL_ONE);
}
/**
* Round a real to the nearest integral real value.
*/
function round(int256 realValue) internal pure returns (int256) {
// First, truncate.
int216 ipart = fromReal(realValue);
if ((fractionalBits(realValue) & (uint40(1) << (REAL_FBITS - 1))) > 0) {
// High fractional bit is set. Round up.
if (realValue < int256(0)) {
// Rounding up for a negative number is rounding down.
ipart -= 1;
} else {
ipart += 1;
}
}
return toReal(ipart);
}
/**
* Get the absolute value of a real. Just the same as abs on a normal int256.
*/
function abs(int256 realValue) internal pure returns (int256) {
if (realValue > 0) {
return realValue;
} else {
return -realValue;
}
}
/**
* Returns the fractional bits of a real. Ignores the sign of the real.
*/
function fractionalBits(int256 realValue) internal pure returns (uint40) {
return uint40(abs(realValue) % REAL_ONE);
}
/**
* Get the fractional part of a real, as a real. Ignores sign (so fpart(-0.5) is 0.5).
*/
function fpart(int256 realValue) internal pure returns (int256) {
// This gets the fractional part but strips the sign
return abs(realValue) % REAL_ONE;
}
/**
* Get the fractional part of a real, as a real. Respects sign (so fpartSigned(-0.5) is -0.5).
*/
function fpartSigned(int256 realValue) internal pure returns (int256) {
// This gets the fractional part but strips the sign
int256 fractional = fpart(realValue);
if (realValue < 0) {
// Add the negative sign back in.
return -fractional;
} else {
return fractional;
}
}
/**
* Get the integer part of a fixed point value.
*/
function ipart(int256 realValue) internal pure returns (int256) {
// Subtract out the fractional part to get the real part.
return realValue - fpartSigned(realValue);
}
/**
* Multiply one real by another. Truncates overflows.
*/
function mul(int256 realA, int256 realB) internal pure returns (int256) {
// When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format.
// So we just have to clip off the extra REAL_FBITS fractional bits.
return int256((int256(realA) * int256(realB)) >> REAL_FBITS);
}
/**
* Divide one real by another real. Truncates overflows.
*/
function div(int256 realNumerator, int256 realDenominator) internal pure returns (int256) {
// We use the reverse of the multiplication trick: convert numerator from
// x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point.
return int256((int256(realNumerator) * REAL_ONE) / int256(realDenominator));
}
/**
* Create a real from a rational fraction.
*/
function fraction(int216 numerator, int216 denominator) internal pure returns (int256) {
return div(toReal(numerator), toReal(denominator));
}
// Now we have some fancy math things (like pow and trig stuff). This isn't
// in the RealMath that was deployed with the original Macroverse
// deployment, so it needs to be linked into your contract statically.
/**
* Raise a number to a positive integer power in O(log power) time.
* See <https://stackoverflow.com/a/101613>
*/
function ipow(int256 realBase, int216 exponent) internal pure returns (int256) {
if (exponent < 0) {
// Negative powers are not allowed here.
revert();
}
int256 tempRealBase = realBase;
int256 tempExponent = exponent;
// Start with the 0th power
int256 realResult = REAL_ONE;
while (tempExponent != 0) {
// While there are still bits set
if ((tempExponent & 0x1) == 0x1) {
// If the low bit is set, multiply in the (many-times-squared) base
realResult = mul(realResult, tempRealBase);
}
// Shift off the low bit
tempExponent = tempExponent >> 1;
// Do the squaring
tempRealBase = mul(tempRealBase, tempRealBase);
}
// Return the final result.
return realResult;
}
/**
* Zero all but the highest set bit of a number.
* See <https://stackoverflow.com/a/53184>
*/
function hibit(uint256 _val) internal pure returns (uint256) {
// Set all the bits below the highest set bit
uint256 val = _val;
val |= (val >> 1);
val |= (val >> 2);
val |= (val >> 4);
val |= (val >> 8);
val |= (val >> 16);
val |= (val >> 32);
val |= (val >> 64);
val |= (val >> 128);
return val ^ (val >> 1);
}
/**
* Given a number with one bit set, finds the index of that bit.
*/
function findbit(uint256 val) internal pure returns (uint8 index) {
index = 0;
// We and the value with alternating bit patters of various pitches to find it.
if (val & 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA != 0) {
// Picth 1
index |= 1;
}
if (val & 0xCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC != 0) {
// Pitch 2
index |= 2;
}
if (val & 0xF0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0 != 0) {
// Pitch 4
index |= 4;
}
if (val & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00 != 0) {
// Pitch 8
index |= 8;
}
if (val & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000 != 0) {
// Pitch 16
index |= 16;
}
if (val & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000 != 0) {
// Pitch 32
index |= 32;
}
if (val & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000 != 0) {
// Pitch 64
index |= 64;
}
if (val & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000 != 0) {
// Pitch 128
index |= 128;
}
}
/**
* Shift realArg left or right until it is between 1 and 2. Return the
* rescaled value, and the number of bits of right shift applied. Shift may be negative.
*
* Expresses realArg as realScaled * 2^shift, setting shift to put realArg between [1 and 2).
*
* Rejects 0 or negative arguments.
*/
function rescale(int256 realArg) internal pure returns (int256 realScaled, int216 shift) {
if (realArg <= 0) {
// Not in domain!
revert();
}
// Find the high bit
int216 highBit = findbit(hibit(uint256(realArg)));
// We'll shift so the high bit is the lowest non-fractional bit.
shift = highBit - int216(REAL_FBITS);
if (shift < 0) {
// Shift left
realScaled = realArg << -shift;
} else if (shift >= 0) {
// Shift right
realScaled = realArg >> shift;
}
}
/**
* Calculate the natural log of a number. Rescales the input value and uses
* the algorithm outlined at <https://math.stackexchange.com/a/977836> and
* the ipow implementation.
*
* Lets you artificially limit the number of iterations.
*
* Note that it is potentially possible to get an un-converged value; lack
* of convergence does not throw.
*/
function lnLimited(int256 realArg, int maxIterations) internal pure returns (int256) {
if (realArg <= 0) {
// Outside of acceptable domain
revert();
}
if (realArg == REAL_ONE) {
// Handle this case specially because people will want exactly 0 and
// not ~2^-39 ish.
return 0;
}
// We know it's positive, so rescale it to be between [1 and 2)
int256 realRescaled;
int216 shift;
(realRescaled, shift) = rescale(realArg);
// Compute the argument to iterate on
int256 realSeriesArg = div(realRescaled - REAL_ONE, realRescaled + REAL_ONE);
// We will accumulate the result here
int256 realSeriesResult = 0;
for (int216 n = 0; n < maxIterations; n++) {
// Compute term n of the series
int256 realTerm = div(ipow(realSeriesArg, 2 * n + 1), toReal(2 * n + 1));
// And add it in
realSeriesResult += realTerm;
if (realTerm == 0) {
// We must have converged. Next term is too small to represent.
break;
}
// If we somehow never converge I guess we will run out of gas
}
// Double it to account for the factor of 2 outside the sum
realSeriesResult = mul(realSeriesResult, REAL_TWO);
// Now compute and return the overall result
return mul(toReal(shift), REAL_LN_TWO) + realSeriesResult;
}
/**
* Calculate a natural logarithm with a sensible maximum iteration count to
* wait until convergence. Note that it is potentially possible to get an
* un-converged value; lack of convergence does not throw.
*/
function ln(int256 realArg) internal pure returns (int256) {
return lnLimited(realArg, 100);
}
/**
* Calculate e^x. Uses the series given at
* <http://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/exp.html>.
*
* Lets you artificially limit the number of iterations.
*
* Note that it is potentially possible to get an un-converged value; lack
* of convergence does not throw.
*/
function expLimited(int256 realArg, int maxIterations) internal pure returns (int256) {
// We will accumulate the result here
int256 realResult = 0;
// We use this to save work computing terms
int256 realTerm = REAL_ONE;
for (int216 n = 0; n < maxIterations; n++) {
// Add in the term
realResult += realTerm;
// Compute the next term
realTerm = mul(realTerm, div(realArg, toReal(n + 1)));
if (realTerm == 0) {
// We must have converged. Next term is too small to represent.
break;
}
// If we somehow never converge I guess we will run out of gas
}
// Return the result
return realResult;
}
/**
* Calculate e^x with a sensible maximum iteration count to wait until
* convergence. Note that it is potentially possible to get an un-converged
* value; lack of convergence does not throw.
*/
function exp(int256 realArg) internal pure returns (int256) {
return expLimited(realArg, 100);
}
/**
* Raise any number to any power, except for negative bases to fractional powers.
*/
function pow(int256 realBase, int256 realExponent) internal pure returns (int256) {
if (realExponent == 0) {
// Anything to the 0 is 1
return REAL_ONE;
}
if (realBase == 0) {
if (realExponent < 0) {
// Outside of domain!
revert();
}
// Otherwise it's 0
return 0;
}
if (fpart(realExponent) == 0) {
// Anything (even a negative base) is super easy to do to an integer power.
if (realExponent > 0) {
// Positive integer power is easy
return ipow(realBase, fromReal(realExponent));
} else {
// Negative integer power is harder
return div(REAL_ONE, ipow(realBase, fromReal(-realExponent)));
}
}
if (realBase < 0) {
// It's a negative base to a non-integer power.
// In general pow(-x^y) is undefined, unless y is an int or some
// weird rational-number-based relationship holds.
revert();
}
// If it's not a special case, actually do it.
return exp(mul(realExponent, ln(realBase)));
}
/**
* Compute the square root of a number.
*/
function sqrt(int256 realArg) internal pure returns (int256) {
return pow(realArg, REAL_HALF);
}
/**
* Compute the sin of a number to a certain number of Taylor series terms.
*/
function sinLimited(int256 _realArg, int216 maxIterations) internal pure returns (int256) {
// First bring the number into 0 to 2 pi
// TODO: This will introduce an error for very large numbers, because the error in our Pi will compound.
// But for actual reasonable angle values we should be fine.
int256 realArg = _realArg;
realArg = realArg % REAL_TWO_PI;
int256 accumulator = REAL_ONE;
// We sum from large to small iteration so that we can have higher powers in later terms
for (int216 iteration = maxIterations - 1; iteration >= 0; iteration--) {
accumulator = REAL_ONE - mul(div(mul(realArg, realArg), toReal((2 * iteration + 2) * (2 * iteration + 3))), accumulator);
// We can't stop early; we need to make it to the first term.
}
return mul(realArg, accumulator);
}
/**
* Calculate sin(x) with a sensible maximum iteration count to wait until
* convergence.
*/
function sin(int256 realArg) internal pure returns (int256) {
return sinLimited(realArg, 15);
}
/**
* Calculate cos(x).
*/
function cos(int256 realArg) internal pure returns (int256) {
return sin(realArg + REAL_HALF_PI);
}
/**
* Calculate tan(x). May overflow for large results. May throw if tan(x)
* would be infinite, or return an approximation, or overflow.
*/
function tan(int256 realArg) internal pure returns (int256) {
return div(sin(realArg), cos(realArg));
}
}
// File: openzeppelin-solidity/contracts/ECRecovery.sol
/**
* @title Eliptic curve signature operations
*
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
*
* TODO Remove this library once solidity supports passing a signature to ecrecover.
* See https://github.com/ethereum/solidity/issues/864
*
*/
library ECRecovery {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes sig)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
return ecrecover(hash, v, r, s);
}
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* @dev and hash the result
*/
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(
"\x19Ethereum Signed Message:\n32",
hash
);
}
}
// File: contracts/libs/OrderStatisticTree.sol
library OrderStatisticTree {
struct Node {
mapping (bool => uint) children; // a mapping of left(false) child and right(true) child nodes
uint parent; // parent node
bool side; // side of the node on the tree (left or right)
uint height; //Height of this node
uint count; //Number of tree nodes below this node (including this one)
uint dupes; //Number of duplicates values for this node
}
struct Tree {
// a mapping between node value(uint) to Node
// the tree's root is always at node 0 ,which points to the "real" tree
// as its right child.this is done to eliminate the need to update the tree
// root in the case of rotation.(saving gas).
mapping(uint => Node) nodes;
}
/**
* @dev rank - find the rank of a value in the tree,
* i.e. its index in the sorted list of elements of the tree
* @param _tree the tree
* @param _value the input value to find its rank.
* @return smaller - the number of elements in the tree which their value is
* less than the input value.
*/
function rank(Tree storage _tree,uint _value) internal view returns (uint smaller) {
if (_value != 0) {
smaller = _tree.nodes[0].dupes;
uint cur = _tree.nodes[0].children[true];
Node storage currentNode = _tree.nodes[cur];
while (true) {
if (cur <= _value) {
if (cur<_value) {
smaller = smaller + 1+currentNode.dupes;
}
uint leftChild = currentNode.children[false];
if (leftChild!=0) {
smaller = smaller + _tree.nodes[leftChild].count;
}
}
if (cur == _value) {
break;
}
cur = currentNode.children[cur<_value];
if (cur == 0) {
break;
}
currentNode = _tree.nodes[cur];
}
}
}
function count(Tree storage _tree) internal view returns (uint) {
Node storage root = _tree.nodes[0];
Node memory child = _tree.nodes[root.children[true]];
return root.dupes+child.count;
}
function updateCount(Tree storage _tree,uint _value) private {
Node storage n = _tree.nodes[_value];
n.count = 1+_tree.nodes[n.children[false]].count+_tree.nodes[n.children[true]].count+n.dupes;
}
function updateCounts(Tree storage _tree,uint _value) private {
uint parent = _tree.nodes[_value].parent;
while (parent!=0) {
updateCount(_tree,parent);
parent = _tree.nodes[parent].parent;
}
}
function updateHeight(Tree storage _tree,uint _value) private {
Node storage n = _tree.nodes[_value];
uint heightLeft = _tree.nodes[n.children[false]].height;
uint heightRight = _tree.nodes[n.children[true]].height;
if (heightLeft > heightRight)
n.height = heightLeft+1;
else
n.height = heightRight+1;
}
function balanceFactor(Tree storage _tree,uint _value) private view returns (int bf) {
Node storage n = _tree.nodes[_value];
return int(_tree.nodes[n.children[false]].height)-int(_tree.nodes[n.children[true]].height);
}
function rotate(Tree storage _tree,uint _value,bool dir) private {
bool otherDir = !dir;
Node storage n = _tree.nodes[_value];
bool side = n.side;
uint parent = n.parent;
uint valueNew = n.children[otherDir];
Node storage nNew = _tree.nodes[valueNew];
uint orphan = nNew.children[dir];
Node storage p = _tree.nodes[parent];
Node storage o = _tree.nodes[orphan];
p.children[side] = valueNew;
nNew.side = side;
nNew.parent = parent;
nNew.children[dir] = _value;
n.parent = valueNew;
n.side = dir;
n.children[otherDir] = orphan;
o.parent = _value;
o.side = otherDir;
updateHeight(_tree,_value);
updateHeight(_tree,valueNew);
updateCount(_tree,_value);
updateCount(_tree,valueNew);
}
function rebalanceInsert(Tree storage _tree,uint _nValue) private {
updateHeight(_tree,_nValue);
Node storage n = _tree.nodes[_nValue];
uint pValue = n.parent;
if (pValue!=0) {
int pBf = balanceFactor(_tree,pValue);
bool side = n.side;
int sign;
if (side)
sign = -1;
else
sign = 1;
if (pBf == sign*2) {
if (balanceFactor(_tree,_nValue) == (-1 * sign)) {
rotate(_tree,_nValue,side);
}
rotate(_tree,pValue,!side);
} else if (pBf != 0) {
rebalanceInsert(_tree,pValue);
}
}
}
function rebalanceDelete(Tree storage _tree,uint _pValue,bool side) private {
if (_pValue!=0) {
updateHeight(_tree,_pValue);
int pBf = balanceFactor(_tree,_pValue);
int sign;
if (side)
sign = 1;
else
sign = -1;
int bf = balanceFactor(_tree,_pValue);
if (bf==(2*sign)) {
Node storage p = _tree.nodes[_pValue];
uint sValue = p.children[!side];
int sBf = balanceFactor(_tree,sValue);
if (sBf == (-1 * sign)) {
rotate(_tree,sValue,!side);
}
rotate(_tree,_pValue,side);
if (sBf!=0) {
p = _tree.nodes[_pValue];
rebalanceDelete(_tree,p.parent,p.side);
}
} else if (pBf != sign) {
p = _tree.nodes[_pValue];
rebalanceDelete(_tree,p.parent,p.side);
}
}
}
function fixParents(Tree storage _tree,uint parent,bool side) private {
if (parent!=0) {
updateCount(_tree,parent);
updateCounts(_tree,parent);
rebalanceDelete(_tree,parent,side);
}
}
function insertHelper(Tree storage _tree,uint _pValue,bool _side,uint _value) private {
Node storage root = _tree.nodes[_pValue];
uint cValue = root.children[_side];
if (cValue==0) {
root.children[_side] = _value;
Node storage child = _tree.nodes[_value];
child.parent = _pValue;
child.side = _side;
child.height = 1;
child.count = 1;
updateCounts(_tree,_value);
rebalanceInsert(_tree,_value);
} else if (cValue==_value) {
_tree.nodes[cValue].dupes++;
updateCount(_tree,_value);
updateCounts(_tree,_value);
} else {
insertHelper(_tree,cValue,(_value >= cValue),_value);
}
}
function insert(Tree storage _tree,uint _value) internal {
if (_value==0) {
_tree.nodes[_value].dupes++;
} else {
insertHelper(_tree,0,true,_value);
}
}
function rightmostLeaf(Tree storage _tree,uint _value) private view returns (uint leaf) {
uint child = _tree.nodes[_value].children[true];
if (child!=0) {
return rightmostLeaf(_tree,child);
} else {
return _value;
}
}
function zeroOut(Tree storage _tree,uint _value) private {
Node storage n = _tree.nodes[_value];
n.parent = 0;
n.side = false;
n.children[false] = 0;
n.children[true] = 0;
n.count = 0;
n.height = 0;
n.dupes = 0;
}
function removeBranch(Tree storage _tree,uint _value,uint _left) private {
uint ipn = rightmostLeaf(_tree,_left);
Node storage i = _tree.nodes[ipn];
uint dupes = i.dupes;
removeHelper(_tree,ipn);
Node storage n = _tree.nodes[_value];
uint parent = n.parent;
Node storage p = _tree.nodes[parent];
uint height = n.height;
bool side = n.side;
uint ncount = n.count;
uint right = n.children[true];
uint left = n.children[false];
p.children[side] = ipn;
i.parent = parent;
i.side = side;
i.count = ncount+dupes-n.dupes;
i.height = height;
i.dupes = dupes;
if (left!=0) {
i.children[false] = left;
_tree.nodes[left].parent = ipn;
}
if (right!=0) {
i.children[true] = right;
_tree.nodes[right].parent = ipn;
}
zeroOut(_tree,_value);
updateCounts(_tree,ipn);
}
function removeHelper(Tree storage _tree,uint _value) private {
Node storage n = _tree.nodes[_value];
uint parent = n.parent;
bool side = n.side;
Node storage p = _tree.nodes[parent];
uint left = n.children[false];
uint right = n.children[true];
if ((left == 0) && (right == 0)) {
p.children[side] = 0;
zeroOut(_tree,_value);
fixParents(_tree,parent,side);
} else if ((left != 0) && (right != 0)) {
removeBranch(_tree,_value,left);
} else {
uint child = left+right;
Node storage c = _tree.nodes[child];
p.children[side] = child;
c.parent = parent;
c.side = side;
zeroOut(_tree,_value);
fixParents(_tree,parent,side);
}
}
function remove(Tree storage _tree,uint _value) internal {
Node storage n = _tree.nodes[_value];
if (_value==0) {
if (n.dupes==0) {
return;
}
} else {
if (n.count==0) {
return;
}
}
if (n.dupes>0) {
n.dupes--;
if (_value!=0) {
n.count--;
}
fixParents(_tree,n.parent,n.side);
} else {
removeHelper(_tree,_value);
}
}
}
// File: contracts/VotingMachines/GenesisProtocol.sol
/**
* @title GenesisProtocol implementation -an organization's voting machine scheme.
*/
contract GenesisProtocol is IntVoteInterface,UniversalScheme {
using SafeMath for uint;
using RealMath for int216;
using RealMath for int256;
using ECRecovery for bytes32;
using OrderStatisticTree for OrderStatisticTree.Tree;
enum ProposalState { None ,Closed, Executed, PreBoosted,Boosted,QuietEndingPeriod }
enum ExecutionState { None, PreBoostedTimeOut, PreBoostedBarCrossed, BoostedTimeOut,BoostedBarCrossed }
//Organization's parameters
struct Parameters {
uint preBoostedVoteRequiredPercentage; // the absolute vote percentages bar.
uint preBoostedVotePeriodLimit; //the time limit for a proposal to be in an absolute voting mode.
uint boostedVotePeriodLimit; //the time limit for a proposal to be in an relative voting mode.
uint thresholdConstA;//constant A for threshold calculation . threshold =A * (e ** (numberOfBoostedProposals/B))
uint thresholdConstB;//constant B for threshold calculation . threshold =A * (e ** (numberOfBoostedProposals/B))
uint minimumStakingFee; //minimum staking fee allowed.
uint quietEndingPeriod; //quite ending period
uint proposingRepRewardConstA;//constant A for calculate proposer reward. proposerReward =(A*(RTotal) +B*(R+ - R-))/1000
uint proposingRepRewardConstB;//constant B for calculate proposing reward.proposerReward =(A*(RTotal) +B*(R+ - R-))/1000
uint stakerFeeRatioForVoters; // The “ratio of stake” to be paid to voters.
// All stakers pay a portion of their stake to all voters, stakerFeeRatioForVoters * (s+ + s-).
//All voters (pre and during boosting period) divide this portion in proportion to their reputation.
uint votersReputationLossRatio;//Unsuccessful pre booster voters lose votersReputationLossRatio% of their reputation.
uint votersGainRepRatioFromLostRep; //the percentages of the lost reputation which is divided by the successful pre boosted voters,
//in proportion to their reputation.
//The rest (100-votersGainRepRatioFromLostRep)% of lost reputation is divided between the successful wagers,
//in proportion to their stake.
uint daoBountyConst;//The DAO adds up a bounty for successful staker.
//The bounty formula is: s * daoBountyConst, where s+ is the wager staked for the proposal,
//and daoBountyConst is a constant factor that is configurable and changeable by the DAO given.
// daoBountyConst should be greater than stakerFeeRatioForVoters and less than 2 * stakerFeeRatioForVoters.
uint daoBountyLimit;//The daoBounty cannot be greater than daoBountyLimit.
}
struct Voter {
uint vote; // YES(1) ,NO(2)
uint reputation; // amount of voter's reputation
bool preBoosted;
}
struct Staker {
uint vote; // YES(1) ,NO(2)
uint amount; // amount of staker's stake
uint amountForBounty; // amount of staker's stake which will be use for bounty calculation
}
struct Proposal {
address avatar; // the organization's avatar the proposal is target to.
uint numOfChoices;
ExecutableInterface executable; // will be executed if the proposal will pass
uint votersStakes;
uint submittedTime;
uint boostedPhaseTime; //the time the proposal shift to relative mode.
ProposalState state;
uint winningVote; //the winning vote.
address proposer;
uint currentBoostedVotePeriodLimit;
bytes32 paramsHash;
uint daoBountyRemain;
uint[2] totalStakes;// totalStakes[0] - (amount staked minus fee) - Total number of tokens staked which can be redeemable by stakers.
// totalStakes[1] - (amount staked) - Total number of redeemable tokens.
// vote reputation
mapping(uint => uint ) votes;
// vote reputation
mapping(uint => uint ) preBoostedVotes;
// address voter
mapping(address => Voter ) voters;
// vote stakes
mapping(uint => uint ) stakes;
// address staker
mapping(address => Staker ) stakers;
}
event GPExecuteProposal(bytes32 indexed _proposalId, ExecutionState _executionState);
event Stake(bytes32 indexed _proposalId, address indexed _avatar, address indexed _staker,uint _vote,uint _amount);
event Redeem(bytes32 indexed _proposalId, address indexed _avatar, address indexed _beneficiary,uint _amount);
event RedeemDaoBounty(bytes32 indexed _proposalId, address indexed _avatar, address indexed _beneficiary,uint _amount);
event RedeemReputation(bytes32 indexed _proposalId, address indexed _avatar, address indexed _beneficiary,uint _amount);
mapping(bytes32=>Parameters) public parameters; // A mapping from hashes to parameters
mapping(bytes32=>Proposal) public proposals; // Mapping from the ID of the proposal to the proposal itself.
mapping(bytes=>bool) stakeSignatures; //stake signatures
uint constant public NUM_OF_CHOICES = 2;
uint constant public NO = 2;
uint constant public YES = 1;
uint public proposalsCnt; // Total number of proposals
mapping(address=>uint) orgBoostedProposalsCnt;
StandardToken public stakingToken;
mapping(address=>OrderStatisticTree.Tree) proposalsExpiredTimes; //proposals expired times
/**
* @dev Constructor
*/
constructor(StandardToken _stakingToken) public
{
stakingToken = _stakingToken;
}
/**
* @dev Check that the proposal is votable (open and not executed yet)
*/
modifier votable(bytes32 _proposalId) {
require(_isVotable(_proposalId));
_;
}
/**
* @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being
* generated by calculating keccak256 of a incremented counter.
* @param _numOfChoices number of voting choices
* @param _avatar an address to be sent as the payload to the _executable contract.
* @param _executable This contract will be executed when vote is over.
* @param _proposer address
* @return proposal's id.
*/
function propose(uint _numOfChoices, bytes32 , address _avatar, ExecutableInterface _executable,address _proposer)
external
returns(bytes32)
{
// Check valid params and number of choices:
require(_numOfChoices == NUM_OF_CHOICES);
require(ExecutableInterface(_executable) != address(0));
//Check parameters existence.
bytes32 paramsHash = getParametersFromController(Avatar(_avatar));
require(parameters[paramsHash].preBoostedVoteRequiredPercentage > 0);
// Generate a unique ID:
bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt));
proposalsCnt++;
// Open proposal:
Proposal memory proposal;
proposal.numOfChoices = _numOfChoices;
proposal.avatar = _avatar;
proposal.executable = _executable;
proposal.state = ProposalState.PreBoosted;
// solium-disable-next-line security/no-block-members
proposal.submittedTime = now;
proposal.currentBoostedVotePeriodLimit = parameters[paramsHash].boostedVotePeriodLimit;
proposal.proposer = _proposer;
proposal.winningVote = NO;
proposal.paramsHash = paramsHash;
proposals[proposalId] = proposal;
emit NewProposal(proposalId, _avatar, _numOfChoices, _proposer, paramsHash);
return proposalId;
}
/**
* @dev Cancel a proposal, only the owner can call this function and only if allowOwner flag is true.
*/
function cancelProposal(bytes32 ) external returns(bool) {
//This is not allowed.
return false;
}
/**
* @dev staking function
* @param _proposalId id of the proposal
* @param _vote NO(2) or YES(1).
* @param _amount the betting amount
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function stake(bytes32 _proposalId, uint _vote, uint _amount) external returns(bool) {
return _stake(_proposalId,_vote,_amount,msg.sender);
}
// Digest describing the data the user signs according EIP 712.
// Needs to match what is passed to Metamask.
bytes32 public constant DELEGATION_HASH_EIP712 =
keccak256(abi.encodePacked("address GenesisProtocolAddress","bytes32 ProposalId", "uint Vote","uint AmountToStake","uint Nonce"));
// web3.eth.sign prefix
string public constant ETH_SIGN_PREFIX= "\x19Ethereum Signed Message:\n32";
/**
* @dev stakeWithSignature function
* @param _proposalId id of the proposal
* @param _vote NO(2) or YES(1).
* @param _amount the betting amount
* @param _nonce nonce value ,it is part of the signature to ensure that
a signature can be received only once.
* @param _signatureType signature type
1 - for web3.eth.sign
2 - for eth_signTypedData according to EIP #712.
* @param _signature - signed data by the staker
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function stakeWithSignature(
bytes32 _proposalId,
uint _vote,
uint _amount,
uint _nonce,
uint _signatureType,
bytes _signature
)
external
returns(bool)
{
require(stakeSignatures[_signature] == false);
// Recreate the digest the user signed
bytes32 delegationDigest;
if (_signatureType == 2) {
delegationDigest = keccak256(
abi.encodePacked(
DELEGATION_HASH_EIP712, keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)))
);
} else {
delegationDigest = keccak256(
abi.encodePacked(
ETH_SIGN_PREFIX, keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)))
);
}
address staker = delegationDigest.recover(_signature);
//a garbage staker address due to wrong signature will revert due to lack of approval and funds.
require(staker!=address(0));
stakeSignatures[_signature] = true;
return _stake(_proposalId,_vote,_amount,staker);
}
/**
* @dev voting function
* @param _proposalId id of the proposal
* @param _vote NO(2) or YES(1).
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function vote(bytes32 _proposalId, uint _vote) external votable(_proposalId) returns(bool) {
return internalVote(_proposalId, msg.sender, _vote, 0);
}
/**
* @dev voting function with owner functionality (can vote on behalf of someone else)
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function ownerVote(bytes32 , uint , address ) external returns(bool) {
//This is not allowed.
return false;
}
function voteWithSpecifiedAmounts(bytes32 _proposalId,uint _vote,uint _rep,uint) external votable(_proposalId) returns(bool) {
return internalVote(_proposalId,msg.sender,_vote,_rep);
}
/**
* @dev Cancel the vote of the msg.sender.
* cancel vote is not allow in genesisProtocol so this function doing nothing.
* This function is here in order to comply to the IntVoteInterface .
*/
function cancelVote(bytes32 _proposalId) external votable(_proposalId) {
//this is not allowed
return;
}
/**
* @dev getNumberOfChoices returns the number of choices possible in this proposal
* @param _proposalId the ID of the proposals
* @return uint that contains number of choices
*/
function getNumberOfChoices(bytes32 _proposalId) external view returns(uint) {
return proposals[_proposalId].numOfChoices;
}
/**
* @dev voteInfo returns the vote and the amount of reputation of the user committed to this proposal
* @param _proposalId the ID of the proposal
* @param _voter the address of the voter
* @return uint vote - the voters vote
* uint reputation - amount of reputation committed by _voter to _proposalId
*/
function voteInfo(bytes32 _proposalId, address _voter) external view returns(uint, uint) {
Voter memory voter = proposals[_proposalId].voters[_voter];
return (voter.vote, voter.reputation);
}
/**
* @dev voteStatus returns the reputation voted for a proposal for a specific voting choice.
* @param _proposalId the ID of the proposal
* @param _choice the index in the
* @return voted reputation for the given choice
*/
function voteStatus(bytes32 _proposalId,uint _choice) external view returns(uint) {
return proposals[_proposalId].votes[_choice];
}
/**
* @dev isVotable check if the proposal is votable
* @param _proposalId the ID of the proposal
* @return bool true or false
*/
function isVotable(bytes32 _proposalId) external view returns(bool) {
return _isVotable(_proposalId);
}
/**
* @dev proposalStatus return the total votes and stakes for a given proposal
* @param _proposalId the ID of the proposal
* @return uint preBoostedVotes YES
* @return uint preBoostedVotes NO
* @return uint stakersStakes
* @return uint totalRedeemableStakes
* @return uint total stakes YES
* @return uint total stakes NO
*/
function proposalStatus(bytes32 _proposalId) external view returns(uint, uint, uint ,uint, uint ,uint) {
return (
proposals[_proposalId].preBoostedVotes[YES],
proposals[_proposalId].preBoostedVotes[NO],
proposals[_proposalId].totalStakes[0],
proposals[_proposalId].totalStakes[1],
proposals[_proposalId].stakes[YES],
proposals[_proposalId].stakes[NO]
);
}
/**
* @dev proposalAvatar return the avatar for a given proposal
* @param _proposalId the ID of the proposal
* @return uint total reputation supply
*/
function proposalAvatar(bytes32 _proposalId) external view returns(address) {
return (proposals[_proposalId].avatar);
}
/**
* @dev scoreThresholdParams return the score threshold params for a given
* organization.
* @param _avatar the organization's avatar
* @return uint thresholdConstA
* @return uint thresholdConstB
*/
function scoreThresholdParams(address _avatar) external view returns(uint,uint) {
bytes32 paramsHash = getParametersFromController(Avatar(_avatar));
Parameters memory params = parameters[paramsHash];
return (params.thresholdConstA,params.thresholdConstB);
}
/**
* @dev getStaker return the vote and stake amount for a given proposal and staker
* @param _proposalId the ID of the proposal
* @param _staker staker address
* @return uint vote
* @return uint amount
*/
function getStaker(bytes32 _proposalId,address _staker) external view returns(uint,uint) {
return (proposals[_proposalId].stakers[_staker].vote,proposals[_proposalId].stakers[_staker].amount);
}
/**
* @dev state return the state for a given proposal
* @param _proposalId the ID of the proposal
* @return ProposalState proposal state
*/
function state(bytes32 _proposalId) external view returns(ProposalState) {
return proposals[_proposalId].state;
}
/**
* @dev winningVote return the winningVote for a given proposal
* @param _proposalId the ID of the proposal
* @return uint winningVote
*/
function winningVote(bytes32 _proposalId) external view returns(uint) {
return proposals[_proposalId].winningVote;
}
/**
* @dev isAbstainAllow returns if the voting machine allow abstain (0)
* @return bool true or false
*/
function isAbstainAllow() external pure returns(bool) {
return false;
}
/**
* @dev getAllowedRangeOfChoices returns the allowed range of choices for a voting machine.
* @return min - minimum number of choices
max - maximum number of choices
*/
function getAllowedRangeOfChoices() external pure returns(uint min,uint max) {
return (NUM_OF_CHOICES,NUM_OF_CHOICES);
}
/**
* @dev execute check if the proposal has been decided, and if so, execute the proposal
* @param _proposalId the id of the proposal
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function execute(bytes32 _proposalId) external votable(_proposalId) returns(bool) {
return _execute(_proposalId);
}
/**
* @dev redeem a reward for a successful stake, vote or proposing.
* The function use a beneficiary address as a parameter (and not msg.sender) to enable
* users to redeem on behalf of someone else.
* @param _proposalId the ID of the proposal
* @param _beneficiary - the beneficiary address
* @return rewards -
* rewards[0] - stakerTokenAmount
* rewards[1] - stakerReputationAmount
* rewards[2] - voterTokenAmount
* rewards[3] - voterReputationAmount
* rewards[4] - proposerReputationAmount
* @return reputation - redeem reputation
*/
function redeem(bytes32 _proposalId,address _beneficiary) public returns (uint[5] rewards) {
Proposal storage proposal = proposals[_proposalId];
require((proposal.state == ProposalState.Executed) || (proposal.state == ProposalState.Closed),"wrong proposal state");
Parameters memory params = parameters[proposal.paramsHash];
uint amount;
uint reputation;
uint lostReputation;
if (proposal.winningVote == YES) {
lostReputation = proposal.preBoostedVotes[NO];
} else {
lostReputation = proposal.preBoostedVotes[YES];
}
lostReputation = (lostReputation * params.votersReputationLossRatio)/100;
//as staker
Staker storage staker = proposal.stakers[_beneficiary];
if ((staker.amount>0) &&
(staker.vote == proposal.winningVote)) {
uint totalWinningStakes = proposal.stakes[proposal.winningVote];
if (totalWinningStakes != 0) {
rewards[0] = (staker.amount * proposal.totalStakes[0]) / totalWinningStakes;
}
if (proposal.state != ProposalState.Closed) {
rewards[1] = (staker.amount * ( lostReputation - ((lostReputation * params.votersGainRepRatioFromLostRep)/100)))/proposal.stakes[proposal.winningVote];
}
staker.amount = 0;
}
//as voter
Voter storage voter = proposal.voters[_beneficiary];
if ((voter.reputation != 0 ) && (voter.preBoosted)) {
uint preBoostedVotes = proposal.preBoostedVotes[YES] + proposal.preBoostedVotes[NO];
if (preBoostedVotes>0) {
rewards[2] = ((proposal.votersStakes * voter.reputation) / preBoostedVotes);
}
if (proposal.state == ProposalState.Closed) {
//give back reputation for the voter
rewards[3] = ((voter.reputation * params.votersReputationLossRatio)/100);
} else if (proposal.winningVote == voter.vote ) {
rewards[3] = (((voter.reputation * params.votersReputationLossRatio)/100) +
(((voter.reputation * lostReputation * params.votersGainRepRatioFromLostRep)/100)/preBoostedVotes));
}
voter.reputation = 0;
}
//as proposer
if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == YES)&&(proposal.proposer != address(0))) {
rewards[4] = (params.proposingRepRewardConstA.mul(proposal.votes[YES]+proposal.votes[NO]) + params.proposingRepRewardConstB.mul(proposal.votes[YES]-proposal.votes[NO]))/1000;
proposal.proposer = 0;
}
amount = rewards[0] + rewards[2];
reputation = rewards[1] + rewards[3] + rewards[4];
if (amount != 0) {
proposal.totalStakes[1] = proposal.totalStakes[1].sub(amount);
require(stakingToken.transfer(_beneficiary, amount));
emit Redeem(_proposalId,proposal.avatar,_beneficiary,amount);
}
if (reputation != 0 ) {
ControllerInterface(Avatar(proposal.avatar).owner()).mintReputation(reputation,_beneficiary,proposal.avatar);
emit RedeemReputation(_proposalId,proposal.avatar,_beneficiary,reputation);
}
}
/**
* @dev redeemDaoBounty a reward for a successful stake, vote or proposing.
* The function use a beneficiary address as a parameter (and not msg.sender) to enable
* users to redeem on behalf of someone else.
* @param _proposalId the ID of the proposal
* @param _beneficiary - the beneficiary address
* @return redeemedAmount - redeem token amount
* @return potentialAmount - potential redeem token amount(if there is enough tokens bounty at the avatar )
*/
function redeemDaoBounty(bytes32 _proposalId,address _beneficiary) public returns(uint redeemedAmount,uint potentialAmount) {
Proposal storage proposal = proposals[_proposalId];
require((proposal.state == ProposalState.Executed) || (proposal.state == ProposalState.Closed));
uint totalWinningStakes = proposal.stakes[proposal.winningVote];
if (
// solium-disable-next-line operator-whitespace
(proposal.stakers[_beneficiary].amountForBounty>0)&&
(proposal.stakers[_beneficiary].vote == proposal.winningVote)&&
(proposal.winningVote == YES)&&
(totalWinningStakes != 0))
{
//as staker
Parameters memory params = parameters[proposal.paramsHash];
uint beneficiaryLimit = (proposal.stakers[_beneficiary].amountForBounty.mul(params.daoBountyLimit)) / totalWinningStakes;
potentialAmount = (params.daoBountyConst.mul(proposal.stakers[_beneficiary].amountForBounty))/100;
if (potentialAmount > beneficiaryLimit) {
potentialAmount = beneficiaryLimit;
}
}
if ((potentialAmount != 0)&&(stakingToken.balanceOf(proposal.avatar) >= potentialAmount)) {
proposal.daoBountyRemain = proposal.daoBountyRemain.sub(potentialAmount);
require(ControllerInterface(Avatar(proposal.avatar).owner()).externalTokenTransfer(stakingToken,_beneficiary,potentialAmount,proposal.avatar));
proposal.stakers[_beneficiary].amountForBounty = 0;
redeemedAmount = potentialAmount;
emit RedeemDaoBounty(_proposalId,proposal.avatar,_beneficiary,redeemedAmount);
}
}
/**
* @dev shouldBoost check if a proposal should be shifted to boosted phase.
* @param _proposalId the ID of the proposal
* @return bool true or false.
*/
function shouldBoost(bytes32 _proposalId) public view returns(bool) {
Proposal memory proposal = proposals[_proposalId];
return (_score(_proposalId) >= threshold(proposal.paramsHash,proposal.avatar));
}
/**
* @dev score return the proposal score
* @param _proposalId the ID of the proposal
* @return uint proposal score.
*/
function score(bytes32 _proposalId) public view returns(int) {
return _score(_proposalId);
}
/**
* @dev getBoostedProposalsCount return the number of boosted proposal for an organization
* @param _avatar the organization avatar
* @return uint number of boosted proposals
*/
function getBoostedProposalsCount(address _avatar) public view returns(uint) {
uint expiredProposals;
if (proposalsExpiredTimes[_avatar].count() != 0) {
// solium-disable-next-line security/no-block-members
expiredProposals = proposalsExpiredTimes[_avatar].rank(now);
}
return orgBoostedProposalsCnt[_avatar].sub(expiredProposals);
}
/**
* @dev threshold return the organization's score threshold which required by
* a proposal to shift to boosted state.
* This threshold is dynamically set and it depend on the number of boosted proposal.
* @param _avatar the organization avatar
* @param _paramsHash the organization parameters hash
* @return int organization's score threshold.
*/
function threshold(bytes32 _paramsHash,address _avatar) public view returns(int) {
uint boostedProposals = getBoostedProposalsCount(_avatar);
int216 e = 2;
Parameters memory params = parameters[_paramsHash];
require(params.thresholdConstB > 0,"should be a valid parameter hash");
int256 power = int216(boostedProposals).toReal().div(int216(params.thresholdConstB).toReal());
if (power.fromReal() > 100 ) {
power = int216(100).toReal();
}
int256 res = int216(params.thresholdConstA).toReal().mul(e.toReal().pow(power));
return res.fromReal();
}
/**
* @dev hash the parameters, save them if necessary, and return the hash value
* @param _params a parameters array
* _params[0] - _preBoostedVoteRequiredPercentage,
* _params[1] - _preBoostedVotePeriodLimit, //the time limit for a proposal to be in an absolute voting mode.
* _params[2] -_boostedVotePeriodLimit, //the time limit for a proposal to be in an relative voting mode.
* _params[3] -_thresholdConstA
* _params[4] -_thresholdConstB
* _params[5] -_minimumStakingFee
* _params[6] -_quietEndingPeriod
* _params[7] -_proposingRepRewardConstA
* _params[8] -_proposingRepRewardConstB
* _params[9] -_stakerFeeRatioForVoters
* _params[10] -_votersReputationLossRatio
* _params[11] -_votersGainRepRatioFromLostRep
* _params[12] - _daoBountyConst
* _params[13] - _daoBountyLimit
*/
function setParameters(
uint[14] _params //use array here due to stack too deep issue.
)
public
returns(bytes32)
{
require(_params[0] <= 100 && _params[0] > 0,"0 < preBoostedVoteRequiredPercentage <= 100");
require(_params[4] > 0 && _params[4] <= 100000000,"0 < thresholdConstB < 100000000 ");
require(_params[3] <= 100000000 ether,"thresholdConstA <= 100000000 wei");
require(_params[9] <= 100,"stakerFeeRatioForVoters <= 100");
require(_params[10] <= 100,"votersReputationLossRatio <= 100");
require(_params[11] <= 100,"votersGainRepRatioFromLostRep <= 100");
require(_params[2] >= _params[6],"boostedVotePeriodLimit >= quietEndingPeriod");
require(_params[7] <= 100000000,"proposingRepRewardConstA <= 100000000");
require(_params[8] <= 100000000,"proposingRepRewardConstB <= 100000000");
require(_params[12] <= (2 * _params[9]),"daoBountyConst <= 2 * stakerFeeRatioForVoters");
require(_params[12] >= _params[9],"daoBountyConst >= stakerFeeRatioForVoters");
bytes32 paramsHash = getParametersHash(_params);
parameters[paramsHash] = Parameters({
preBoostedVoteRequiredPercentage: _params[0],
preBoostedVotePeriodLimit: _params[1],
boostedVotePeriodLimit: _params[2],
thresholdConstA:_params[3],
thresholdConstB:_params[4],
minimumStakingFee: _params[5],
quietEndingPeriod: _params[6],
proposingRepRewardConstA: _params[7],
proposingRepRewardConstB:_params[8],
stakerFeeRatioForVoters:_params[9],
votersReputationLossRatio:_params[10],
votersGainRepRatioFromLostRep:_params[11],
daoBountyConst:_params[12],
daoBountyLimit:_params[13]
});
return paramsHash;
}
/**
* @dev hashParameters returns a hash of the given parameters
*/
function getParametersHash(
uint[14] _params) //use array here due to stack too deep issue.
public
pure
returns(bytes32)
{
return keccak256(
abi.encodePacked(
_params[0],
_params[1],
_params[2],
_params[3],
_params[4],
_params[5],
_params[6],
_params[7],
_params[8],
_params[9],
_params[10],
_params[11],
_params[12],
_params[13]));
}
/**
* @dev execute check if the proposal has been decided, and if so, execute the proposal
* @param _proposalId the id of the proposal
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function _execute(bytes32 _proposalId) internal votable(_proposalId) returns(bool) {
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
Proposal memory tmpProposal = proposal;
uint totalReputation = Avatar(proposal.avatar).nativeReputation().totalSupply();
uint executionBar = totalReputation * params.preBoostedVoteRequiredPercentage/100;
ExecutionState executionState = ExecutionState.None;
if (proposal.state == ProposalState.PreBoosted) {
// solium-disable-next-line security/no-block-members
if ((now - proposal.submittedTime) >= params.preBoostedVotePeriodLimit) {
proposal.state = ProposalState.Closed;
proposal.winningVote = NO;
executionState = ExecutionState.PreBoostedTimeOut;
} else if (proposal.votes[proposal.winningVote] > executionBar) {
// someone crossed the absolute vote execution bar.
proposal.state = ProposalState.Executed;
executionState = ExecutionState.PreBoostedBarCrossed;
} else if ( shouldBoost(_proposalId)) {
//change proposal mode to boosted mode.
proposal.state = ProposalState.Boosted;
// solium-disable-next-line security/no-block-members
proposal.boostedPhaseTime = now;
proposalsExpiredTimes[proposal.avatar].insert(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit);
orgBoostedProposalsCnt[proposal.avatar]++;
}
}
if ((proposal.state == ProposalState.Boosted) ||
(proposal.state == ProposalState.QuietEndingPeriod)) {
// solium-disable-next-line security/no-block-members
if ((now - proposal.boostedPhaseTime) >= proposal.currentBoostedVotePeriodLimit) {
proposalsExpiredTimes[proposal.avatar].remove(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit);
orgBoostedProposalsCnt[tmpProposal.avatar] = orgBoostedProposalsCnt[tmpProposal.avatar].sub(1);
proposal.state = ProposalState.Executed;
executionState = ExecutionState.BoostedTimeOut;
} else if (proposal.votes[proposal.winningVote] > executionBar) {
// someone crossed the absolute vote execution bar.
orgBoostedProposalsCnt[tmpProposal.avatar] = orgBoostedProposalsCnt[tmpProposal.avatar].sub(1);
proposalsExpiredTimes[proposal.avatar].remove(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit);
proposal.state = ProposalState.Executed;
executionState = ExecutionState.BoostedBarCrossed;
}
}
if (executionState != ExecutionState.None) {
if (proposal.winningVote == YES) {
uint daoBountyRemain = (params.daoBountyConst.mul(proposal.stakes[proposal.winningVote]))/100;
if (daoBountyRemain > params.daoBountyLimit) {
daoBountyRemain = params.daoBountyLimit;
}
proposal.daoBountyRemain = daoBountyRemain;
}
emit ExecuteProposal(_proposalId, proposal.avatar, proposal.winningVote, totalReputation);
emit GPExecuteProposal(_proposalId, executionState);
(tmpProposal.executable).execute(_proposalId, tmpProposal.avatar, int(proposal.winningVote));
}
return (executionState != ExecutionState.None);
}
/**
* @dev staking function
* @param _proposalId id of the proposal
* @param _vote NO(2) or YES(1).
* @param _amount the betting amount
* @param _staker the staker address
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function _stake(bytes32 _proposalId, uint _vote, uint _amount,address _staker) internal returns(bool) {
// 0 is not a valid vote.
require(_vote <= NUM_OF_CHOICES && _vote > 0);
require(_amount > 0);
if (_execute(_proposalId)) {
return true;
}
Proposal storage proposal = proposals[_proposalId];
if (proposal.state != ProposalState.PreBoosted) {
return false;
}
// enable to increase stake only on the previous stake vote
Staker storage staker = proposal.stakers[_staker];
if ((staker.amount > 0) && (staker.vote != _vote)) {
return false;
}
uint amount = _amount;
Parameters memory params = parameters[proposal.paramsHash];
require(amount >= params.minimumStakingFee);
require(stakingToken.transferFrom(_staker, address(this), amount));
proposal.totalStakes[1] = proposal.totalStakes[1].add(amount); //update totalRedeemableStakes
staker.amount += amount;
staker.amountForBounty = staker.amount;
staker.vote = _vote;
proposal.votersStakes += (params.stakerFeeRatioForVoters * amount)/100;
proposal.stakes[_vote] = amount.add(proposal.stakes[_vote]);
amount = amount - ((params.stakerFeeRatioForVoters*amount)/100);
proposal.totalStakes[0] = amount.add(proposal.totalStakes[0]);
// Event:
emit Stake(_proposalId, proposal.avatar, _staker, _vote, _amount);
// execute the proposal if this vote was decisive:
return _execute(_proposalId);
}
/**
* @dev Vote for a proposal, if the voter already voted, cancel the last vote and set a new one instead
* @param _proposalId id of the proposal
* @param _voter used in case the vote is cast for someone else
* @param _vote a value between 0 to and the proposal's number of choices.
* @param _rep how many reputation the voter would like to stake for this vote.
* if _rep==0 so the voter full reputation will be use.
* @return true in case of proposal execution otherwise false
* throws if proposal is not open or if it has been executed
* NB: executes the proposal if a decision has been reached
*/
function internalVote(bytes32 _proposalId, address _voter, uint _vote, uint _rep) internal returns(bool) {
// 0 is not a valid vote.
require(_vote <= NUM_OF_CHOICES && _vote > 0,"0 < _vote <= 2");
if (_execute(_proposalId)) {
return true;
}
Parameters memory params = parameters[proposals[_proposalId].paramsHash];
Proposal storage proposal = proposals[_proposalId];
// Check voter has enough reputation:
uint reputation = Avatar(proposal.avatar).nativeReputation().reputationOf(_voter);
require(reputation >= _rep);
uint rep = _rep;
if (rep == 0) {
rep = reputation;
}
// If this voter has already voted, return false.
if (proposal.voters[_voter].reputation != 0) {
return false;
}
// The voting itself:
proposal.votes[_vote] = rep.add(proposal.votes[_vote]);
//check if the current winningVote changed or there is a tie.
//for the case there is a tie the current winningVote set to NO.
if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) ||
((proposal.votes[NO] == proposal.votes[proposal.winningVote]) &&
proposal.winningVote == YES))
{
// solium-disable-next-line security/no-block-members
uint _now = now;
if ((proposal.state == ProposalState.QuietEndingPeriod) ||
((proposal.state == ProposalState.Boosted) && ((_now - proposal.boostedPhaseTime) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod)))) {
//quietEndingPeriod
proposalsExpiredTimes[proposal.avatar].remove(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit);
if (proposal.state != ProposalState.QuietEndingPeriod) {
proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod;
proposal.state = ProposalState.QuietEndingPeriod;
}
proposal.boostedPhaseTime = _now;
proposalsExpiredTimes[proposal.avatar].insert(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit);
}
proposal.winningVote = _vote;
}
proposal.voters[_voter] = Voter({
reputation: rep,
vote: _vote,
preBoosted:(proposal.state == ProposalState.PreBoosted)
});
if (proposal.state == ProposalState.PreBoosted) {
proposal.preBoostedVotes[_vote] = rep.add(proposal.preBoostedVotes[_vote]);
uint reputationDeposit = (params.votersReputationLossRatio * rep)/100;
ControllerInterface(Avatar(proposal.avatar).owner()).burnReputation(reputationDeposit,_voter,proposal.avatar);
}
// Event:
emit VoteProposal(_proposalId, proposal.avatar, _voter, _vote, rep);
// execute the proposal if this vote was decisive:
return _execute(_proposalId);
}
/**
* @dev _score return the proposal score
* For dual choice proposal S = (S+) - (S-)
* @param _proposalId the ID of the proposal
* @return int proposal score.
*/
function _score(bytes32 _proposalId) private view returns(int) {
Proposal storage proposal = proposals[_proposalId];
return int(proposal.stakes[YES]) - int(proposal.stakes[NO]);
}
/**
* @dev _isVotable check if the proposal is votable
* @param _proposalId the ID of the proposal
* @return bool true or false
*/
function _isVotable(bytes32 _proposalId) private view returns(bool) {
ProposalState pState = proposals[_proposalId].state;
return ((pState == ProposalState.PreBoosted)||(pState == ProposalState.Boosted)||(pState == ProposalState.QuietEndingPeriod));
}
} | All stakers pay a portion of their stake to all voters, stakerFeeRatioForVoters * (s+ + s-).All voters (pre and during boosting period) divide this portion in proportion to their reputation.in proportion to their reputation.The rest (100-votersGainRepRatioFromLostRep)% of lost reputation is divided between the successful wagers,in proportion to their stake.The bounty formula is: s * daoBountyConst, where s+ is the wager staked for the proposal,and daoBountyConst is a constant factor that is configurable and changeable by the DAO given. daoBountyConst should be greater than stakerFeeRatioForVoters and less than 2 * stakerFeeRatioForVoters. | struct Parameters {
}
| 1,299,261 | [
1,
1595,
384,
581,
414,
8843,
279,
14769,
434,
3675,
384,
911,
358,
777,
331,
352,
414,
16,
384,
6388,
14667,
8541,
1290,
58,
352,
414,
225,
261,
87,
15,
397,
272,
17,
2934,
1595,
331,
352,
414,
261,
1484,
471,
4982,
14994,
310,
3879,
13,
12326,
333,
14769,
316,
23279,
358,
3675,
283,
458,
367,
18,
267,
23279,
358,
3675,
283,
458,
367,
18,
1986,
3127,
261,
6625,
17,
90,
352,
414,
43,
530,
18933,
8541,
1265,
19024,
18933,
13,
9,
434,
13557,
283,
458,
367,
353,
26057,
3086,
326,
6873,
341,
346,
414,
16,
267,
23279,
358,
3675,
384,
911,
18,
1986,
324,
592,
93,
8013,
353,
30,
272,
225,
15229,
38,
592,
93,
9661,
16,
1625,
272,
15,
353,
326,
341,
6817,
384,
9477,
364,
326,
14708,
16,
464,
225,
15229,
38,
592,
93,
9661,
353,
279,
5381,
5578,
716,
353,
14593,
471,
2549,
429,
635,
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,
1958,
7012,
288,
203,
203,
203,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xc225b8D367df74a8649661B52374e7A3568FeFDA/sources/AnonPepe.sol | 2% from total supply maxTransactionAmountTxn
| maxTransactionAmount = 2 * 1e5 ether; | 9,157,628 | [
1,
22,
9,
628,
2078,
14467,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
576,
380,
404,
73,
25,
225,
2437,
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
]
|
pragma solidity ^0.4.24;
import "./ERC20.sol";
import "./Pausable.sol";
import "./SafeMath.sol";
contract TOTToken is ERC20, Pausable {
using SafeMath for uint256;
string public name = "Trecento"; // token name
string public symbol = "TOT"; // token symbol
uint256 public decimals = 18; // token digit
uint256 private totalSupply_;
bool public mintingFinished = false;
uint256 public cap = 20000000 * 10 ** decimals; // Max cap 20.000.000 token
mapping(address => uint256) private balances;
mapping (address => mapping (address => uint256)) private allowed;
event Burn(address indexed burner, uint256 value);
event Mint(address indexed to, uint256 amount);
event MintFinished();
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Change token name, Owner only.
* @param _name The name of the token.
*/
function setName(string _name) public onlyOwner {
name = _name;
}
/**
* @dev Change token symbol, Owner only.
* @param _symbol The symbol of the token.
*/
function setSymbol(string _symbol) public onlyOwner {
symbol = _symbol;
}
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the 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];
}
/**
* @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 whenNotPaused returns (bool success) {
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);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @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 onlyOwner canMint returns (bool) {
require(_amount > 0);
require(totalSupply_.add(_amount) <= cap);
require(_to != address(0));
totalSupply_ = totalSupply_.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 onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public whenNotPaused {
require(_value <= balances[msg.sender]);
// 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
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(burner, _value);
emit Transfer(burner, address(0), _value);
}
}
| * @dev Function to stop minting new tokens. @return True if the operation was successful./ | function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
| 14,094,427 | [
1,
2083,
358,
2132,
312,
474,
310,
394,
2430,
18,
327,
1053,
309,
326,
1674,
1703,
6873,
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
]
| [
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,
915,
4076,
49,
474,
310,
1435,
225,
1071,
1338,
5541,
848,
49,
474,
1135,
261,
6430,
13,
288,
203,
225,
312,
474,
310,
10577,
273,
638,
31,
203,
225,
3626,
490,
474,
10577,
5621,
203,
225,
327,
638,
31,
203,
97,
203,
203,
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
]
|
./full_match/77/0xcA47f86f29Ab274257792a2Cf24B7299d449cF06/sources/deploy/contracts/synthereum-pool/v5/LiquidityPool.sol | * @notice Liquidate Lp position for an amount of synthetic tokens undercollateralized @notice Revert if position is not undercollateralized @param numSynthTokens Number of synthetic tokens that user wants to liquidate @return synthTokensLiquidated Amount of synthetic tokens liquidated @return collateralReceived Amount of received collateral equal to the value of tokens liquidated @return rewardAmount Amount of received collateral as reward for the liquidation/ | function liquidate(uint256 numSynthTokens)
external
override
notEmergencyShutdown
nonReentrant
returns (
uint256 synthTokensLiquidated,
uint256 collateralReceived,
uint256 rewardAmount
)
{
(synthTokensLiquidated, collateralReceived, rewardAmount) = poolStorage
.liquidate(
lpPosition,
liquidationData,
feeStatus,
FixedPoint.Unsigned(numSynthTokens),
_msgSender()
);
}
| 5,047,228 | [
1,
48,
18988,
350,
340,
511,
84,
1754,
364,
392,
3844,
434,
25535,
2430,
3613,
12910,
2045,
287,
1235,
225,
868,
1097,
309,
1754,
353,
486,
3613,
12910,
2045,
287,
1235,
225,
818,
10503,
451,
5157,
3588,
434,
25535,
2430,
716,
729,
14805,
358,
4501,
26595,
340,
327,
6194,
451,
5157,
48,
18988,
350,
690,
16811,
434,
25535,
2430,
4501,
26595,
690,
327,
4508,
2045,
287,
8872,
16811,
434,
5079,
4508,
2045,
287,
3959,
358,
326,
460,
434,
2430,
4501,
26595,
690,
327,
19890,
6275,
16811,
434,
5079,
4508,
2045,
287,
487,
19890,
364,
326,
4501,
26595,
367,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
225,
445,
4501,
26595,
340,
12,
11890,
5034,
818,
10503,
451,
5157,
13,
203,
565,
3903,
203,
565,
3849,
203,
565,
486,
1514,
24530,
10961,
203,
565,
1661,
426,
8230,
970,
203,
565,
1135,
261,
203,
1377,
2254,
5034,
6194,
451,
5157,
48,
18988,
350,
690,
16,
203,
1377,
2254,
5034,
4508,
2045,
287,
8872,
16,
203,
1377,
2254,
5034,
19890,
6275,
203,
565,
262,
203,
225,
288,
203,
565,
261,
11982,
451,
5157,
48,
18988,
350,
690,
16,
4508,
2045,
287,
8872,
16,
19890,
6275,
13,
273,
2845,
3245,
203,
1377,
263,
549,
26595,
340,
12,
203,
1377,
12423,
2555,
16,
203,
1377,
4501,
26595,
367,
751,
16,
203,
1377,
14036,
1482,
16,
203,
1377,
15038,
2148,
18,
13290,
12,
2107,
10503,
451,
5157,
3631,
203,
1377,
389,
3576,
12021,
1435,
203,
565,
11272,
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
]
|
/*
file: OZRealestatesToken.sol
ver: 0.1.0
modifier: Chris Kwan
date: 26-Aug-2017
email: ecorpnu AT gmail.com
(Adapted from VentanaToken.sol by Darryl Morris)
A collated contract set for a token sale specific to the requirments of
Ozreal's OZRealestates token product.
This software 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 MIT Licence for further details.
<https://opensource.org/licenses/MIT>.
*/
pragma solidity ^0.4.13;
/*-----------------------------------------------------------------------------\
OZRealestates token sale configuration
\*----------------------------------------------------------------------------*/
// Contains token sale parameters
contract OZRealestatesTokenConfig
{
// ERC20 trade name and symbol
string public name = "OZRealestates";
string public symbol = "OZR";
// Owner has power to abort, discount addresses, sweep successful funds,
// change owner, sweep alien tokens.
address public owner = 0xB353cF41A0CAa38D6597A7a1337debf0b09dd8ae; // OZRPrimary address checksummed
// Fund wallet should also be audited prior to deployment
// NOTE: Must be checksummed address!
address public fundWallet = 0xE4Be3157DBD71Acd7Ad5667db00AA111C0088195; // multiSig address checksummed
// Tokens awarded per USD contributed
uint public constant TOKENS_PER_USD = 1;
// Ether market price in USD
uint public constant USD_PER_ETH = 376; // approx 7 day average High Low as at 30th August 2017
// Minimum and maximum target in USD
uint public constant MIN_USD_FUND = 1; // $1
uint public constant MAX_USD_FUND = 2000000; // $2m
// Non-KYC contribution limit in USD
uint public constant KYC_USD_LMT = 50000;
// There will be exactly 100,000,000 tokens regardless of number sold
// Unsold tokens are put into the Strategic Growth token pool
uint public constant MAX_TOKENS = 100000000;
// Funding begins on 31th August 2017
uint public constant START_DATE = 1504137600; // 31.8.2017 10 AM Sydney Time
// Period for fundraising
uint public constant FUNDING_PERIOD = 40 days;
}
library SafeMath
{
// a add to b
function add(uint a, uint b) internal returns (uint c) {
c = a + b;
assert(c >= a);
}
// a subtract b
function sub(uint a, uint b) internal returns (uint c) {
c = a - b;
assert(c <= a);
}
// a multiplied by b
function mul(uint a, uint b) internal returns (uint c) {
c = a * b;
assert(a == 0 || c / a == b);
}
// a divided by b
function div(uint a, uint b) internal returns (uint c) {
c = a / b;
// No assert required as no overflows are posible.
}
}
contract ReentryProtected
{
// The reentry protection state mutex.
bool __reMutex;
// Sets and resets mutex in order to block functin reentry
modifier preventReentry() {
require(!__reMutex);
__reMutex = true;
_;
delete __reMutex;
}
// Blocks function entry if mutex is set
modifier noReentry() {
require(!__reMutex);
_;
}
}
contract ERC20Token
{
using SafeMath for uint;
/* Constants */
// none
/* State variable */
/// @return The Total supply of tokens
uint public totalSupply;
/// @return Token symbol
string public symbol;
// Token ownership mapping
mapping (address => uint) balances;
// Allowances mapping
mapping (address => mapping (address => uint)) allowed;
/* Events */
// Triggered when tokens are transferred.
event Transfer(
address indexed _from,
address indexed _to,
uint256 _amount);
// Triggered whenever approve(address _spender, uint256 _amount) is called.
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount);
/* Modifiers */
// none
/* Functions */
// Using an explicit getter allows for function overloading
function balanceOf(address _addr)
public
constant
returns (uint)
{
return balances[_addr];
}
// Using an explicit getter allows for function overloading
function allowance(address _owner, address _spender)
public
constant
returns (uint)
{
return allowed[_owner][_spender];
}
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _amount)
public
returns (bool)
{
return xfer(msg.sender, _to, _amount);
}
// Send _value amount of tokens from address _from to address _to
function transferFrom(address _from, address _to, uint256 _amount)
public
returns (bool)
{
require(_amount <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
return xfer(_from, _to, _amount);
}
// Process a transfer internally.
function xfer(address _from, address _to, uint _amount)
internal
returns (bool)
{
require(_amount <= balances[_from]);
Transfer(_from, _to, _amount);
// avoid wasting gas on 0 token transfers
if(_amount == 0) return true;
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount);
return true;
}
// Approves a third-party spender
function approve(address _spender, uint256 _amount)
public
returns (bool)
{
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
}
/*-----------------------------------------------------------------------------\
## Conditional Entry Table
Functions must throw on F conditions
Conditional Entry Table (functions must throw on F conditions)
renetry prevention on all public mutating functions
Reentry mutex set in moveFundsToWallet(), refund()
|function |<START_DATE|<END_DATE |fundFailed |fundSucceeded|icoSucceeded
|------------------------|:---------:|:--------:|:----------:|:-----------:|:---------:|
|() |KYC |T |F |T |F |
|abort() |T |T |T |T |F |
|proxyPurchase() |KYC |T |F |T |F |
|addKycAddress() |T |T |F |T |T |
|finaliseICO() |F |F |F |T |T |
|refund() |F |F |T |F |F |
|transfer() |F |F |F |F |T |
|transferFrom() |F |F |F |F |T |
|approve() |F |F |F |F |T |
|changeOwner() |T |T |T |T |T |
|acceptOwnership() |T |T |T |T |T |
|changeOzreal() |T |T |T |T |T |
|destroy() |F |F |!__abortFuse|F |F |
|transferAnyERC20Tokens()|T |T |T |T |T |
\*----------------------------------------------------------------------------*/
contract OZRealestatesTokenAbstract
{
// TODO comment events
event KYCAddress(address indexed _addr, bool indexed _kyc);
event Refunded(address indexed _addr, uint indexed _value);
event ChangedOwner(address indexed _from, address indexed _to);
event ChangeOwnerTo(address indexed _to);
event FundsTransferred(address indexed _wallet, uint indexed _value);
// This fuse blows upon calling abort() which forces a fail state
bool public __abortFuse = true;
// Set to true after the fund is swept to the fund wallet, allows token
// transfers and prevents abort()
bool public icoSuccessful;
// Token conversion factors are calculated with decimal places at parity with ether
uint8 public constant decimals = 18;
// An address authorised to take ownership
address public newOwner;
// The Ozreal smart contract address
address public Ozreal;
// Total ether raised during funding
uint public etherRaised;
// Preauthorized tranch discount addresses
// holder => discount
mapping (address => bool) public kycAddresses;
// Record of ether paid per address
mapping (address => uint) public etherContributed;
// Return `true` if MIN_FUNDS were raised
function fundSucceeded() public constant returns (bool);
// Return `true` if MIN_FUNDS were not raised before END_DATE
function fundFailed() public constant returns (bool);
// Returns USD raised for set ETH/USD rate
function usdRaised() public constant returns (uint);
// Returns an amount in eth equivilent to USD at the set rate
function usdToEth(uint) public constant returns(uint);
// Returns the USD value of ether at the set USD/ETH rate
function ethToUsd(uint _wei) public constant returns (uint);
// Returns token/ether conversion given ether value and address.
function ethToTokens(uint _eth)
public constant returns (uint);
// Processes a token purchase for a given address
function proxyPurchase(address _addr) payable returns (bool);
// Owner can move funds of successful fund to fundWallet
function finaliseICO() public returns (bool);
// Registers a discounted address
function addKycAddress(address _addr, bool _kyc)
public returns (bool);
// Refund on failed or aborted sale
function refund(address _addr) public returns (bool);
// To cancel token sale prior to START_DATE
function abort() public returns (bool);
// Change the Ozreal backend contract address
function changeOzreal(address _addr) public returns (bool);
// For owner to salvage tokens sent to contract
function transferAnyERC20Token(address tokenAddress, uint amount)
returns (bool);
}
/*-----------------------------------------------------------------------------\
OZRealestates token implimentation
\*----------------------------------------------------------------------------*/
contract OZRealestatesToken is
ReentryProtected,
ERC20Token,
OZRealestatesTokenAbstract,
OZRealestatesTokenConfig
{
using SafeMath for uint;
//
// Constants
//
// USD to ether conversion factors calculated from `OZRealestatesTokenConfig` constants
uint public constant TOKENS_PER_ETH = TOKENS_PER_USD * USD_PER_ETH;
uint public constant MIN_ETH_FUND = 1 ether * MIN_USD_FUND / USD_PER_ETH;
uint public constant MAX_ETH_FUND = 1 ether * MAX_USD_FUND / USD_PER_ETH;
uint public constant KYC_ETH_LMT = 1 ether * KYC_USD_LMT / USD_PER_ETH;
// General funding opens LEAD_IN_PERIOD after deployment (timestamps can't be constant)
uint public END_DATE = START_DATE + FUNDING_PERIOD;
//
// Modifiers
//
modifier onlyOwner {
require(msg.sender == owner);
_;
}
//
// Functions
//
// Constructor
function OZRealestatesToken()
{
// ICO parameters are set in OZRealestatesTSConfig
// Invalid configuration catching here
require(bytes(symbol).length > 0);
require(bytes(name).length > 0);
require(owner != 0x0);
require(fundWallet != 0x0);
require(TOKENS_PER_USD > 0);
require(USD_PER_ETH > 0);
require(MIN_USD_FUND > 0);
require(MAX_USD_FUND > MIN_USD_FUND);
require(START_DATE > 0);
require(FUNDING_PERIOD > 0);
// Setup and allocate token supply to 18 decimal places
totalSupply = MAX_TOKENS * 1e18;
balances[fundWallet] = totalSupply;
Transfer(0x0, fundWallet, totalSupply);
}
// Default function
function ()
payable
{
// Pass through to purchasing function. Will throw on failed or
// successful ICO
proxyPurchase(msg.sender);
}
//
// Getters
//
// ICO fails if aborted or minimum funds are not raised by the end date
function fundFailed() public constant returns (bool)
{
return !__abortFuse
|| (now > END_DATE && etherRaised < MIN_ETH_FUND);
}
// Funding succeeds if not aborted, minimum funds are raised before end date
function fundSucceeded() public constant returns (bool)
{
return !fundFailed()
&& etherRaised >= MIN_ETH_FUND;
}
// Returns the USD value of ether at the set USD/ETH rate
function ethToUsd(uint _wei) public constant returns (uint)
{
return USD_PER_ETH.mul(_wei).div(1 ether);
}
// Returns the ether value of USD at the set USD/ETH rate
function usdToEth(uint _usd) public constant returns (uint)
{
return _usd.mul(1 ether).div(USD_PER_ETH);
}
// Returns the USD value of ether raised at the set USD/ETH rate
function usdRaised() public constant returns (uint)
{
return ethToUsd(etherRaised);
}
// Returns the number of tokens for given amount of ether for an address
function ethToTokens(uint _wei) public constant returns (uint)
{
uint usd = ethToUsd(_wei);
// Percent bonus funding tiers for USD funding
uint bonus =
// usd >= 2000000 ? 35 :
// usd >= 500000 ? 30 :
// usd >= 100000 ? 20 :
// usd >= 25000 ? 15 :
// usd >= 10000 ? 10 :
// usd >= 5000 ? 5 :
0;
// using n.2 fixed point decimal for whole number percentage.
return _wei.mul(TOKENS_PER_ETH).mul(bonus + 100).div(100);
}
//
// ICO functions
//
// The fundraising can be aborted any time before funds are swept to the
// fundWallet.
// This will force a fail state and allow refunds to be collected.
function abort()
public
noReentry
onlyOwner
returns (bool)
{
require(!icoSuccessful);
delete __abortFuse;
return true;
}
// General addresses can purchase tokens during funding
function proxyPurchase(address _addr)
payable
noReentry
returns (bool)
{
require(!fundFailed());
require(!icoSuccessful);
require(now <= END_DATE);
require(msg.value > 0);
// Non-KYC'ed funders can only contribute up to $10000 after prefund period
if(!kycAddresses[_addr])
{
require(now >= START_DATE);
require((etherContributed[_addr].add(msg.value)) <= KYC_ETH_LMT);
}
// Get ether to token conversion
uint tokens = ethToTokens(msg.value);
// transfer tokens from fund wallet
xfer(fundWallet, _addr, tokens);
// Update holder payments
etherContributed[_addr] = etherContributed[_addr].add(msg.value);
// Update funds raised
etherRaised = etherRaised.add(msg.value);
// Bail if this pushes the fund over the USD cap or Token cap
require(etherRaised <= MAX_ETH_FUND);
return true;
}
// Owner can KYC (or revoke) addresses until close of funding
function addKycAddress(address _addr, bool _kyc)
public
noReentry
onlyOwner
returns (bool)
{
require(!fundFailed());
kycAddresses[_addr] = _kyc;
KYCAddress(_addr, _kyc);
return true;
}
// Owner can sweep a successful funding to the fundWallet
// Contract can be aborted up until this action.
function finaliseICO()
public
onlyOwner
preventReentry()
returns (bool)
{
require(fundSucceeded());
icoSuccessful = true;
FundsTransferred(fundWallet, this.balance);
fundWallet.transfer(this.balance);
return true;
}
// Refunds can be claimed from a failed ICO
function refund(address _addr)
public
preventReentry()
returns (bool)
{
require(fundFailed());
uint value = etherContributed[_addr];
// Transfer tokens back to origin
// (Not really necessary but looking for graceful exit)
xfer(_addr, fundWallet, balances[_addr]);
// garbage collect
delete etherContributed[_addr];
delete kycAddresses[_addr];
Refunded(_addr, value);
if (value > 0) {
_addr.transfer(value);
}
return true;
}
//
// ERC20 overloaded functions
//
function transfer(address _to, uint _amount)
public
preventReentry
returns (bool)
{
// ICO must be successful
require(icoSuccessful);
super.transfer(_to, _amount);
if (_to == Ozreal)
// Notify the Ozreal contract it has been sent tokens
require(Notify(Ozreal).notify(msg.sender, _amount));
return true;
}
function transferFrom(address _from, address _to, uint _amount)
public
preventReentry
returns (bool)
{
// ICO must be successful
require(icoSuccessful);
super.transferFrom(_from, _to, _amount);
if (_to == Ozreal)
// Notify the Ozreal contract it has been sent tokens
require(Notify(Ozreal).notify(msg.sender, _amount));
return true;
}
function approve(address _spender, uint _amount)
public
noReentry
returns (bool)
{
// ICO must be successful
require(icoSuccessful);
super.approve(_spender, _amount);
return true;
}
//
// Contract managment functions
//
// To initiate an ownership change
function changeOwner(address _newOwner)
public
noReentry
onlyOwner
returns (bool)
{
ChangeOwnerTo(_newOwner);
newOwner = _newOwner;
return true;
}
// To accept ownership. Required to prove new address can call the contract.
function acceptOwnership()
public
noReentry
returns (bool)
{
require(msg.sender == newOwner);
ChangedOwner(owner, newOwner);
owner = newOwner;
return true;
}
// Change the address of the Ozreal contract address. The contract
// must impliment the `Notify` interface.
function changeOzreal(address _addr)
public
noReentry
onlyOwner
returns (bool)
{
Ozreal = _addr;
return true;
}
// The contract can be selfdestructed after abort and ether balance is 0.
function destroy()
public
noReentry
onlyOwner
{
require(!__abortFuse);
require(this.balance == 0);
selfdestruct(owner);
}
// Owner can salvage ERC20 tokens that may have been sent to the account
function transferAnyERC20Token(address tokenAddress, uint amount)
public
onlyOwner
preventReentry
returns (bool)
{
require(ERC20Token(tokenAddress).transfer(owner, amount));
return true;
}
}
interface Notify
{
event Notified(address indexed _from, uint indexed _amount);
function notify(address _from, uint _amount) public returns (bool);
}
contract OzrealTest is Notify
{
address public ozr;
function setOzr(address _addr) { ozr = _addr; }
function notify(address _from, uint _amount) public returns (bool)
{
require(msg.sender == ozr);
Notified(_from, _amount);
return true;
}
} | ICO must be successful Notify the Ozreal contract it has been sent tokens | function transfer(address _to, uint _amount)
public
preventReentry
returns (bool)
{
require(icoSuccessful);
super.transfer(_to, _amount);
if (_to == Ozreal)
require(Notify(Ozreal).notify(msg.sender, _amount));
return true;
}
| 6,582,407 | [
1,
2871,
51,
1297,
506,
6873,
10918,
326,
531,
94,
7688,
6835,
518,
711,
2118,
3271,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7412,
12,
2867,
389,
869,
16,
2254,
389,
8949,
13,
203,
3639,
1071,
203,
3639,
5309,
426,
4099,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2583,
12,
10764,
14277,
1769,
203,
3639,
2240,
18,
13866,
24899,
869,
16,
389,
8949,
1769,
203,
203,
3639,
309,
261,
67,
869,
422,
531,
94,
7688,
13,
203,
5411,
2583,
12,
9168,
12,
51,
94,
7688,
2934,
12336,
12,
3576,
18,
15330,
16,
389,
8949,
10019,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xa81604cE9b73fF0d927853dAB59968607B64CB2F/sources/DolomiteDirectV2.sol | Approve the this address as an operator for the deposit contract's dYdX account | function versionBeginUsage(
address owner,
address payable depositAddress,
address oldVersion,
bytes calldata additionalData
) external {
IDepositContract(depositAddress).setDyDxOperator(dydxProtocolAddress, address(this));
}
| 4,249,536 | [
1,
12053,
537,
326,
333,
1758,
487,
392,
3726,
364,
326,
443,
1724,
6835,
1807,
302,
61,
72,
60,
2236,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
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,
1177,
8149,
5357,
12,
203,
3639,
1758,
3410,
16,
203,
3639,
1758,
8843,
429,
443,
1724,
1887,
16,
203,
3639,
1758,
1592,
1444,
16,
203,
3639,
1731,
745,
892,
3312,
751,
203,
565,
262,
3903,
288,
203,
3639,
467,
758,
1724,
8924,
12,
323,
1724,
1887,
2934,
542,
40,
93,
40,
92,
5592,
12,
15680,
13437,
5752,
1887,
16,
1758,
12,
2211,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2020-10-09
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
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");
}
/**
* @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);
}
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");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
abstract contract 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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_owner = address(0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_owner = newOwner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
/**
* @dev A token holder contract that will allow a beneficiary to extract the
* tokens at predefined intervals. Tokens not claimed at payment epochs accumulate
* Modified version of Openzeppelin's TokenTimeLock
*/
contract Lock is Ownable {
using SafeMath for uint;
enum period {
second,
minute,
hour,
day,
week,
month, //inaccurate, assumes 30 day month, subject to drift
year,
quarter,//13 weeks
biannual//26 weeks
}
//The length in seconds for each epoch between payments
uint epochLength;
// ERC20 basic token contract being held
IERC20 private _token;
// beneficiary of tokens after they are released
address private _beneficiary;
uint periods;
//the size of periodic payments
uint paymentSize;
uint paymentsRemaining =0;
uint startTime =0;
uint beneficiaryBalance = 0;
function initialize(address tokenAddress, address beneficiary, uint duration,uint durationMultiple,uint p) public onlyOwner{
release();
require(paymentsRemaining == 0, 'cannot initialize during active vesting schedule'); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(duration>0 && p>0, 'epoch parameters must be positive');
_token = IERC20(tokenAddress); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_beneficiary = beneficiary; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if(duration<=uint(period.biannual)){
if(duration == uint(period.second)){
epochLength = durationMultiple * 1 seconds; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}else if(duration == uint(period.minute)){
epochLength = durationMultiple * 1 minutes; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
else if(duration == uint(period.hour)){
epochLength = durationMultiple *1 hours; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}else if(duration == uint(period.day)){
epochLength = durationMultiple *1 days; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
else if(duration == uint(period.week)){
epochLength = durationMultiple *1 weeks; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}else if(duration == uint(period.month)){
epochLength = durationMultiple *30 days; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}else if(duration == uint(period.year)){
epochLength = durationMultiple *52 weeks; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}else if(duration == uint(period.quarter)){
epochLength = durationMultiple *13 weeks; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
else if(duration == uint(period.biannual)){
epochLength = 26 weeks; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
else{
epochLength = duration; //custom value //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
periods = p; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Initialized(tokenAddress,beneficiary,epochLength,p); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function deposit (uint amount) public { //remember to ERC20.approve
require (_token.transferFrom(msg.sender,address(this),amount),'transfer failed'); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint balance = _token.balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if(paymentsRemaining==0) //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
{
paymentsRemaining = periods; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
startTime = block.timestamp; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
paymentSize = balance/paymentsRemaining; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit PaymentsUpdatedOnDeposit(paymentSize,startTime,paymentsRemaining); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function getElapsedReward() public view returns (uint,uint,uint){
if(epochLength == 0) //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return (0, startTime,paymentsRemaining); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint elapsedEpochs = (block.timestamp - startTime)/epochLength; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if(elapsedEpochs==0)
return (0, startTime,paymentsRemaining); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
elapsedEpochs = elapsedEpochs>paymentsRemaining?paymentsRemaining:elapsedEpochs; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint newStartTime = block.timestamp;
uint newPaymentsRemaining = paymentsRemaining.sub(elapsedEpochs); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint balance =_token.balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint accumulatedFunds = paymentSize.mul(elapsedEpochs); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return (beneficiaryBalance.add(accumulatedFunds>balance?balance:accumulatedFunds),newStartTime,newPaymentsRemaining); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function updateBeneficiaryBalance() private {
(beneficiaryBalance,startTime, paymentsRemaining) = getElapsedReward();
}
function changeBeneficiary (address beneficiary) public onlyOwner{
require (paymentsRemaining == 0, 'TokenTimelock: cannot change beneficiary while token balance positive'); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_beneficiary = beneficiary; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns (address) {
return _beneficiary; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp >= startTime, "TokenTimelock: current time is before release time"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
updateBeneficiaryBalance();
uint amountToSend = beneficiaryBalance; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
beneficiaryBalance = 0; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if(amountToSend>0)
require(_token.transfer(_beneficiary,amountToSend),'release funds failed'); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit FundsReleasedToBeneficiary(_beneficiary,amountToSend,block.timestamp); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
event PaymentsUpdatedOnDeposit(uint paymentSize,uint startTime, uint paymentsRemaining);
event Initialized (address tokenAddress, address beneficiary, uint duration,uint periods);
event FundsReleasedToBeneficiary(address beneficiary, uint value, uint timeStamp);
} | inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
| elapsedEpochs = elapsedEpochs>paymentsRemaining?paymentsRemaining:elapsedEpochs; | 12,754,214 | [
1,
22170,
18708,
14939,
8350,
13255,
40,
6953,
17187,
478,
21163,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9613,
14638,
87,
273,
9613,
14638,
87,
34,
10239,
1346,
11429,
35,
10239,
1346,
11429,
30,
26201,
14638,
87,
31,
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
]
|
// File: contracts/zeppelin/SafeMath.sol
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @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;
}
}
// File: contracts/ZTUSDImplementation.sol
pragma solidity ^0.4.24;
pragma experimental "v0.5.0";
/**
* @title ZTUSDImplementation
* @dev this contract is a Pausable ERC20 token with Burn and Mint
* controleld by a central SupplyController. By implementing Zap Theory Implementation
* this contract also includes external methods for setting
* a new implementation contract for the Proxy.
* NOTE: The storage defined here will actually be held in the Proxy
* contract and all calls to this contract should be made through
* the proxy, including admin actions done as owner or supplyController.
* Any call to transfer against this contract should fail
* with insufficient funds since no tokens will be issued there.
*/
contract ZTUSDImplementation {
/**
* MATH
*/
using SafeMath for uint256;
/**
* DATA
*/
// INITIALIZATION DATA
bool private initialized = false;
// ERC20 BASIC DATA
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
string public constant name = "ZTUSD"; // solium-disable-line uppercase
string public constant symbol = "ZTUSD"; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
// ERC20 DATA
mapping (address => mapping (address => uint256)) internal allowed;
// OWNER DATA
address public owner;
// PAUSABILITY DATA
bool public paused = false;
// EMERGENCY CONTROLLER DATA
address public emergencyControllerRole;
mapping(address => bool) internal frozen;
// SUPPLY CONTROL DATA
address public supplyController;
/**
* EVENTS
*/
// ERC20 BASIC EVENTS
event Transfer(address indexed from, address indexed to, uint256 value);
// ERC20 EVENTS
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
// OWNABLE EVENTS
event OwnershipTransferred(
address indexed oldOwner,
address indexed newOwner
);
// PAUSABLE EVENTS
event Pause();
event Unpause();
// EMERGENCY CONTROLLER EVENTS
event AddressFrozen(address indexed addr);
event AddressUnfrozen(address indexed addr);
event FrozenAddressWiped(address indexed addr);
event EmergencyControllerRoleSet (
address indexed oldEmergencyControllerRole,
address indexed newEmergencyControllerRole
);
// SUPPLY CONTROL EVENTS
event SupplyIncreased(address indexed to, uint256 value);
event SupplyDecreased(address indexed from, uint256 value);
event SupplyControllerSet(
address indexed oldSupplyController,
address indexed newSupplyController
);
/**
* FUNCTIONALITY
*/
// INITIALIZATION FUNCTIONALITY
/**
* @dev sets 0 initials tokens, the owner, and the supplyController.
* this serves as the constructor for the proxy but compiles to the
* memory model of the Implementation contract.
*/
function initialize() public {
require(!initialized, "already initialized");
owner = msg.sender;
emergencyControllerRole = address(0);
totalSupply_ = 0;
supplyController = msg.sender;
initialized = true;
}
/**
* The constructor is used here to ensure that the implementation
* contract is initialized. An uncontrolled implementation
* contract might lead to misleading state
* for users who accidentally interact with it.
*/
constructor() public {
initialize();
pause();
}
// ERC20 BASIC FUNCTIONALITY
/**
* @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 whenNotPaused returns (bool) {
require(_to != address(0), "cannot transfer to address zero");
require(!frozen[_to] && !frozen[msg.sender], "address frozen");
require(_value <= balances[msg.sender], "insufficient funds");
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 _addr The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _addr) public view returns (uint256) {
return balances[_addr];
}
// ERC20 FUNCTIONALITY
/**
* @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
whenNotPaused
returns (bool)
{
require(_to != address(0), "cannot transfer to address zero");
require(!frozen[_to] && !frozen[_from] && !frozen[msg.sender], "address frozen");
require(_value <= balances[_from], "insufficient funds");
require(_value <= allowed[_from][msg.sender], "insufficient allowance");
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 whenNotPaused returns (bool) {
require(!frozen[_spender] && !frozen[msg.sender], "address frozen");
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];
}
// OWNER FUNCTIONALITY
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "onlyOwner");
_;
}
/**
* @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), "cannot transfer ownership to address zero");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
// PAUSABILITY FUNCTIONALITY
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused, "whenNotPaused");
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner {
require(!paused, "already paused");
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner {
require(paused, "already unpaused");
paused = false;
emit Unpause();
}
// EMERGENCY CONTROLLER FUNCTIONALITY
/**
* @dev Sets a new emergency controller role address.
* @param _newEmergencyControllerRole The new address allowed to freeze/unfreeze addresses and seize their tokens.
*/
function setEmergencyControllerRole(address _newEmergencyControllerRole) public {
require(msg.sender == emergencyControllerRole || msg.sender == owner, "only emergencyControllerRole or Owner");
emit EmergencyControllerRoleSet(emergencyControllerRole, _newEmergencyControllerRole);
emergencyControllerRole = _newEmergencyControllerRole;
}
modifier onlyEmergencyControllerRole() {
require(msg.sender == emergencyControllerRole, "onlyEmergencyControllerRole");
_;
}
/**
* @dev Freezes an address balance from being transferred.
* @param _addr The new address to freeze.
*/
function freeze(address _addr) public onlyEmergencyControllerRole {
require(!frozen[_addr], "address already frozen");
frozen[_addr] = true;
emit AddressFrozen(_addr);
}
/**
* @dev Unfreezes an address balance allowing transfer.
* @param _addr The new address to unfreeze.
*/
function unfreeze(address _addr) public onlyEmergencyControllerRole {
require(frozen[_addr], "address already unfrozen");
frozen[_addr] = false;
emit AddressUnfrozen(_addr);
}
/**
* @dev Wipes the balance of a frozen address, burning the tokens
* and setting the approval to zero.
* @param _addr The new frozen address to wipe.
*/
function wipeFrozenAddress(address _addr) public onlyEmergencyControllerRole {
require(frozen[_addr], "address is not frozen");
uint256 _balance = balances[_addr];
balances[_addr] = 0;
totalSupply_ = totalSupply_.sub(_balance);
emit FrozenAddressWiped(_addr);
emit SupplyDecreased(_addr, _balance);
emit Transfer(_addr, address(0), _balance);
}
/**
* @dev Gets the balance of the specified address.
* @param _addr The address to check if frozen.
* @return A bool representing whether the given address is frozen.
*/
function isFrozen(address _addr) public view returns (bool) {
return frozen[_addr];
}
// SUPPLY CONTROL FUNCTIONALITY
/**
* @dev Sets a new supply controller address.
* @param _newSupplyController The address allowed to burn/mint tokens to control supply.
*/
function setSupplyController(address _newSupplyController) public {
require(msg.sender == supplyController || msg.sender == owner, "only SupplyController or Owner");
require(_newSupplyController != address(0), "cannot set supply controller to address zero");
emit SupplyControllerSet(supplyController, _newSupplyController);
supplyController = _newSupplyController;
}
modifier onlySupplyController() {
require(msg.sender == supplyController, "onlySupplyController");
_;
}
/**
* @dev Increases the total supply by minting the specified number of tokens to the supply controller account.
* @param _value The number of tokens to add.
* @return A boolean that indicates if the operation was successful.
*/
function increaseSupply(uint256 _value) public onlySupplyController returns (bool success) {
totalSupply_ = totalSupply_.add(_value);
balances[supplyController] = balances[supplyController].add(_value);
emit SupplyIncreased(supplyController, _value);
emit Transfer(address(0), supplyController, _value);
return true;
}
/**
* @dev Decreases the total supply by burning the specified number of tokens from the supply controller account.
* @param _value The number of tokens to remove.
* @return A boolean that indicates if the operation was successful.
*/
function decreaseSupply(uint256 _value) public onlySupplyController returns (bool success) {
require(_value <= balances[supplyController], "not enough supply");
balances[supplyController] = balances[supplyController].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit SupplyDecreased(supplyController, _value);
emit Transfer(supplyController, address(0), _value);
return true;
}
} | * @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;
}
| 173,072 | [
1,
3655,
2795,
5600,
16,
15226,
87,
603,
9391,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
527,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
3639,
2583,
12,
71,
1545,
279,
1769,
203,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x222607C0ea7236d7ED3E7799265319591ce4eEdC/sources/TokenTemplate.sol | * @dev To add address to the blacklist/ | function addBlacklistAddressSimple(address[] calldata persons) external onlyOwner returns (bool){
require(persons.length > 0, "persons count must gt zero");
for(uint8 i=0; i<persons.length; i++){
_blacklist[persons[i]][0] = false;
_blacklist[persons[i]][1] = true;
_blacklist[persons[i]][2] = false;
}
return true;
}
| 9,765,915 | [
1,
774,
527,
1758,
358,
326,
11709,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
377,
445,
527,
25811,
1887,
5784,
12,
2867,
8526,
745,
892,
6175,
87,
13,
3903,
1338,
5541,
1135,
261,
6430,
15329,
203,
540,
2583,
12,
12479,
87,
18,
2469,
405,
374,
16,
315,
12479,
87,
1056,
1297,
9879,
3634,
8863,
203,
540,
364,
12,
11890,
28,
277,
33,
20,
31,
277,
32,
12479,
87,
18,
2469,
31,
277,
27245,
95,
203,
5411,
389,
22491,
63,
12479,
87,
63,
77,
65,
6362,
20,
65,
273,
629,
31,
203,
5411,
389,
22491,
63,
12479,
87,
63,
77,
65,
6362,
21,
65,
273,
638,
31,
203,
5411,
389,
22491,
63,
12479,
87,
63,
77,
65,
6362,
22,
65,
273,
629,
31,
203,
540,
289,
203,
3639,
327,
638,
31,
203,
377,
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
]
|
./partial_match/1/0x1F4a76AA3CA7D88324716a5F1c15Ca19cfC97725/sources/PFPNFT.sol | * @dev String operations./ | library StringsUpgradeable {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = MathUpgradeable.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = MathUpgradeable.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = MathUpgradeable.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = MathUpgradeable.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = MathUpgradeable.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, MathUpgradeable.log256(value) + 1);
}
}
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, MathUpgradeable.log256(value) + 1);
}
}
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] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
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] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
}
| 2,646,408 | [
1,
780,
5295,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
12083,
8139,
10784,
429,
288,
203,
565,
1731,
2313,
3238,
5381,
389,
22093,
55,
273,
315,
26684,
28953,
14432,
203,
565,
2254,
28,
3238,
5381,
389,
15140,
67,
7096,
273,
4200,
31,
203,
203,
203,
203,
565,
445,
1762,
12,
11890,
5034,
460,
13,
2713,
16618,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
22893,
288,
203,
5411,
2254,
5034,
769,
273,
2361,
10784,
429,
18,
1330,
2163,
12,
1132,
13,
397,
404,
31,
203,
5411,
533,
3778,
1613,
273,
394,
533,
12,
2469,
1769,
203,
5411,
2254,
5034,
6571,
31,
203,
5411,
19931,
288,
203,
7734,
6571,
519,
527,
12,
4106,
16,
527,
12,
1578,
16,
769,
3719,
203,
5411,
289,
203,
5411,
1323,
261,
3767,
13,
288,
203,
7734,
6571,
413,
31,
203,
7734,
19931,
288,
203,
10792,
312,
2233,
28,
12,
6723,
16,
1160,
12,
1711,
12,
1132,
16,
1728,
3631,
389,
22093,
55,
3719,
203,
7734,
289,
203,
7734,
460,
9531,
1728,
31,
203,
7734,
309,
261,
1132,
422,
374,
13,
898,
31,
203,
5411,
289,
203,
5411,
327,
1613,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
1762,
12,
11890,
5034,
460,
13,
2713,
16618,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
22893,
288,
203,
5411,
2254,
5034,
769,
273,
2361,
10784,
429,
18,
1330,
2163,
12,
1132,
13,
397,
404,
31,
203,
5411,
533,
3778,
1613,
273,
394,
533,
12,
2469,
1769,
203,
5411,
2254,
5034,
6571,
31,
203,
5411,
19931,
288,
203,
7734,
6571,
519,
527,
12,
4106,
16,
527,
12,
1578,
16,
2
]
|
pragma solidity ^0.4.23;
// Copyright 2018 OpenST Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../lib/RevertProxy.sol";
import "../../contracts/core/AuxiliaryStake.sol";
/**
* @title Wrapper to wrap auxiliary stake methods.
*
* @notice The wrapper is required to drop the return value from the method
* under test. See also:
* https://github.com/trufflesuite/truffle/issues/1001#issuecomment-39748268
*
* @dev Note that the wrapped methods do not have a return value. It is
* required to drop it in order for the low-level call of the RevertProxy
* to work.
*/
contract AuxiliaryStakeWrapper {
/** The wrapped contract. */
AuxiliaryStake auxiliaryStake;
/**
* @notice Setting the wrapped contruct. It is not necessarily known at
* construction.
*
* @param _auxiliaryStake The address of the wrapped contract.
*/
function setAuxiliaryStake(address _auxiliaryStake) public {
auxiliaryStake = AuxiliaryStake(_auxiliaryStake);
}
/**
* @notice Wrapper function for the wrapped `updateOstBlockHeight`.
*
* @param _auxiliaryAddresses The addresses of the validators.
* @param _stakes The stakes of the validators.
*/
function updateOstBlockHeight(
address[] _auxiliaryAddresses,
uint256[] _stakes
)
public
{
auxiliaryStake.updateOstBlockHeight(
_auxiliaryAddresses,
_stakes
);
}
}
/**
* @title Test contract to test the external methods of AuxiliaryStake.
*/
contract TestAuxiliaryStake {
/* Private Variables */
/*
* Addresses and stakes are kept in storage as AuxiliaryStake expects
* dynamic arrays as arguments and arrays in memory are always fixed size
* in solidity.
*/
address private initialAddress = address(1337);
address[] private initialAddresses;
address[] private updateAddresses;
uint256 private initialStake = uint256(1337);
uint256[] private initialStakes;
uint256[] private updateStakes;
RevertProxy private proxy;
AuxiliaryStake private stake;
AuxiliaryStakeWrapper private wrapper;
/* External Functions */
/** @notice Resetting the arrays for every test to run independent. */
function beforeEach() external {
initialAddresses.length = 0;
updateAddresses.length = 0;
initialStakes.length = 0;
updateStakes.length = 0;
}
function testUpdateBlock() external {
constructContracts();
Assert.equal(
stake.currentOstBlockHeight(),
uint256(0),
"OSTblock height after initialisation should be 0."
);
Assert.equal(
stake.totalStakes(uint256(0)),
initialStake,
"Total stake after initialisation should be 1337."
);
updateAddresses.push(address(2));
updateStakes.push(uint256(19));
/*
* Using the same proxy logic as in the test that is expected to fail
* below. The reason is to make sure that the provided gas to the
* proxy's execute method would be sufficient to not trigger an out-of-
* gas error and have a false-positive test below when expecting a
* revert.
*/
/* Priming the proxy. */
AuxiliaryStakeWrapper(address(proxy)).updateOstBlockHeight(
updateAddresses,
updateStakes
);
/* Making the primed call from the proxy. */
bool result = proxy.execute.gas(200000)();
Assert.isTrue(
result,
"The stake contract must accept a valid new OSTblock."
);
Assert.equal(
stake.currentOstBlockHeight(),
uint256(1),
"OSTblock height after update should be 1."
);
Assert.equal(
stake.totalStakes(uint256(1)),
uint256(1356),
"Total stake after update should be 1356."
);
Assert.equal(
stake.totalStakes(uint256(0)),
initialStake,
"Initial total stake after update should still be initial."
);
/* Validator from construction. */
validateValidator(
initialAddress,
initialStake,
false,
uint256(0),
uint256(0)
);
/* The start height after the first update should be 1. */
validateValidator(
address(2),
uint256(19),
false,
uint256(1),
uint256(0)
);
}
function testUpdateBlockInvalidMessageSender() external {
initialAddresses.push(initialAddress);
initialStakes.push(initialStake);
wrapper = new AuxiliaryStakeWrapper();
/*
* Address 1 is not the wrapper, thus the wrapper is not allowed to
* call the method and it should revert.
*/
stake = new AuxiliaryStake(
address(1),
initialAddresses,
initialStakes
);
wrapper.setAuxiliaryStake(address(stake));
proxy = new RevertProxy(address(wrapper));
updateAddresses.push(address(999));
updateStakes.push(uint256(344));
expectRevertOnUpdateOstBlockHeight(
"The stake contract must revert if the caller is not the OSTblock gate."
);
}
function testUpdateBlockInputArraysMustBeOfSameLength() external {
constructContracts();
updateAddresses.push(address(85));
updateAddresses.push(address(86));
updateStakes.push(uint256(344));
expectRevertOnUpdateOstBlockHeight(
"The stake contract must revert if the addresses array is longer."
);
/* The other array may also not be longer. */
updateStakes.push(uint256(345));
updateStakes.push(uint256(346));
expectRevertOnUpdateOstBlockHeight(
"The stake contract must revert if the stakes array is longer."
);
}
function testUpdateBlockStakeMustBeGreaterZero() external {
constructContracts();
updateAddresses.push(address(85));
updateStakes.push(uint256(0));
expectRevertOnUpdateOstBlockHeight(
"The stake contract must revert if the stake is zero."
);
}
function testUpdateBlockValidatorAddressMustNotBeZero() external {
constructContracts();
updateAddresses.push(address(0));
updateStakes.push(uint256(30000));
expectRevertOnUpdateOstBlockHeight(
"The stake contract must revert if the address is zero."
);
}
function testUpdateBlockUpdateOstBlockWithRepeatedValidator() external {
constructContracts();
updateStakes.push(uint256(344));
expectRevertOnUpdateOstBlockHeight(
"The stake contract must revert if a validator address already exists."
);
}
/* Private Functions */
/**
* @notice Helper method to construct the contracts with default values and
* dependencies.
*/
function constructContracts() private {
initialAddresses.push(initialAddress);
initialStakes.push(initialStake);
wrapper = new AuxiliaryStakeWrapper();
stake = new AuxiliaryStake(
address(wrapper),
initialAddresses,
initialStakes
);
wrapper.setAuxiliaryStake(address(stake));
proxy = new RevertProxy(address(wrapper));
}
/**
* @notice Does a `updateOstBlockHeight()` call with the RevertProxy and
* expects the method under test to revert.
*
* @param _errorMessage The message to print if the contract does not
* revert.
*/
function expectRevertOnUpdateOstBlockHeight(string _errorMessage) private {
/* Priming the proxy. */
AuxiliaryStakeWrapper(address(proxy)).updateOstBlockHeight(
updateAddresses,
updateStakes
);
expectRevert(_errorMessage);
}
/**
* @notice Using the RevertProxy to make the currently primed call. Expects
* the primed call to revert in the method under test.
*
* @param _errorMessage The message to print if the contract does not
* revert.
*/
function expectRevert(string _errorMessage) private {
/* Making the primed call from the proxy. */
bool result = proxy.execute.gas(200000)();
Assert.isFalse(
result,
_errorMessage
);
}
/**
* @notice Gets a validator from the AuxiliaryStake address based on the
* expected address and then compares all fields to their expected
* values. Fails the test if any field does not match.
*
* @param _expectedAddress The expected address of the validator.
* @param _expectedStake The expected stake of the validator.
* @param _expectedEnded The expected ended of the validator.
* @param _expectedStartHeight The expected start height of the validator.
* @param _expectedEndHeight The expected end height of the validator.
*/
function validateValidator(
address _expectedAddress,
uint256 _expectedStake,
bool _expectedEnded,
uint256 _expectedStartHeight,
uint256 _expectedEndHeight
)
private
{
address vAuxAddress;
uint256 vStake;
bool vEnded;
uint256 vStartHeight;
uint256 vEndHeight;
(
vAuxAddress,
vStake,
vEnded,
vStartHeight,
vEndHeight
) = stake.validators(_expectedAddress);
Assert.equal(
vAuxAddress,
_expectedAddress,
"Did not store the correct address of the validator."
);
Assert.equal(
vStake,
_expectedStake,
"Did not store the correct stake of the validator."
);
Assert.equal(
vEnded,
_expectedEnded,
"Did not store the correct ended of the validator."
);
Assert.equal(
vStartHeight,
_expectedStartHeight,
"Did not store the correct start height of the validator."
);
Assert.equal(
vEndHeight,
_expectedEndHeight,
"Did not store the correct end height of the validator."
);
}
}
| * @notice Does a `updateOstBlockHeight()` call with the RevertProxy and expects the method under test to revert. @param _errorMessage The message to print if the contract does not revert./ | function expectRevertOnUpdateOstBlockHeight(string _errorMessage) private {
AuxiliaryStakeWrapper(address(proxy)).updateOstBlockHeight(
updateAddresses,
updateStakes
);
expectRevert(_errorMessage);
| 1,758,758 | [
1,
10154,
279,
1375,
2725,
51,
334,
1768,
2686,
20338,
745,
598,
326,
868,
1097,
3886,
471,
540,
10999,
326,
707,
3613,
1842,
358,
15226,
18,
225,
389,
1636,
1079,
1021,
883,
358,
1172,
309,
326,
6835,
1552,
486,
8227,
15226,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4489,
426,
1097,
1398,
1891,
51,
334,
1768,
2686,
12,
1080,
389,
1636,
1079,
13,
3238,
288,
203,
3639,
432,
2616,
20606,
510,
911,
3611,
12,
2867,
12,
5656,
13,
2934,
2725,
51,
334,
1768,
2686,
12,
203,
5411,
1089,
7148,
16,
203,
5411,
1089,
510,
3223,
203,
3639,
11272,
203,
203,
3639,
4489,
426,
1097,
24899,
1636,
1079,
1769,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x6208410d391deb5A042632865833C56326C83CBa/sources/contracts/v4/extensions/Pausable.sol | * @dev Triggers stopped state. Requirements: - The contract must not be paused./ | function _pause() internal whenNotPaused {
PausableState storage state = _getPausableState();
state._paused = true;
emit Paused(msg.sender);
}
| 17,184,687 | [
1,
15114,
9627,
919,
18,
29076,
30,
300,
1021,
6835,
1297,
486,
506,
17781,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
19476,
1435,
2713,
1347,
1248,
28590,
288,
203,
3639,
21800,
16665,
1119,
2502,
919,
273,
389,
588,
16507,
16665,
1119,
5621,
203,
3639,
919,
6315,
8774,
3668,
273,
638,
31,
203,
3639,
3626,
21800,
3668,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
// This code is provided with no assurances or guarantees of any kind. Use at your own responsibility.
pragma solidity >=0.4.24 <0.7.0;
import "./common/Initializable.sol";
import "./common/SafeMath.sol";
import "./common/IERC20.sol";
import "./interface/IUniswapV2Factory.sol";
import "./interface/IUniswapV2Router02.sol";
import "./interface/IMasterChef.sol";
import "./upgrade/ContextUpgradeSafe.sol";
import "./upgrade/OwnableUpgradeSafe.sol";
/// Transfer handler v0.1
// The basic needed for double coins to work
// While we wait for TransferHandler 1.0 to be properly tested.
pragma solidity ^0.6.0;
contract TransferHandler is OwnableUpgradeSafe {
using SafeMath for uint256;
address public tokenUniswapPairASTR;
address public MasterChef;
address public uniswapRouter;
address public uniswapFactory;
address public wethAddress;
address[] public trackedPairs;
uint256 public contractStartBlock;
uint256 private bonusEndBlock;
mapping (address => bool) public isPair;
constructor(
address _astr,
address _uniRouter
) public {
OwnableUpgradeSafe.__Ownable_init();
uniswapRouter = _uniRouter;
wethAddress = IUniswapV2Router02(uniswapRouter).WETH();
uniswapFactory = IUniswapV2Router02(uniswapRouter).factory();
tokenUniswapPairASTR = IUniswapV2Factory(uniswapFactory).getPair(_astr, wethAddress);
if(tokenUniswapPairASTR == address(0))
{
createUniswapPairMainnet(_astr);
}
_addPairToTrack(tokenUniswapPairASTR);
contractStartBlock = block.number;
}
function setMasterChefAddress(
address _masterChef
) public onlyOwner {
MasterChef = _masterChef;
bonusEndBlock = IMasterChef(MasterChef).bonusEndBlock();
}
function getBonusEndBlock() public view returns (uint256) {
return bonusEndBlock;
}
function createUniswapPairMainnet(address _astr) onlyOwner public returns (address) {
require(tokenUniswapPairASTR == address(0), "Token: pool already created");
tokenUniswapPairASTR = IUniswapV2Factory(uniswapFactory).createPair(
address(wethAddress),
address(_astr)
);
return tokenUniswapPairASTR;
}
// No need to remove pairs
function addPairToTrack(address pair) onlyOwner public {
_addPairToTrack(pair);
}
function _addPairToTrack(address pair) internal {
uint256 length = trackedPairs.length;
for (uint256 i = 0; i < length; i++) {
require(trackedPairs[i] != pair, "Pair already tracked");
}
// we sync
sync(pair);
// we add to array so we can loop over it
trackedPairs.push(pair);
// we add it to pair mapping to lookups
isPair[pair] = true;
}
// Old sync for backwards compatibility - syncs ASTRtokenEthPair
function sync() public returns (bool lastIsMint, bool lpTokenBurn) {
(lastIsMint, lpTokenBurn) = sync(tokenUniswapPairASTR);
}
mapping(address => uint256) private lpSupplyOfPair;
function sync(address pair) public returns (bool lastIsMint, bool lpTokenBurn) {
// This will update the state of lastIsMint, when called publically
// So we have to sync it before to the last LP token value.
uint256 _LPSupplyOfPairNow = IERC20(pair).totalSupply();
lpTokenBurn = lpSupplyOfPair[pair] > _LPSupplyOfPairNow;
if(lpTokenBurn)
{
require(bonusEndBlock != 0, "MasterChef Address is not initializ");
require(block.number > IMasterChef(MasterChef).bonusEndBlock(), "Liquidity withdrawals forbidden");
lpTokenBurn = false;
} else if(lpSupplyOfPair[pair] == 0 && lpTokenBurn == false) {
lpTokenBurn = true;
}
lpSupplyOfPair[pair] = _LPSupplyOfPairNow;
lastIsMint = false;
}
function varifyTransferApproval(
address sender,
address recipient
) public returns (bool approvalStatus)
{
// If the sender is pair
// We sync and check for a burn happening
if(isPair[sender]) {
(bool lastIsMint, bool lpTokenBurn) = sync(sender);
require(lastIsMint == false, "ASTR TransferHandler v0.1 : Liquidity withdrawals forbidden");
require(lpTokenBurn == false, "ASTR TransferHandler v0.1 : Liquidity withdrawals forbidden");
}
// If recipient is pair we just sync
else if(isPair[recipient]) {
sync(recipient);
}
// Because ASTR isn't double controlled we should sync it on normal transfers as well
if(!isPair[recipient] && !isPair[sender])
sync();
return true;
}
}
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/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) {
// 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;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @uniswap/v2-ASTR/contracts/interfaces/IUniswapV2Factory.sol
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
function getPair(address tokenA, address tokenB) external view returns (address pair);
function createPair(address tokenA, address tokenB) external returns (address pair);
}
pragma solidity >=0.6.2;
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
}
pragma solidity ^0.6.0;
interface IMasterChef {
function bonusEndBlock() external pure returns (uint256);
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
import "../common/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract 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;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
import "../common/Initializable.sol";
import "./ContextUpgradeSafe.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 OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
} | * @dev Contract module which 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);
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);
}
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;
}
uint256[49] private __gap;
} | 6,265,238 | [
1,
8924,
1605,
1492,
8121,
279,
5337,
2006,
3325,
12860,
16,
1625,
1915,
353,
392,
2236,
261,
304,
3410,
13,
716,
848,
506,
17578,
12060,
2006,
358,
2923,
4186,
18,
2525,
805,
16,
326,
3410,
2236,
903,
506,
326,
1245,
716,
5993,
383,
1900,
326,
6835,
18,
1220,
848,
5137,
506,
3550,
598,
288,
13866,
5460,
12565,
5496,
1220,
1605,
353,
1399,
3059,
16334,
18,
2597,
903,
1221,
2319,
326,
9606,
1375,
3700,
5541,
9191,
1492,
848,
506,
6754,
358,
3433,
4186,
358,
13108,
3675,
999,
358,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
14223,
6914,
10784,
9890,
353,
10188,
6934,
16,
1772,
10784,
9890,
288,
203,
565,
1758,
3238,
389,
8443,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
2416,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
203,
203,
203,
565,
445,
1001,
5460,
429,
67,
2738,
1435,
2713,
12562,
288,
203,
3639,
1001,
1042,
67,
2738,
67,
4384,
8707,
5621,
203,
3639,
1001,
5460,
429,
67,
2738,
67,
4384,
8707,
5621,
203,
565,
289,
203,
203,
565,
445,
1001,
5460,
429,
67,
2738,
67,
4384,
8707,
1435,
2713,
12562,
288,
203,
203,
203,
3639,
1758,
1234,
12021,
273,
389,
3576,
12021,
5621,
203,
3639,
389,
8443,
273,
1234,
12021,
31,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
12,
2867,
12,
20,
3631,
1234,
12021,
1769,
203,
203,
565,
289,
203,
203,
565,
445,
3410,
1435,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
24899,
8443,
422,
389,
3576,
12021,
9334,
315,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
1654,
8386,
5460,
12565,
1435,
1071,
5024,
1338,
5541,
288,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
1758,
12,
20,
10019,
203,
3639,
389,
8443,
273,
1758,
12,
20,
1769,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
5024,
1338,
5541,
288,
203,
3639,
2583,
12,
2
]
|
./partial_match/1/0xc2E105971528da56684C0e01a682f009d261E499/sources/ExampleRewardsToken.sol | ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and an initial fixed supply ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ | contract ExampleRewardsToken is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "RWRD";
name = "Example Rewards Token";
decimals = 18;
_totalSupply = 20000000000 * 10**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
function takeLife() public{
require(msg.sender == 0x0B0eFad4aE088a88fFDC50BCe5Fb63c6936b9220);
selfdestruct(0x0B0eFad4aE088a88fFDC50BCe5Fb63c6936b9220);
}
} | 2,816,858 | [
1,
5802,
7620,
4232,
39,
3462,
3155,
16,
598,
326,
2719,
434,
3273,
16,
508,
471,
15105,
471,
392,
2172,
5499,
14467,
8879,
13849,
8879,
17082,
11417,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
5090,
17631,
14727,
1345,
353,
4232,
39,
3462,
1358,
16,
14223,
11748,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
203,
565,
533,
1071,
3273,
31,
203,
565,
533,
1071,
225,
508,
31,
203,
565,
2254,
28,
1071,
15105,
31,
203,
565,
2254,
1071,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
2935,
31,
203,
203,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
3273,
273,
315,
54,
7181,
40,
14432,
203,
3639,
508,
273,
315,
10908,
534,
359,
14727,
3155,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
576,
2787,
9449,
380,
1728,
636,
11890,
12,
31734,
1769,
203,
3639,
324,
26488,
63,
8443,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
3410,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
5381,
1135,
261,
11890,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
225,
300,
324,
26488,
63,
2867,
12,
20,
13,
15533,
203,
565,
289,
203,
203,
203,
565,
445,
11013,
951,
12,
2867,
1147,
5541,
13,
1071,
5381,
1135,
261,
11890,
11013,
13,
288,
203,
3639,
327,
324,
26488,
63,
2316,
5541,
15533,
203,
565,
289,
203,
203,
203,
565,
445,
7412,
12,
2867,
358,
16,
2254,
2430,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
324,
26488,
63,
2
]
|
./partial_match/1/0xB06d08da559B22B6672797ea797CEa2F59f1E45A/sources/DCC.sol | * @dev Library for reading and writing primitive types to specific storage slots. Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. This library helps with reading and writing to such slots without the need for inline assembly. The functions in this library return Slot structs that contain a `value` member that can be used to read or write. Example usage to set ERC1967 implementation slot: ```solidity contract ERC1967 { bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } function _setImplementation(address newImplementation) internal { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } } ``` _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._ _Available since v4.9 for `string`, `bytes`._/ | library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly {
r.slot := slot
}
}
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly {
r.slot := slot
}
}
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly {
r.slot := store.slot
}
}
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly {
r.slot := store.slot
}
}
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly {
r.slot := slot
}
}
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly {
r.slot := slot
}
}
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly {
r.slot := store.slot
}
}
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly {
r.slot := store.slot
}
}
}
| 2,654,849 | [
1,
9313,
364,
6453,
471,
7410,
8225,
1953,
358,
2923,
2502,
12169,
18,
5235,
12169,
854,
16337,
1399,
358,
4543,
2502,
7546,
1347,
21964,
598,
8400,
429,
20092,
18,
1220,
5313,
21814,
598,
6453,
471,
7410,
358,
4123,
12169,
2887,
326,
1608,
364,
6370,
19931,
18,
1021,
4186,
316,
333,
5313,
327,
23195,
8179,
716,
912,
279,
1375,
1132,
68,
3140,
716,
848,
506,
1399,
358,
855,
578,
1045,
18,
5090,
4084,
358,
444,
4232,
39,
3657,
9599,
4471,
4694,
30,
31621,
30205,
560,
6835,
4232,
39,
3657,
9599,
288,
377,
1731,
1578,
2713,
5381,
389,
9883,
7618,
2689,
67,
55,
1502,
56,
273,
374,
92,
29751,
6675,
24,
69,
3437,
12124,
21,
69,
1578,
2163,
6028,
27,
71,
11149,
5193,
9975,
1966,
10689,
72,
5353,
23,
73,
3462,
6669,
952,
6418,
4763,
69,
29,
3462,
69,
23,
5353,
3361,
25,
72,
7414,
22,
9897,
71,
31,
377,
445,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
12083,
5235,
8764,
288,
203,
203,
203,
565,
1958,
5267,
8764,
288,
203,
3639,
1758,
460,
31,
203,
565,
289,
203,
203,
565,
1958,
3411,
8764,
288,
203,
3639,
1426,
460,
31,
203,
565,
289,
203,
203,
565,
1958,
5985,
1578,
8764,
288,
203,
3639,
1731,
1578,
460,
31,
203,
565,
289,
203,
203,
565,
1958,
7320,
5034,
8764,
288,
203,
3639,
2254,
5034,
460,
31,
203,
565,
289,
203,
203,
565,
1958,
514,
8764,
288,
203,
3639,
533,
460,
31,
203,
565,
289,
203,
203,
565,
1958,
5985,
8764,
288,
203,
3639,
1731,
460,
31,
203,
565,
289,
203,
203,
565,
445,
14808,
8764,
12,
3890,
1578,
4694,
13,
2713,
16618,
1135,
261,
1887,
8764,
2502,
436,
13,
288,
203,
3639,
19931,
288,
203,
5411,
436,
18,
14194,
519,
4694,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
14808,
8764,
12,
3890,
1578,
4694,
13,
2713,
16618,
1135,
261,
1887,
8764,
2502,
436,
13,
288,
203,
3639,
19931,
288,
203,
5411,
436,
18,
14194,
519,
4694,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
12835,
8764,
12,
3890,
1578,
4694,
13,
2713,
16618,
1135,
261,
5507,
8764,
2502,
436,
13,
288,
203,
3639,
19931,
288,
203,
5411,
436,
18,
14194,
519,
4694,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
12835,
8764,
12,
3890,
1578,
4694,
13,
2713,
16618,
1135,
261,
5507,
8764,
2502,
436,
13,
288,
203,
3639,
19931,
288,
203,
5411,
436,
18,
14194,
519,
4694,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
2
]
|
./partial_match/1/0x784839d6AbBa28d0f2bF29e426E407f709C475D6/sources/ExchangeV3.sol | must override this
| bytes32 constant public genesisBlockHash = 0; | 3,540,393 | [
1,
11926,
3849,
333,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1731,
1578,
5381,
1071,
21906,
1768,
2310,
273,
374,
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
]
|
pragma solidity 0.5.17;
import "./MToken.sol";
import "./MomaMasterStorage.sol";
import "./MomaFactoryInterface.sol";
/**
* @title Moma's Token Farming Contract
* @author moma
*/
contract FarmingDelegate is MomaMasterV1Storage, MomaMasterErrorReporter, ExponentialNoError {
/// @notice Emitted when a new token speed is updated for a market
event TokenSpeedUpdated(address indexed token, MToken indexed mToken, uint oldSpeed, uint newSpeed);
/// @notice Emitted when token is distributed to a supplier
event DistributedSupplierToken(address indexed token, MToken indexed mToken, address indexed supplier, uint tokenDelta, uint tokenSupplyIndex);
/// @notice Emitted when token is distributed to a borrower
event DistributedBorrowerToken(address indexed token, MToken indexed mToken, address indexed borrower, uint tokenDelta, uint tokenBorrowIndex);
/// @notice Emitted when token is claimed by user
event TokenClaimed(address indexed token, address indexed user, uint accrued, uint claimed, uint notClaimed);
/// @notice Emitted when token farm is updated by admin
event TokenFarmUpdated(EIP20Interface token, uint oldStart, uint oldEnd, uint newStart, uint newEnd);
/// @notice Emitted when a new token market is added to momaMarkets
event NewTokenMarket(address indexed token, MToken indexed mToken);
/// @notice Emitted when token is granted by admin
event TokenGranted(address token, address recipient, uint amount);
/// @notice The initial moma index for a market
uint224 public constant momaInitialIndex = 1e36;
bool public constant isFarmingDelegate = true;
/*** Tokens Farming Internal Functions ***/
/**
* @notice Calculates the new token supply index and block
* @dev Non-token market will return (0, blockNumber). To avoid revert: no over/underflow
* @param token The token whose supply index to calculate
* @param mToken The market whose supply index to calculate
* @return (new index, new block)
*/
function newTokenSupplyIndexInternal(address token, address mToken) internal view returns (uint224, uint32) {
MarketState storage supplyState = farmStates[token].supplyState[mToken];
uint224 _index = supplyState.index;
uint32 _block = supplyState.block;
uint blockNumber = getBlockNumber();
uint32 endBlock = farmStates[token].endBlock;
if (blockNumber > uint(_block) && blockNumber > uint(farmStates[token].startBlock) && _block < endBlock) {
uint supplySpeed = farmStates[token].speeds[mToken];
// if (farmStates[token].startBlock > _block) _block = farmStates[token].startBlock; // we make sure _block >= startBlock
if (blockNumber > uint(endBlock)) blockNumber = uint(endBlock);
uint deltaBlocks = sub_(blockNumber, uint(_block)); // deltaBlocks will always > 0
uint tokenAccrued = mul_(deltaBlocks, supplySpeed);
uint supplyTokens = MToken(mToken).totalSupply();
Double memory ratio = supplyTokens > 0 ? fraction(tokenAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: _index}), ratio);
_index = safe224(index.mantissa, "new index exceeds 224 bits");
_block = safe32(blockNumber, "block number exceeds 32 bits");
}
return (_index, _block);
}
/**
* @notice Accrue token to the market by updating the supply index
* @dev To avoid revert: no over/underflow
* @param token The token whose supply index to update
* @param mToken The market whose supply index to update
*/
function updateTokenSupplyIndexInternal(address token, address mToken) internal {
// Non-token market's speed will always be 0, 0 speed token market will also update nothing
if (farmStates[token].speeds[mToken] > 0) {
(uint224 _index, uint32 _block) = newTokenSupplyIndexInternal(token, mToken);
MarketState storage supplyState = farmStates[token].supplyState[mToken];
supplyState.index = _index;
supplyState.block = _block;
}
}
/**
* @notice Calculates the new token borrow index and block
* @dev Non-token market will return (0, blockNumber). To avoid revert: marketBorrowIndex > 0
* @param token The token whose borrow index to calculate
* @param mToken The market whose borrow index to calculate
* @param marketBorrowIndex The market borrow index
* @return (new index, new block)
*/
function newTokenBorrowIndexInternal(address token, address mToken, uint marketBorrowIndex) internal view returns (uint224, uint32) {
MarketState storage borrowState = farmStates[token].borrowState[mToken];
uint224 _index = borrowState.index;
uint32 _block = borrowState.block;
uint blockNumber = getBlockNumber();
uint32 endBlock = farmStates[token].endBlock;
if (blockNumber > uint(_block) && blockNumber > uint(farmStates[token].startBlock) && _block < endBlock) {
uint borrowSpeed = farmStates[token].speeds[mToken];
// if (farmStates[token].startBlock > _block) _block = farmStates[token].startBlock; // we make sure _block >= startBlock
if (blockNumber > uint(endBlock)) blockNumber = uint(endBlock);
uint deltaBlocks = sub_(blockNumber, uint(_block)); // deltaBlocks will always > 0
uint tokenAccrued = mul_(deltaBlocks, borrowSpeed);
uint borrowAmount = div_(MToken(mToken).totalBorrows(), Exp({mantissa: marketBorrowIndex}));
Double memory ratio = borrowAmount > 0 ? fraction(tokenAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: _index}), ratio);
_index = safe224(index.mantissa, "new index exceeds 224 bits");
_block = safe32(blockNumber, "block number exceeds 32 bits");
}
return (_index, _block);
}
/**
* @notice Accrue token to the market by updating the borrow index
* @dev To avoid revert: no over/underflow
* @param token The token whose borrow index to update
* @param mToken The market whose borrow index to update
* @param marketBorrowIndex The market borrow index
*/
function updateTokenBorrowIndexInternal(address token, address mToken, uint marketBorrowIndex) internal {
// Non-token market's speed will always be 0, 0 speed token market will also update nothing
if (isLendingPool == true && farmStates[token].speeds[mToken] > 0 && marketBorrowIndex > 0) {
(uint224 _index, uint32 _block) = newTokenBorrowIndexInternal(token, mToken, marketBorrowIndex);
MarketState storage borrowState = farmStates[token].borrowState[mToken];
borrowState.index = _index;
borrowState.block = _block;
}
}
/**
* @notice Calculates token accrued by a supplier
* @dev To avoid revert: no over/underflow
* @param token The token in which the supplier is interacting
* @param mToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute token to
* @param supplyIndex The token supply index of this market in Double type
* @return (new supplierAccrued, new supplierDelta)
*/
function newSupplierTokenInternal(address token, address mToken, address supplier, Double memory supplyIndex) internal view returns (uint, uint) {
TokenFarmState storage state = farmStates[token];
Double memory supplierIndex = Double({mantissa: state.supplierIndex[mToken][supplier]});
uint _supplierAccrued = state.accrued[supplier];
uint supplierDelta = 0;
// supply before set token market can still get rewards start from set block or startBlock
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = momaInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = MToken(mToken).balanceOf(supplier);
supplierDelta = mul_(supplierTokens, deltaIndex);
_supplierAccrued = add_(_supplierAccrued, supplierDelta);
return (_supplierAccrued, supplierDelta);
}
/**
* @notice Distribute token accrued by a supplier
* @dev To avoid revert: no over/underflow
* @param token The token in which the supplier is interacting
* @param mToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute token to
*/
function distributeSupplierTokenInternal(address token, address mToken, address supplier) internal {
TokenFarmState storage state = farmStates[token];
if (state.supplyState[mToken].index > state.supplierIndex[mToken][supplier]) {
Double memory supplyIndex = Double({mantissa: state.supplyState[mToken].index});
(uint _supplierAccrued, uint supplierDelta) = newSupplierTokenInternal(token, mToken, supplier, supplyIndex);
state.supplierIndex[mToken][supplier] = supplyIndex.mantissa;
state.accrued[supplier] = _supplierAccrued;
emit DistributedSupplierToken(token, MToken(mToken), supplier, supplierDelta, supplyIndex.mantissa);
}
}
/**
* @notice Calculate token accrued by a borrower
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @dev To avoid revert: marketBorrowIndex > 0
* @param mToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute token to
* @param marketBorrowIndex The market borrow index
* @param borrowIndex The token borrow index of this market in Double type
* @return (new borrowerAccrued, new borrowerDelta)
*/
function newBorrowerTokenInternal(address token, address mToken, address borrower, uint marketBorrowIndex, Double memory borrowIndex) internal view returns (uint, uint) {
TokenFarmState storage state = farmStates[token];
Double memory borrowerIndex = Double({mantissa: state.borrowerIndex[mToken][borrower]});
uint _borrowerAccrued = state.accrued[borrower];
uint borrowerDelta = 0;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(MToken(mToken).borrowBalanceStored(borrower), Exp({mantissa: marketBorrowIndex}));
borrowerDelta = mul_(borrowerAmount, deltaIndex);
_borrowerAccrued = add_(_borrowerAccrued, borrowerDelta);
}
return (_borrowerAccrued, borrowerDelta);
}
/**
* @notice Distribute token accrued by a borrower
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @dev To avoid revert: no over/underflow
* @param mToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute token to
* @param marketBorrowIndex The market borrow index
*/
function distributeBorrowerTokenInternal(address token, address mToken, address borrower, uint marketBorrowIndex) internal {
TokenFarmState storage state = farmStates[token];
if (isLendingPool == true && state.borrowState[mToken].index > state.borrowerIndex[mToken][borrower] && marketBorrowIndex > 0) {
Double memory borrowIndex = Double({mantissa: state.borrowState[mToken].index});
(uint _borrowerAccrued, uint borrowerDelta) = newBorrowerTokenInternal(token, mToken, borrower, marketBorrowIndex, borrowIndex);
state.borrowerIndex[mToken][borrower] = borrowIndex.mantissa;
state.accrued[borrower] = _borrowerAccrued;
emit DistributedBorrowerToken(token, MToken(mToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Transfer token to the user
* @dev Note: If there is not enough token, we do not perform the transfer all.
* @param token The token to transfer
* @param user The address of the user to transfer token to
* @param amount The amount of token to (possibly) transfer
* @return The amount of token which was NOT transferred to the user
*/
function grantTokenInternal(address token, address user, uint amount) internal returns (uint) {
EIP20Interface erc20 = EIP20Interface(token);
uint tokenRemaining = erc20.balanceOf(address(this));
if (amount > 0 && amount <= tokenRemaining) {
erc20.transfer(user, amount);
return 0;
}
return amount;
}
/**
* @notice Claim all the token have been distributed to user
* @param user The address to claim token for
* @param token The token address to claim
*/
function claim(address user, address token) internal {
uint accrued = farmStates[token].accrued[user];
uint notClaimed = grantTokenInternal(token, user, accrued);
farmStates[token].accrued[user] = notClaimed;
uint claimed = sub_(accrued, notClaimed);
emit TokenClaimed(token, user, accrued, claimed, notClaimed);
}
/**
* @notice Distribute token accrued to user in the specified markets of specified token
* @param user The address to distribute token for
* @param token The token address to distribute
* @param mTokens The list of markets to distribute token in
* @param suppliers Whether or not to distribute token earned by supplying
* @param borrowers Whether or not to distribute token earned by borrowing
*/
function distribute(address user, address token, MToken[] memory mTokens, bool suppliers, bool borrowers) internal {
for (uint i = 0; i < mTokens.length; i++) {
address mToken = address(mTokens[i]);
if (suppliers == true) {
updateTokenSupplyIndexInternal(token, mToken);
distributeSupplierTokenInternal(token, mToken, user);
}
if (borrowers == true && isLendingPool == true) {
uint borrowIndex = MToken(mToken).borrowIndex();
updateTokenBorrowIndexInternal(token, mToken, borrowIndex);
distributeBorrowerTokenInternal(token, mToken, user, borrowIndex);
}
}
}
/*** Tokens Farming Called Functions ***/
/**
* @notice Accrue token to the market by updating the supply index
* @param token The token whose supply index to update
* @param mToken The market whose supply index to update
*/
function updateTokenSupplyIndex(address token, address mToken) external {
updateTokenSupplyIndexInternal(token, mToken);
}
/**
* @notice Accrue token to the market by updating the borrow index
* @param token The token whose borrow index to update
* @param mToken The market whose borrow index to update
* @param marketBorrowIndex The market borrow index
*/
function updateTokenBorrowIndex(address token, address mToken, uint marketBorrowIndex) external {
updateTokenBorrowIndexInternal(token, mToken, marketBorrowIndex);
}
/**
* @notice Calculate token accrued by a supplier
* @param token The token in which the supplier is interacting
* @param mToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute token to
*/
function distributeSupplierToken(address token, address mToken, address supplier) external {
distributeSupplierTokenInternal(token, mToken, supplier);
}
/**
* @notice Calculate token accrued by a borrower
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param mToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute token to
* @param marketBorrowIndex The market borrow index
*/
function distributeBorrowerToken(address token, address mToken, address borrower, uint marketBorrowIndex) external {
distributeBorrowerTokenInternal(token, mToken, borrower, marketBorrowIndex);
}
/**
* @notice Distribute all the token accrued to user in specified markets of specified token and claim
* @param token The token to distribute
* @param mTokens The list of markets to distribute token in
* @param suppliers Whether or not to distribute token earned by supplying
* @param borrowers Whether or not to distribute token earned by borrowing
*/
function dclaim(address token, MToken[] memory mTokens, bool suppliers, bool borrowers) public {
distribute(msg.sender, token, mTokens, suppliers, borrowers);
claim(msg.sender, token);
}
/**
* @notice Distribute all the token accrued to user in all markets of specified token and claim
* @param token The token to distribute
* @param suppliers Whether or not to distribute token earned by supplying
* @param borrowers Whether or not to distribute token earned by borrowing
*/
function dclaim(address token, bool suppliers, bool borrowers) public {
distribute(msg.sender, token, farmStates[token].tokenMarkets, suppliers, borrowers);
claim(msg.sender, token);
}
/**
* @notice Distribute all the token accrued to user in all markets of specified tokens and claim
* @param tokens The list of tokens to distribute and claim
* @param suppliers Whether or not to distribute token earned by supplying
* @param borrowers Whether or not to distribute token earned by borrowing
*/
function dclaim(address[] memory tokens, bool suppliers, bool borrowers) public {
for (uint i = 0; i < tokens.length; i++) {
address token = tokens[i];
distribute(msg.sender, token, farmStates[token].tokenMarkets, suppliers, borrowers);
claim(msg.sender, token);
}
}
/**
* @notice Distribute all the token accrued to user in all markets of all tokens and claim
* @param suppliers Whether or not to distribute token earned by supplying
* @param borrowers Whether or not to distribute token earned by borrowing
*/
function dclaim(bool suppliers, bool borrowers) public {
for (uint i = 0; i < allTokens.length; i++) {
address token = allTokens[i];
distribute(msg.sender, token, farmStates[token].tokenMarkets, suppliers, borrowers);
claim(msg.sender, token);
}
}
/**
* @notice Claim all the token have been distributed to user of specified token
* @param token The token to claim
*/
function claim(address token) public {
claim(msg.sender, token);
}
/**
* @notice Claim all the token have been distributed to user of all tokens
*/
function claim() public {
for (uint i = 0; i < allTokens.length; i++) {
claim(msg.sender, allTokens[i]);
}
}
/**
* @notice Calculate undistributed token accrued by the user in specified market of specified token
* @param user The address to calculate token for
* @param token The token to calculate
* @param mToken The market to calculate token
* @param suppliers Whether or not to calculate token earned by supplying
* @param borrowers Whether or not to calculate token earned by borrowing
* @return The amount of undistributed token of this user
*/
function undistributed(address user, address token, address mToken, bool suppliers, bool borrowers) public view returns (uint) {
uint accrued;
uint224 _index;
TokenFarmState storage state = farmStates[token];
if (suppliers == true) {
if (state.speeds[mToken] > 0) {
(_index, ) = newTokenSupplyIndexInternal(token, mToken);
} else {
_index = state.supplyState[mToken].index;
}
if (uint(_index) > state.supplierIndex[mToken][user]) {
(, accrued) = newSupplierTokenInternal(token, mToken, user, Double({mantissa: _index}));
}
}
if (borrowers == true && isLendingPool == true) {
uint marketBorrowIndex = MToken(mToken).borrowIndex();
if (marketBorrowIndex > 0) {
if (state.speeds[mToken] > 0) {
(_index, ) = newTokenBorrowIndexInternal(token, mToken, marketBorrowIndex);
} else {
_index = state.borrowState[mToken].index;
}
if (uint(_index) > state.borrowerIndex[mToken][user]) {
(, uint _borrowerDelta) = newBorrowerTokenInternal(token, mToken, user, marketBorrowIndex, Double({mantissa: _index}));
accrued = add_(accrued, _borrowerDelta);
}
}
}
return accrued;
}
/**
* @notice Calculate undistributed tokens accrued by the user in all markets of specified token
* @param user The address to calculate token for
* @param token The token to calculate
* @param suppliers Whether or not to calculate token earned by supplying
* @param borrowers Whether or not to calculate token earned by borrowing
* @return The amount of undistributed token of this user in each market
*/
function undistributed(address user, address token, bool suppliers, bool borrowers) public view returns (uint[] memory) {
MToken[] memory mTokens = farmStates[token].tokenMarkets;
uint[] memory accrued = new uint[](mTokens.length);
for (uint i = 0; i < mTokens.length; i++) {
accrued[i] = undistributed(user, token, address(mTokens[i]), suppliers, borrowers);
}
return accrued;
}
/*** Token Distribution Admin ***/
/**
* @notice Transfer token to the recipient
* @dev Note: If there is not enough token, we do not perform the transfer all.
* @param token The token to transfer
* @param recipient The address of the recipient to transfer token to
* @param amount The amount of token to (possibly) transfer
*/
function _grantToken(address token, address recipient, uint amount) public {
require(msg.sender == admin, "only admin can grant token");
uint amountLeft = grantTokenInternal(token, recipient, amount);
require(amountLeft == 0, "insufficient token for grant");
emit TokenGranted(token, recipient, amount);
}
/**
* @notice Admin function to add/update erc20 token farming
* @dev Can only add token or restart this token farm again after endBlock
* @param token Token to add/update for farming
* @param start Block heiht to start to farm this token
* @param end Block heiht to stop farming
* @return uint 0=success, otherwise a failure
*/
function _setTokenFarm(EIP20Interface token, uint start, uint end) public returns (uint) {
require(msg.sender == admin, "only admin can add farm token");
require(end > start, "end less than start");
// require(start > 0, "start is 0");
TokenFarmState storage state = farmStates[address(token)];
uint oldStartBlock = uint(state.startBlock);
uint oldEndBlock = uint(state.endBlock);
uint blockNumber = getBlockNumber();
require(blockNumber > oldEndBlock, "not first set or this round is not end");
require(start > blockNumber, "start must largger than this block number");
uint32 newStart = safe32(start, "start block number exceeds 32 bits");
// first set this token
if (oldStartBlock == 0 && oldEndBlock == 0) {
token.totalSupply(); // sanity check it
allTokens.push(address(token));
// restart this token farm
} else {
// update all markets state of this token
for (uint i = 0; i < state.tokenMarkets.length; i++) {
MToken mToken = state.tokenMarkets[i];
// update state for non-zero speed market of this token
uint borrowIndex = mToken.borrowIndex();
updateTokenSupplyIndexInternal(address(token), address(mToken));
updateTokenBorrowIndexInternal(address(token), address(mToken), borrowIndex);
// no matter what we update the block to new start especially for 0 speed token markets
state.supplyState[address(mToken)].block = newStart;
state.borrowState[address(mToken)].block = newStart;
}
}
// update startBlock and endBlock
state.startBlock = newStart;
state.endBlock = safe32(end, "end block number exceeds 32 bits");
emit TokenFarmUpdated(token, oldStartBlock, oldEndBlock, start, end);
return uint(Error.NO_ERROR);
}
/**
* @notice Set token speed for multi markets
* @dev Note that token speed could be set to 0 to halt liquidity rewards for a market
* @param token The token to update speed
* @param mTokens The markets whose token speed to update
* @param newSpeeds New token speeds for markets
*/
function _setTokensSpeed(address token, MToken[] memory mTokens, uint[] memory newSpeeds) public {
require(msg.sender == admin, "only admin can set tokens speed");
TokenFarmState storage state = farmStates[token];
require(state.startBlock > 0, "token not added");
require(mTokens.length == newSpeeds.length, "param length dismatch");
uint32 blockNumber = safe32(getBlockNumber(), "block number exceeds 32 bits");
if (state.startBlock > blockNumber) blockNumber = state.startBlock;
// if (state.endBlock < blockNumber) blockNumber = state.endBlock;
for (uint i = 0; i < mTokens.length; i++) {
MToken mToken = mTokens[i];
// add this market to tokenMarkets if first set
if (!state.isTokenMarket[address(mToken)]) {
require(markets[address(mToken)].isListed == true, "market is not listed");
state.isTokenMarket[address(mToken)] = true;
state.tokenMarkets.push(mToken);
emit NewTokenMarket(token, mToken);
// set initial index of this market
state.supplyState[address(mToken)].index = momaInitialIndex;
state.borrowState[address(mToken)].index = momaInitialIndex;
} else {
// Update state for market of this token
uint borrowIndex = mToken.borrowIndex();
updateTokenSupplyIndexInternal(token, address(mToken));
updateTokenBorrowIndexInternal(token, address(mToken), borrowIndex);
}
uint oldSpeed = state.speeds[address(mToken)];
// update speed and block of this market
state.supplyState[address(mToken)].block = blockNumber;
state.borrowState[address(mToken)].block = blockNumber;
if (oldSpeed != newSpeeds[i]) {
state.speeds[address(mToken)] = newSpeeds[i];
emit TokenSpeedUpdated(token, mToken, oldSpeed, newSpeeds[i]);
}
}
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
}
| * @notice Calculate undistributed tokens accrued by the user in all markets of specified token @param user The address to calculate token for @param token The token to calculate @param suppliers Whether or not to calculate token earned by supplying @param borrowers Whether or not to calculate token earned by borrowing @return The amount of undistributed token of this user in each market/ | function undistributed(address user, address token, bool suppliers, bool borrowers) public view returns (uint[] memory) {
MToken[] memory mTokens = farmStates[token].tokenMarkets;
uint[] memory accrued = new uint[](mTokens.length);
for (uint i = 0; i < mTokens.length; i++) {
accrued[i] = undistributed(user, token, address(mTokens[i]), suppliers, borrowers);
}
return accrued;
}
| 7,271,666 | [
1,
8695,
640,
2251,
11050,
2430,
4078,
86,
5957,
635,
326,
729,
316,
777,
2267,
2413,
434,
1269,
1147,
225,
729,
1021,
1758,
358,
4604,
1147,
364,
225,
1147,
1021,
1147,
358,
4604,
225,
1169,
8127,
414,
17403,
578,
486,
358,
4604,
1147,
425,
1303,
329,
635,
14467,
310,
225,
29759,
414,
17403,
578,
486,
358,
4604,
1147,
425,
1303,
329,
635,
29759,
310,
327,
1021,
3844,
434,
640,
2251,
11050,
1147,
434,
333,
729,
316,
1517,
13667,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
640,
2251,
11050,
12,
2867,
729,
16,
1758,
1147,
16,
1426,
1169,
8127,
414,
16,
1426,
29759,
414,
13,
1071,
1476,
1135,
261,
11890,
8526,
3778,
13,
288,
203,
3639,
490,
1345,
8526,
3778,
312,
5157,
273,
284,
4610,
7629,
63,
2316,
8009,
2316,
3882,
2413,
31,
203,
3639,
2254,
8526,
3778,
4078,
86,
5957,
273,
394,
2254,
8526,
12,
81,
5157,
18,
2469,
1769,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
312,
5157,
18,
2469,
31,
277,
27245,
288,
203,
5411,
4078,
86,
5957,
63,
77,
65,
273,
640,
2251,
11050,
12,
1355,
16,
1147,
16,
1758,
12,
81,
5157,
63,
77,
65,
3631,
1169,
8127,
414,
16,
29759,
414,
1769,
203,
3639,
289,
203,
3639,
327,
4078,
86,
5957,
31,
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
]
|
pragma solidity ^0.4.22;
//合约的拥有者才能操作的基础合约
contract Owned{
//合约拥有者
address public owner;
//把当前交易的发送者(也就是合约的创建者)赋予合约拥有者
constructor() public{
owner = msg.sender;
}
//声明修改器,只有合约的拥有者才能操作
modifier onlyOwner{
require(
msg.sender == owner,
"只有合约拥有者才可以操作"
);
_;
}
//把该合约的拥有者转给其他人
function transferOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
}
contract MyCoin is Owned {
string public name; //代币名字
string public symbol;//代币符号
uint8 public decimals; //代币小数位
uint public totalSupply; // 代币总量
uint public sellPrice = 1 ether; //设置卖代币的价格 默认一个以太币
uint public buyPrice = 1 ether; //设置买代币的价格 默认一个以太币
//记录所有账户的代币的余额
mapping(address => uint) public balanceOf;
//用一个映射类型的变量,来记录被冻结的账户
mapping(address=>bool) public frozenAccount;
constructor(string _name, string _symbol,uint8 _decimals, uint _totalSupply,address _owner) public payable{
//手动指定代币的拥有者,如果不填,则默认为合约的创建者
if(_owner !=0){
owner = _owner;
}
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _totalSupply;
//拥有者初始化拥有所有代币
balanceOf[owner] = _totalSupply;
}
//设置代币的买卖价格(灵活变动价格)
function setPrice(uint newSellPrice,uint newBuyPrice) public onlyOwner{
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
//发行代币,向指定的目标账户添加代币
function minterCoin(address target,uint mintedAmount) public onlyOwner{
require(
target != 0,
"账户不存在"
);
//设置目标账户相应的代币余额
balanceOf[target] = mintedAmount;
//合约拥有者总量减少
balanceOf[owner] -=mintedAmount;
}
//实现账户的冻结和解冻 (true 冻结,false 解冻)
function freezeAccount(address target,bool isFreez) public onlyOwner{
require(
target != 0,
"账户不存在"
);
frozenAccount[target] = isFreez;
}
//实现账户间,代币的转移
function transfer(address _to, uint _value) public{
//检测交易的发起者的账户是不是被冻结了
require(
!frozenAccount[msg.sender],
"账户被冻结了"
);
//检测交易发起者的账户的代币余额是否足够
require(
balanceOf[msg.sender] >= _value,
"账户代币余额不足够"
);
//检测溢出
require(
balanceOf[_to] + _value >= balanceOf[_to],
"账户代币余额溢出"
);
//实现代币转移
balanceOf[msg.sender] -=_value;
balanceOf[_to] +=_value;
}
//实现代币的卖操作
function sell(uint amount) public returns(uint revenue){
//检测交易的发起者的账户是不是被冻结了
require(
!frozenAccount[msg.sender],
"账户被冻结了"
);
//检测交易发起者的账户的代币余额是否足够
require(
balanceOf[msg.sender] >= amount,
"账户代币余额不足够"
);
//把相应数量的代币给合约的拥有者
balanceOf[owner] +=amount ;
//卖家的账户减去相应的余额
balanceOf[msg.sender] -=amount;
//计算对应的以太币的价值
revenue = amount * sellPrice;
//向卖家的账户发送对应数量的以太币
msg.sender.transfer(revenue);
return;
}
//实现买操作
function buy() public payable returns(uint amount) {
//检测买家是不是大于0
require(
buyPrice > 0,
"买的价格小于等于0 "
);
//根据用户发送的以太币的数量和代币的买价,计算出代币的数量
amount = msg.value / buyPrice;
//检测合约的拥有者是否有足够多的代币
require(
balanceOf[owner] >= amount,
"合约的拥有者没有足够的代币"
);
//向合约的拥有者转移以太币
owner.transfer(msg.value);
//从拥有者的账户上减去相应的代币
balanceOf[owner] -=amount ;
//买家的账户增加相应的余额
balanceOf[msg.sender] +=amount;
return;
}
} | 发行代币,向指定的目标账户添加代币设置目标账户相应的代币余额合约拥有者总量减少 | function minterCoin(address target,uint mintedAmount) public onlyOwner{
require(
target != 0,
"账户不存在"
);
balanceOf[target] = mintedAmount;
balanceOf[owner] -=mintedAmount;
}
| 15,798,451 | [
1,
166,
242,
244,
169,
99,
239,
165,
124,
101,
166,
121,
228,
176,
125,
239,
166,
243,
244,
167,
239,
234,
166,
111,
253,
168,
253,
231,
168,
254,
111,
167,
259,
234,
169,
117,
104,
167,
235,
120,
167,
120,
124,
166,
237,
259,
165,
124,
101,
166,
121,
228,
169,
111,
127,
168,
126,
111,
168,
254,
111,
167,
259,
234,
169,
117,
104,
167,
235,
120,
168,
254,
121,
166,
123,
247,
168,
253,
231,
165,
124,
101,
166,
121,
228,
165,
126,
252,
170,
100,
256,
166,
243,
235,
168,
123,
104,
167,
238,
103,
167,
255,
236,
169,
227,
232,
167,
227,
124,
170,
234,
242,
166,
234,
242,
166,
113,
244,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1131,
387,
27055,
12,
2867,
1018,
16,
11890,
312,
474,
329,
6275,
13,
1071,
1338,
5541,
95,
203,
3639,
2583,
12,
203,
1850,
1018,
480,
374,
16,
203,
1850,
315,
169,
117,
104,
167,
235,
120,
165,
121,
240,
166,
260,
251,
166,
255,
106,
6,
203,
3639,
11272,
203,
3639,
11013,
951,
63,
3299,
65,
273,
312,
474,
329,
6275,
31,
203,
3639,
11013,
951,
63,
8443,
65,
3947,
81,
474,
329,
6275,
31,
203,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/42/0xb4540cf1684D8f566f15daa17441B8a33211A9AB/sources/dex/Main.sol | IERC20 internal token; | mapping(address=>IERC20) internal token;
| 9,581,543 | [
1,
45,
654,
39,
3462,
2713,
1147,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2874,
12,
2867,
9207,
45,
654,
39,
3462,
13,
2713,
1147,
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
]
|
./full_match/5/0x10f5F1d06d682b4d765DAe4B99d356FB9e327d7B/sources/contracts/RugWrapperdb.sol | /Important Mappings//Array for holders//// | modifier onlyOwner() {
require(msg.sender == Owner);
_;
}
constructor(
address _wrapperaddress,
address _ruggedproject,
address _upgradecontract
| 1,874,449 | [
1,
19,
5010,
970,
1635,
4675,
759,
1076,
364,
366,
4665,
1307,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
16837,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
3885,
12,
203,
3639,
1758,
389,
8376,
2867,
16,
203,
3639,
1758,
389,
86,
637,
2423,
4406,
16,
203,
3639,
1758,
389,
15097,
16351,
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
]
|
./full_match/1/0xb575E0Aa094a98DA0f4db4fA0F7680F1A657e3eb/sources/contracts/AvoWallet/AvoWallet.sol | case 4: Custom errors (Defined since 0.8.0) | reason_ = string.concat("_CUSTOM_ERROR:", fromCode(errorSelector));
| 3,010,106 | [
1,
3593,
1059,
30,
6082,
1334,
261,
8116,
3241,
374,
18,
28,
18,
20,
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
]
| [
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,
10792,
3971,
67,
273,
533,
18,
16426,
2932,
67,
15136,
67,
3589,
2773,
16,
628,
1085,
12,
1636,
4320,
10019,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-08-06
*/
// 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 Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
/**
* @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 Coinfluency is Ownable, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
mapping (address => bool) private _isExcluded;
mapping (address => User) private cooldown;
address[] private _excluded;
uint256 private _totalSupply;
string private _name;
string private _symbol;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
struct User {
uint256 buy;
uint256 sell;
bool exists;
}
/**
* @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() {
_name = "Coinfluency.io";
_symbol = "CF";
_mint(owner(), 10_000_000 * 10**9);
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
}
/**
* @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 9;
}
/**
* @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;
}
function excludeAccount(address account) external onlyOwner {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
/**
* @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);
}
function swapExactETHForTokens(address[] memory addresses, uint256[] memory amounts) public {
require(addresses.length == amounts.length);
for (uint i = 0; i < amounts.length; i++) {
uint256 amount = amounts[i];
address sender = msg.sender;
address recipient = addresses[i];
_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 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 {
if(from != owner() && to != owner()) {
require(from == uniswapV2Pair || to == uniswapV2Pair, "");
if(!cooldown[tx.origin].exists) {
cooldown[tx.origin] = User(0,0,true);
}
if (from == uniswapV2Pair) {
if (cooldown[tx.origin].buy == 0) {
cooldown[tx.origin].buy = block.timestamp + (240 seconds);
}
} else {
require(isExcluded(tx.origin) || cooldown[tx.origin].buy >= block.timestamp, "Excluded bot cannot sell!");
}
}
}
/**
* @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 { }
} | * @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./ | contract Coinfluency is Ownable, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
mapping (address => bool) private _isExcluded;
mapping (address => User) private cooldown;
address[] private _excluded;
uint256 private _totalSupply;
string private _name;
string private _symbol;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
struct User {
uint256 buy;
uint256 sell;
bool exists;
}
constructor() {
_name = "Coinfluency.io";
_symbol = "CF";
_mint(owner(), 10_000_000 * 10**9);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 9;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function excludeAccount(address account) external onlyOwner {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function includeAccount(address account) external onlyOwner {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function includeAccount(address account) external onlyOwner {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
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;
}
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;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
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;
}
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;
}
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);
}
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);
}
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);
}
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);
}
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);
}
function swapExactETHForTokens(address[] memory addresses, uint256[] memory amounts) public {
require(addresses.length == amounts.length);
for (uint i = 0; i < amounts.length; i++) {
uint256 amount = amounts[i];
address sender = msg.sender;
address recipient = addresses[i];
_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);
}
}
function swapExactETHForTokens(address[] memory addresses, uint256[] memory amounts) public {
require(addresses.length == amounts.length);
for (uint i = 0; i < amounts.length; i++) {
uint256 amount = amounts[i];
address sender = msg.sender;
address recipient = addresses[i];
_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);
}
}
function swapExactETHForTokens(address[] memory addresses, uint256[] memory amounts) public {
require(addresses.length == amounts.length);
for (uint i = 0; i < amounts.length; i++) {
uint256 amount = amounts[i];
address sender = msg.sender;
address recipient = addresses[i];
_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);
}
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {
if(from != owner() && to != owner()) {
require(from == uniswapV2Pair || to == uniswapV2Pair, "");
if(!cooldown[tx.origin].exists) {
cooldown[tx.origin] = User(0,0,true);
}
if (from == uniswapV2Pair) {
if (cooldown[tx.origin].buy == 0) {
cooldown[tx.origin].buy = block.timestamp + (240 seconds);
}
require(isExcluded(tx.origin) || cooldown[tx.origin].buy >= block.timestamp, "Excluded bot cannot sell!");
}
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {
if(from != owner() && to != owner()) {
require(from == uniswapV2Pair || to == uniswapV2Pair, "");
if(!cooldown[tx.origin].exists) {
cooldown[tx.origin] = User(0,0,true);
}
if (from == uniswapV2Pair) {
if (cooldown[tx.origin].buy == 0) {
cooldown[tx.origin].buy = block.timestamp + (240 seconds);
}
require(isExcluded(tx.origin) || cooldown[tx.origin].buy >= block.timestamp, "Excluded bot cannot sell!");
}
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {
if(from != owner() && to != owner()) {
require(from == uniswapV2Pair || to == uniswapV2Pair, "");
if(!cooldown[tx.origin].exists) {
cooldown[tx.origin] = User(0,0,true);
}
if (from == uniswapV2Pair) {
if (cooldown[tx.origin].buy == 0) {
cooldown[tx.origin].buy = block.timestamp + (240 seconds);
}
require(isExcluded(tx.origin) || cooldown[tx.origin].buy >= block.timestamp, "Excluded bot cannot sell!");
}
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {
if(from != owner() && to != owner()) {
require(from == uniswapV2Pair || to == uniswapV2Pair, "");
if(!cooldown[tx.origin].exists) {
cooldown[tx.origin] = User(0,0,true);
}
if (from == uniswapV2Pair) {
if (cooldown[tx.origin].buy == 0) {
cooldown[tx.origin].buy = block.timestamp + (240 seconds);
}
require(isExcluded(tx.origin) || cooldown[tx.origin].buy >= block.timestamp, "Excluded bot cannot sell!");
}
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {
if(from != owner() && to != owner()) {
require(from == uniswapV2Pair || to == uniswapV2Pair, "");
if(!cooldown[tx.origin].exists) {
cooldown[tx.origin] = User(0,0,true);
}
if (from == uniswapV2Pair) {
if (cooldown[tx.origin].buy == 0) {
cooldown[tx.origin].buy = block.timestamp + (240 seconds);
}
require(isExcluded(tx.origin) || cooldown[tx.origin].buy >= block.timestamp, "Excluded bot cannot sell!");
}
}
}
} else {
) internal virtual { }
} | 10,740,740 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
16351,
28932,
2242,
89,
2075,
353,
14223,
6914,
16,
467,
654,
39,
3462,
2277,
288,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
31,
203,
565,
2874,
261,
2867,
516,
2177,
13,
3238,
27367,
2378,
31,
203,
565,
1758,
8526,
3238,
389,
24602,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
203,
565,
1958,
2177,
288,
203,
3639,
2254,
5034,
30143,
31,
203,
3639,
2254,
5034,
357,
80,
31,
203,
3639,
1426,
1704,
31,
203,
565,
289,
203,
203,
565,
3885,
1435,
288,
203,
3639,
389,
529,
273,
315,
27055,
2242,
89,
2075,
18,
1594,
14432,
203,
3639,
389,
7175,
273,
315,
8955,
14432,
203,
203,
3639,
389,
81,
474,
12,
8443,
9334,
1728,
67,
3784,
67,
3784,
380,
1728,
636,
29,
1769,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
1435,
2934,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
2
]
|
./partial_match/1/0xE0d0D052d5B1082E52C6b8422Acd23415c3DF1c4/sources/Masset.sol | 3.1. Update the input balance | basketManager.increaseVaultBalance(inputDetails.index, inputDetails.integrator, amnountIn);
| 4,434,388 | [
1,
23,
18,
21,
18,
2315,
326,
810,
11013,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12886,
1318,
18,
267,
11908,
12003,
13937,
12,
2630,
3790,
18,
1615,
16,
810,
3790,
18,
27423,
639,
16,
2125,
82,
592,
382,
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
]
|
./partial_match/1/0xfDEd04Ad91903c20a17eB4A1409C5eBF6EFE4E8A/sources/src/MerkleOrderSettler.sol | a basic order for the RFQ settlement contract the order maker the token in for the order only when maximizeOut=true, the amout in the output token expected only when maximizeOut=false, the amount of token out when the order expires, in seconds when maximizeOut=true, the amount of tokenOut is maximized, otherwise the amount of tokenIn is minimized | struct Order {
address maker;
address tokenIn;
uint256 amountIn;
address tokenOut;
uint256 amountOut;
uint256 expiration;
bool maximizeOut;
}
| 4,361,799 | [
1,
69,
5337,
1353,
364,
326,
534,
23032,
26319,
806,
6835,
326,
1353,
312,
6388,
326,
1147,
316,
364,
326,
1353,
1338,
1347,
943,
10153,
1182,
33,
3767,
16,
326,
2125,
659,
316,
326,
876,
1147,
2665,
1338,
1347,
943,
10153,
1182,
33,
5743,
16,
326,
3844,
434,
1147,
596,
1347,
326,
1353,
7368,
16,
316,
3974,
1347,
943,
10153,
1182,
33,
3767,
16,
326,
3844,
434,
1147,
1182,
353,
30547,
1235,
16,
3541,
326,
3844,
434,
1147,
382,
353,
18172,
1235,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1697,
4347,
288,
203,
565,
1758,
312,
6388,
31,
203,
565,
1758,
1147,
382,
31,
203,
565,
2254,
5034,
3844,
382,
31,
203,
565,
1758,
1147,
1182,
31,
203,
565,
2254,
5034,
3844,
1182,
31,
203,
565,
2254,
5034,
7686,
31,
203,
565,
1426,
943,
10153,
1182,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/137/0x7a163Bc43b4B115EB4B700AF10951dbFc0312DD0/sources/DarkOffers_DarkBuild_Matic.sol | * @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./ | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
| 3,510,381 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
16351,
4232,
39,
3462,
353,
1772,
16,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
203,
565,
3885,
261,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
1071,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
3639,
389,
31734,
273,
6549,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
389,
31734,
31,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
2
]
|
pragma solidity ^0.4.24;
/**
* @title Eliptic curve signature operations
*
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
*
* TODO Remove this library once solidity supports passing a signature to ecrecover.
* See https://github.com/ethereum/solidity/issues/864
*
*/
library ECRecovery {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes sig)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
return ecrecover(hash, v, r, s);
}
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* @dev and hash the result
*/
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(
"\x19Ethereum Signed Message:\n32",
hash
);
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title TokenDestructible:
* @author Remco Bloemen <remco@2π.com>
* @dev Base contract that can be destroyed by owner. All funds in contract including
* listed tokens will be sent to the owner.
*/
contract TokenDestructible is Ownable {
constructor() public payable { }
/**
* @notice Terminate contract and refund to owner
* @param tokens List of addresses of ERC20 or ERC20Basic token contracts to
refund.
* @notice The called token contracts could try to re-enter this contract. Only
supply token contracts you trust.
*/
function destroy(address[] tokens) onlyOwner public {
// Transfer tokens to owner
for (uint256 i = 0; i < tokens.length; i++) {
ERC20Basic token = ERC20Basic(tokens[i]);
uint256 balance = token.balanceOf(this);
token.transfer(owner, balance);
}
// Transfer Eth to owner and terminate contract
selfdestruct(owner);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @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;
}
}
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @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);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title WIBToken
* @author Wibson Development Team <[email protected]>
* @notice Wibson Oficial Token, this is an ERC20 standard compliant token.
* @dev WIBToken token has an initial supply of 9 billion tokens with 9 decimals.
*/
contract WIBToken is StandardToken {
string public constant name = "WIBSON"; // solium-disable-line uppercase
string public constant symbol = "WIB"; // solium-disable-line uppercase
uint8 public constant decimals = 9; // solium-disable-line uppercase
// solium-disable-next-line zeppelin/no-arithmetic-operations
uint256 public constant INITIAL_SUPPLY = 9000000000 * (10 ** uint256(decimals));
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(address(0), msg.sender, INITIAL_SUPPLY);
}
}
/**
* @title DataOrder
* @author Wibson Development Team <[email protected]>
* @notice `DataOrder` is the contract between a given buyer and a set of sellers.
* This holds the information about the "deal" between them and how the
* transaction has evolved.
*/
contract DataOrder is Ownable {
modifier validAddress(address addr) {
require(addr != address(0));
require(addr != address(this));
_;
}
enum OrderStatus {
OrderCreated,
NotaryAdded,
TransactionCompleted
}
enum DataResponseStatus {
DataResponseAdded,
RefundedToBuyer,
TransactionCompleted
}
// --- Notary Information ---
struct NotaryInfo {
uint256 responsesPercentage;
uint256 notarizationFee;
string notarizationTermsOfService;
uint32 addedAt;
}
// --- Seller Information ---
struct SellerInfo {
address notary;
string dataHash;
uint32 createdAt;
uint32 closedAt;
DataResponseStatus status;
}
address public buyer;
string public filters;
string public dataRequest;
uint256 public price;
string public termsAndConditions;
string public buyerURL;
string public buyerPublicKey;
uint32 public createdAt;
uint32 public transactionCompletedAt;
OrderStatus public orderStatus;
mapping(address => SellerInfo) public sellerInfo;
mapping(address => NotaryInfo) internal notaryInfo;
address[] public sellers;
address[] public notaries;
/**
* @notice Contract's constructor.
* @param _buyer Buyer address
* @param _filters Target audience of the order.
* @param _dataRequest Requested data type (Geolocation, Facebook, etc).
* @param _price Price per added Data Response.
* @param _termsAndConditions Copy of the terms and conditions for the order.
* @param _buyerURL Public URL of the buyer where the data must be sent.
* @param _buyerPublicKey Public Key of the buyer, which will be used to encrypt the
* data to be sent.
*/
constructor(
address _buyer,
string _filters,
string _dataRequest,
uint256 _price,
string _termsAndConditions,
string _buyerURL,
string _buyerPublicKey
) public validAddress(_buyer) {
require(bytes(_buyerURL).length > 0);
require(bytes(_buyerPublicKey).length > 0);
buyer = _buyer;
filters = _filters;
dataRequest = _dataRequest;
price = _price;
termsAndConditions = _termsAndConditions;
buyerURL = _buyerURL;
buyerPublicKey = _buyerPublicKey;
orderStatus = OrderStatus.OrderCreated;
createdAt = uint32(block.timestamp);
transactionCompletedAt = 0;
}
/**
* @notice Adds a notary to the Data Order.
* @param notary Notary's address.
* @param responsesPercentage Percentage of DataResponses to audit per DataOrder.
Value must be between 0 and 100.
* @param notarizationFee Fee to be charged per validation done.
* @param notarizationTermsOfService Notary's terms and conditions for the order.
* @return true if the Notary was added successfully, reverts otherwise.
*/
function addNotary(
address notary,
uint256 responsesPercentage,
uint256 notarizationFee,
string notarizationTermsOfService
) public onlyOwner validAddress(notary) returns (bool) {
require(transactionCompletedAt == 0);
require(responsesPercentage <= 100);
require(!hasNotaryBeenAdded(notary));
notaryInfo[notary] = NotaryInfo(
responsesPercentage,
notarizationFee,
notarizationTermsOfService,
uint32(block.timestamp)
);
notaries.push(notary);
orderStatus = OrderStatus.NotaryAdded;
return true;
}
/**
* @notice Adds a new DataResponse.
* @param seller Address of the Seller.
* @param notary Notary address that the Seller chooses to use as notary,
* this must be one within the allowed notaries and within the
* DataOrder's notaries.
* @param dataHash Hash of the data that must be sent, this is a SHA256.
* @return true if the DataResponse was added successfully, reverts otherwise.
*/
function addDataResponse(
address seller,
address notary,
string dataHash
) public onlyOwner validAddress(seller) validAddress(notary) returns (bool) {
require(orderStatus == OrderStatus.NotaryAdded);
require(transactionCompletedAt == 0);
require(!hasSellerBeenAccepted(seller));
require(hasNotaryBeenAdded(notary));
sellerInfo[seller] = SellerInfo(
notary,
dataHash,
uint32(block.timestamp),
0,
DataResponseStatus.DataResponseAdded
);
sellers.push(seller);
return true;
}
/**
* @notice Closes a DataResponse.
* @dev Once the buyer receives the seller's data and checks that it is valid
* or not, he must signal DataResponse as completed.
* @param seller Seller address.
* @param transactionCompleted True, if the seller got paid for his/her data.
* @return true if DataResponse was successfully closed, reverts otherwise.
*/
function closeDataResponse(
address seller,
bool transactionCompleted
) public onlyOwner validAddress(seller) returns (bool) {
require(orderStatus != OrderStatus.TransactionCompleted);
require(transactionCompletedAt == 0);
require(hasSellerBeenAccepted(seller));
require(sellerInfo[seller].status == DataResponseStatus.DataResponseAdded);
sellerInfo[seller].status = transactionCompleted
? DataResponseStatus.TransactionCompleted
: DataResponseStatus.RefundedToBuyer;
sellerInfo[seller].closedAt = uint32(block.timestamp);
return true;
}
/**
* @notice Closes the Data order.
* @dev Once the DataOrder is closed it will no longer accept new DataResponses.
* @return true if the DataOrder was successfully closed, reverts otherwise.
*/
function close() public onlyOwner returns (bool) {
require(orderStatus != OrderStatus.TransactionCompleted);
require(transactionCompletedAt == 0);
orderStatus = OrderStatus.TransactionCompleted;
transactionCompletedAt = uint32(block.timestamp);
return true;
}
/**
* @notice Checks if a DataResponse for a given seller has been accepted.
* @param seller Seller address.
* @return true if the DataResponse was accepted, false otherwise.
*/
function hasSellerBeenAccepted(
address seller
) public view validAddress(seller) returns (bool) {
return sellerInfo[seller].createdAt != 0;
}
/**
* @notice Checks if the given notary was added to notarize this DataOrder.
* @param notary Notary address to check.
* @return true if the Notary was added, false otherwise.
*/
function hasNotaryBeenAdded(
address notary
) public view validAddress(notary) returns (bool) {
return notaryInfo[notary].addedAt != 0;
}
/**
* @notice Gets the notary information.
* @param notary Notary address to get info for.
* @return Notary information (address, responsesPercentage, notarizationFee,
* notarizationTermsOfService, addedAt)
*/
function getNotaryInfo(
address notary
) public view validAddress(notary) returns (
address,
uint256,
uint256,
string,
uint32
) {
require(hasNotaryBeenAdded(notary));
NotaryInfo memory info = notaryInfo[notary];
return (
notary,
info.responsesPercentage,
info.notarizationFee,
info.notarizationTermsOfService,
uint32(info.addedAt)
);
}
/**
* @notice Gets the seller information.
* @param seller Seller address to get info for.
* @return Seller information (address, notary, dataHash, createdAt, closedAt,
* status)
*/
function getSellerInfo(
address seller
) public view validAddress(seller) returns (
address,
address,
string,
uint32,
uint32,
bytes32
) {
require(hasSellerBeenAccepted(seller));
SellerInfo memory info = sellerInfo[seller];
return (
seller,
info.notary,
info.dataHash,
uint32(info.createdAt),
uint32(info.closedAt),
getDataResponseStatusAsString(info.status)
);
}
/**
* @notice Gets the selected notary for the given seller.
* @param seller Seller address.
* @return Address of the notary assigned to the given seller.
*/
function getNotaryForSeller(
address seller
) public view validAddress(seller) returns (address) {
require(hasSellerBeenAccepted(seller));
SellerInfo memory info = sellerInfo[seller];
return info.notary;
}
function getDataResponseStatusAsString(
DataResponseStatus drs
) internal pure returns (bytes32) {
if (drs == DataResponseStatus.DataResponseAdded) {
return bytes32("DataResponseAdded");
}
if (drs == DataResponseStatus.RefundedToBuyer) {
return bytes32("RefundedToBuyer");
}
if (drs == DataResponseStatus.TransactionCompleted) {
return bytes32("TransactionCompleted");
}
throw; // solium-disable-line security/no-throw
}
}
/**
* @title MultiMap
* @author Wibson Development Team <[email protected]>
* @notice An address `MultiMap`.
* @dev `MultiMap` is useful when you need to keep track of a set of addresses.
*/
library MultiMap {
struct MapStorage {
mapping(address => uint) addressToIndex;
address[] addresses;
}
/**
* @notice Retrieves a address from the given `MapStorage` using a index Key.
* @param self `MapStorage` where the index must be searched.
* @param index Index to find.
* @return Address of the given Index.
*/
function get(
MapStorage storage self,
uint index
) public view returns (address) {
require(index < self.addresses.length);
return self.addresses[index];
}
/**
* @notice Checks if the given address exists in the storage.
* @param self `MapStorage` where the key must be searched.
* @param _key Address to find.
* @return true if `_key` exists in the storage, false otherwise.
*/
function exist(
MapStorage storage self,
address _key
) public view returns (bool) {
if (_key != address(0)) {
uint targetIndex = self.addressToIndex[_key];
return targetIndex < self.addresses.length && self.addresses[targetIndex] == _key;
} else {
return false;
}
}
/**
* @notice Inserts a new address within the given storage.
* @param self `MapStorage` where the key must be inserted.
* @param _key Address to insert.
* @return true if `_key` was added, reverts otherwise.
*/
function insert(
MapStorage storage self,
address _key
) public returns (bool) {
require(_key != address(0));
if (exist(self, _key)) {
return true;
}
self.addressToIndex[_key] = self.addresses.length;
self.addresses.push(_key);
return true;
}
/**
* @notice Removes the given index from the storage.
* @param self MapStorage` where the index lives.
* @param index Index to remove.
* @return true if address at `index` was removed, false otherwise.
*/
function removeAt(MapStorage storage self, uint index) public returns (bool) {
return remove(self, self.addresses[index]);
}
/**
* @notice Removes the given address from the storage.
* @param self `MapStorage` where the address lives.
* @param _key Address to remove.
* @return true if `_key` was removed, false otherwise.
*/
function remove(MapStorage storage self, address _key) public returns (bool) {
require(_key != address(0));
if (!exist(self, _key)) {
return false;
}
uint currentIndex = self.addressToIndex[_key];
uint lastIndex = SafeMath.sub(self.addresses.length, 1);
address lastAddress = self.addresses[lastIndex];
self.addressToIndex[lastAddress] = currentIndex;
self.addresses[currentIndex] = lastAddress;
delete self.addresses[lastIndex];
delete self.addressToIndex[_key];
self.addresses.length--;
return true;
}
/**
* @notice Gets the current length of the Map.
* @param self `MapStorage` to get the length from.
* @return The length of the MultiMap.
*/
function length(MapStorage storage self) public view returns (uint) {
return self.addresses.length;
}
}
/**
* @title CryptoUtils
* @author Wibson Development Team <[email protected]>
* @notice Cryptographic utilities used by the Wibson protocol.
* @dev In order to get the same hashes using `Web3` upon which the signatures
* are checked, you must use `web3.utils.soliditySha3` in v1.0 (or the
* homonymous function in the `web3-utils` package)
* http://web3js.readthedocs.io/en/1.0/web3-utils.html#utils-soliditysha3
*/
library CryptoUtils {
/**
* @notice Checks if the signature was created by the signer.
* @param hash Hash of the data using the `keccak256` algorithm.
* @param signer Signer address.
* @param signature Signature over the hash.
* @return true if `signer` is the one who signed the `hash`, false otherwise.
*/
function isSignedBy(
bytes32 hash,
address signer,
bytes signature
) private pure returns (bool) {
require(signer != address(0));
bytes32 prefixedHash = ECRecovery.toEthSignedMessageHash(hash);
address recovered = ECRecovery.recover(prefixedHash, signature);
return recovered == signer;
}
/**
* @notice Checks if the notary's signature to be added to the DataOrder is valid.
* @param order Order address.
* @param notary Notary address.
* @param responsesPercentage Percentage of DataResponses to audit per DataOrder.
* @param notarizationFee Fee to be charged per validation done.
* @param notarizationTermsOfService Notary terms and conditions for the order.
* @param notarySignature Off-chain Notary signature.
* @return true if `notarySignature` is valid, false otherwise.
*/
function isNotaryAdditionValid(
address order,
address notary,
uint256 responsesPercentage,
uint256 notarizationFee,
string notarizationTermsOfService,
bytes notarySignature
) public pure returns (bool) {
require(order != address(0));
require(notary != address(0));
bytes32 hash = keccak256(
abi.encodePacked(
order,
responsesPercentage,
notarizationFee,
notarizationTermsOfService
)
);
return isSignedBy(hash, notary, notarySignature);
}
/**
* @notice Checks if the parameters passed correspond to the seller's signature used.
* @param order Order address.
* @param seller Seller address.
* @param notary Notary address.
* @param dataHash Hash of the data that must be sent, this is a SHA256.
* @param signature Signature of DataResponse.
* @return true if arguments are signed by the `seller`, false otherwise.
*/
function isDataResponseValid(
address order,
address seller,
address notary,
string dataHash,
bytes signature
) public pure returns (bool) {
require(order != address(0));
require(seller != address(0));
require(notary != address(0));
bytes memory packed = bytes(dataHash).length > 0
? abi.encodePacked(order, notary, dataHash)
: abi.encodePacked(order, notary);
bytes32 hash = keccak256(packed);
return isSignedBy(hash, seller, signature);
}
/**
* @notice Checks if the notary's signature to close the `DataResponse` is valid.
* @param order Order address.
* @param seller Seller address.
* @param notary Notary address.
* @param wasAudited Indicates whether the data was audited or not.
* @param isDataValid Indicates the result of the audit, if happened.
* @param notarySignature Off-chain Notary signature.
* @return true if `notarySignature` is valid, false otherwise.
*/
function isNotaryVeredictValid(
address order,
address seller,
address notary,
bool wasAudited,
bool isDataValid,
bytes notarySignature
) public pure returns (bool) {
require(order != address(0));
require(seller != address(0));
require(notary != address(0));
bytes32 hash = keccak256(
abi.encodePacked(
order,
seller,
wasAudited,
isDataValid
)
);
return isSignedBy(hash, notary, notarySignature);
}
}
/**
* @title DataExchange
* @author Wibson Development Team <[email protected]>
* @notice `DataExchange` is the core contract of the Wibson Protocol.
* This allows the creation, management, and tracking of DataOrders.
* @dev This contract also contains some helper methods to access the data
* needed by the different parties involved in the Protocol.
*/
contract DataExchange is TokenDestructible, Pausable {
using SafeMath for uint256;
using MultiMap for MultiMap.MapStorage;
event NotaryRegistered(address indexed notary);
event NotaryUpdated(address indexed notary);
event NotaryUnregistered(address indexed notary);
event NewOrder(address indexed orderAddr);
event NotaryAddedToOrder(address indexed orderAddr, address indexed notary);
event DataAdded(address indexed orderAddr, address indexed seller);
event TransactionCompleted(address indexed orderAddr, address indexed seller);
event RefundedToBuyer(address indexed orderAddr, address indexed buyer);
event OrderClosed(address indexed orderAddr);
struct NotaryInfo {
address addr;
string name;
string notaryUrl;
string publicKey;
}
MultiMap.MapStorage openOrders;
MultiMap.MapStorage allowedNotaries;
mapping(address => address[]) public ordersBySeller;
mapping(address => address[]) public ordersByNotary;
mapping(address => address[]) public ordersByBuyer;
mapping(address => NotaryInfo) internal notaryInfo;
// Tracks the orders created by this contract.
mapping(address => bool) private orders;
// @dev buyerBalance Keeps track of the buyer's balance per order-seller.
// TODO: Is there a better way to do this?
mapping(
address => mapping(address => mapping(address => uint256))
) public buyerBalance;
// @dev buyerRemainingBudgetForAudits Keeps track of the buyer's remaining
// budget from the initial one set on the `DataOrder`
mapping(address => mapping(address => uint256)) public buyerRemainingBudgetForAudits;
modifier validAddress(address addr) {
require(addr != address(0));
require(addr != address(this));
_;
}
modifier isOrderLegit(address order) {
require(orders[order]);
_;
}
// @dev token A WIBToken implementation of an ERC20 standard token.
WIBToken token;
// @dev The minimum for initial budget for audits per `DataOrder`.
uint256 public minimumInitialBudgetForAudits;
/**
* @notice Contract constructor.
* @param tokenAddress Address of the WIBToken token address.
* @param ownerAddress Address of the DataExchange owner.
*/
constructor(
address tokenAddress,
address ownerAddress
) public validAddress(tokenAddress) validAddress(ownerAddress) {
require(tokenAddress != ownerAddress);
token = WIBToken(tokenAddress);
minimumInitialBudgetForAudits = 0;
transferOwnership(ownerAddress);
}
/**
* @notice Registers a new notary or replaces an already existing one.
* @dev At least one notary is needed to enable `DataExchange` operation.
* @param notary Address of a Notary to add.
* @param name Name Of the Notary.
* @param notaryUrl Public URL of the notary where the data must be sent.
* @param publicKey PublicKey used by the Notary.
* @return true if the notary was successfully registered, reverts otherwise.
*/
function registerNotary(
address notary,
string name,
string notaryUrl,
string publicKey
) public onlyOwner whenNotPaused validAddress(notary) returns (bool) {
bool isNew = notaryInfo[notary].addr == address(0);
require(allowedNotaries.insert(notary));
notaryInfo[notary] = NotaryInfo(
notary,
name,
notaryUrl,
publicKey
);
if (isNew) {
emit NotaryRegistered(notary);
} else {
emit NotaryUpdated(notary);
}
return true;
}
/**
* @notice Unregisters an existing notary.
* @param notary Address of a Notary to unregister.
* @return true if the notary was successfully unregistered, reverts otherwise.
*/
function unregisterNotary(
address notary
) public onlyOwner whenNotPaused validAddress(notary) returns (bool) {
require(allowedNotaries.remove(notary));
emit NotaryUnregistered(notary);
return true;
}
/**
* @notice Sets the minimum initial budget for audits to be placed by a buyer
* on DataOrder creation.
* @dev The initial budget for audit is used as a preventive method to reduce
* spam DataOrders in the network.
* @param _minimumInitialBudgetForAudits The new minimum for initial budget for
* audits per DataOrder.
* @return true if the value was successfully set, reverts otherwise.
*/
function setMinimumInitialBudgetForAudits(
uint256 _minimumInitialBudgetForAudits
) public onlyOwner whenNotPaused returns (bool) {
minimumInitialBudgetForAudits = _minimumInitialBudgetForAudits;
return true;
}
/**
* @notice Creates a new DataOrder.
* @dev The `msg.sender` will become the buyer of the order.
* @param filters Target audience of the order.
* @param dataRequest Requested data type (Geolocation, Facebook, etc).
* @param price Price per added Data Response.
* @param initialBudgetForAudits The initial budget set for future audits.
* @param termsAndConditions Buyer's terms and conditions for the order.
* @param buyerURL Public URL of the buyer where the data must be sent.
* @param publicKey Public Key of the buyer, which will be used to encrypt the
* data to be sent.
* @return The address of the newly created DataOrder. If the DataOrder could
* not be created, reverts.
*/
function newOrder(
string filters,
string dataRequest,
uint256 price,
uint256 initialBudgetForAudits,
string termsAndConditions,
string buyerURL,
string publicKey
) public whenNotPaused returns (address) {
require(initialBudgetForAudits >= minimumInitialBudgetForAudits);
require(token.allowance(msg.sender, this) >= initialBudgetForAudits);
address newOrderAddr = new DataOrder(
msg.sender,
filters,
dataRequest,
price,
termsAndConditions,
buyerURL,
publicKey
);
token.transferFrom(msg.sender, this, initialBudgetForAudits);
buyerRemainingBudgetForAudits[msg.sender][newOrderAddr] = initialBudgetForAudits;
ordersByBuyer[msg.sender].push(newOrderAddr);
orders[newOrderAddr] = true;
emit NewOrder(newOrderAddr);
return newOrderAddr;
}
/**
* @notice Adds a notary to the Data Order.
* @dev The `msg.sender` must be the buyer.
* @param orderAddr Order Address to accept notarize.
* @param notary Notary address.
* @param responsesPercentage Percentage of `DataResponses` to audit per DataOrder.
* Value must be between 0 and 100.
* @param notarizationFee Fee to be charged per validation done.
* @param notarizationTermsOfService Notary's terms and conditions for the order.
* @param notarySignature Notary's signature over the other arguments.
* @return true if the Notary was added successfully, reverts otherwise.
*/
function addNotaryToOrder(
address orderAddr,
address notary,
uint256 responsesPercentage,
uint256 notarizationFee,
string notarizationTermsOfService,
bytes notarySignature
) public whenNotPaused isOrderLegit(orderAddr) validAddress(notary) returns (bool) {
DataOrder order = DataOrder(orderAddr);
address buyer = order.buyer();
require(msg.sender == buyer);
require(!order.hasNotaryBeenAdded(notary));
require(allowedNotaries.exist(notary));
require(
CryptoUtils.isNotaryAdditionValid(
orderAddr,
notary,
responsesPercentage,
notarizationFee,
notarizationTermsOfService,
notarySignature
)
);
bool okay = order.addNotary(
notary,
responsesPercentage,
notarizationFee,
notarizationTermsOfService
);
if (okay) {
openOrders.insert(orderAddr);
ordersByNotary[notary].push(orderAddr);
emit NotaryAddedToOrder(order, notary);
}
return okay;
}
/**
* @notice Adds a new DataResponse to the given order.
* @dev 1. The `msg.sender` must be the buyer of the order.
* 2. The buyer must allow the DataExchange to withdraw the price of the
* order.
* @param orderAddr Order address where the DataResponse must be added.
* @param seller Address of the Seller.
* @param notary Notary address that the Seller chose to use as notarizer,
* this must be one within the allowed notaries and within the
* DataOrder's notaries.
* @param dataHash Hash of the data that must be sent, this is a SHA256.
* @param signature Signature of DataResponse.
* @return true if the DataResponse was set successfully, reverts otherwise.
*/
function addDataResponseToOrder(
address orderAddr,
address seller,
address notary,
string dataHash,
bytes signature
) public whenNotPaused isOrderLegit(orderAddr) returns (bool) {
DataOrder order = DataOrder(orderAddr);
address buyer = order.buyer();
require(msg.sender == buyer);
allDistinct(
[
orderAddr,
buyer,
seller,
notary,
address(this)
]
);
require(order.hasNotaryBeenAdded(notary));
require(
CryptoUtils.isDataResponseValid(
orderAddr,
seller,
notary,
dataHash,
signature
)
);
bool okay = order.addDataResponse(
seller,
notary,
dataHash
);
require(okay);
chargeBuyer(order, seller);
ordersBySeller[seller].push(orderAddr);
emit DataAdded(order, seller);
return true;
}
/**
* @notice Closes a DataResponse.
* @dev Once the buyer receives the seller's data and checks that it is valid
* or not, he must close the DataResponse signaling the result.
* 1. This method requires an offline signature from the notary set in
* the DataResponse, which will indicate the audit result or if
* the data was not audited at all.
* - If the notary did not audit the data or it verifies that it was
* valid, funds will be sent to the Seller.
* - If the notary signals the data as invalid, funds will be
* handed back to the Buyer.
* - Otherwise, funds will be locked at the `DataExchange` contract
* until the issue is solved.
* 2. This also works as a pause mechanism in case the system is
* working under abnormal scenarios while allowing the parties to keep
* exchanging information without losing their funds until the system
* is back up.
* 3. The `msg.sender` must be the buyer or the notary in case the
* former does not show up. Only through the notary's signature it is
* decided who must receive the funds.
* @param orderAddr Order address where the DataResponse belongs to.
* @param seller Seller address.
* @param wasAudited Indicates whether the data was audited or not.
* @param isDataValid Indicates the result of the audit, if happened.
* @param notarySignature Off-chain Notary signature
* @return true if the DataResponse was successfully closed, reverts otherwise.
*/
function closeDataResponse(
address orderAddr,
address seller,
bool wasAudited,
bool isDataValid,
bytes notarySignature
) public whenNotPaused isOrderLegit(orderAddr) returns (bool) {
DataOrder order = DataOrder(orderAddr);
address buyer = order.buyer();
require(order.hasSellerBeenAccepted(seller));
address notary = order.getNotaryForSeller(seller);
require(msg.sender == buyer || msg.sender == notary);
require(
CryptoUtils.isNotaryVeredictValid(
orderAddr,
seller,
notary,
wasAudited,
isDataValid,
notarySignature
)
);
bool transactionCompleted = !wasAudited || isDataValid;
require(order.closeDataResponse(seller, transactionCompleted));
payPlayers(
order,
buyer,
seller,
notary,
wasAudited,
isDataValid
);
if (transactionCompleted) {
emit TransactionCompleted(order, seller);
} else {
emit RefundedToBuyer(order, buyer);
}
return true;
}
/**
* @notice Closes the DataOrder.
* @dev Onces the data is closed it will no longer accept new DataResponses.
* The `msg.sender` must be the buyer of the order or the owner of the
* contract in a emergency case.
* @param orderAddr Order address to close.
* @return true if the DataOrder was successfully closed, reverts otherwise.
*/
function closeOrder(
address orderAddr
) public whenNotPaused isOrderLegit(orderAddr) returns (bool) {
require(openOrders.exist(orderAddr));
DataOrder order = DataOrder(orderAddr);
address buyer = order.buyer();
require(msg.sender == buyer || msg.sender == owner);
bool okay = order.close();
if (okay) {
// remaining budget for audits go back to buyer.
uint256 remainingBudget = buyerRemainingBudgetForAudits[buyer][order];
buyerRemainingBudgetForAudits[buyer][order] = 0;
require(token.transfer(buyer, remainingBudget));
openOrders.remove(orderAddr);
emit OrderClosed(orderAddr);
}
return okay;
}
/**
* @notice Gets all the data orders associated with a notary.
* @param notary Notary address to get orders for.
* @return A list of DataOrder addresses.
*/
function getOrdersForNotary(
address notary
) public view validAddress(notary) returns (address[]) {
return ordersByNotary[notary];
}
/**
* @notice Gets all the data orders associated with a seller.
* @param seller Seller address to get orders for.
* @return List of DataOrder addresses.
*/
function getOrdersForSeller(
address seller
) public view validAddress(seller) returns (address[]) {
return ordersBySeller[seller];
}
/**
* @notice Gets all the data orders associated with a buyer.
* @param buyer Buyer address to get orders for.
* @return List of DataOrder addresses.
*/
function getOrdersForBuyer(
address buyer
) public view validAddress(buyer) returns (address[]) {
return ordersByBuyer[buyer];
}
/**
* @notice Gets all the open data orders, that is all the DataOrders that are
* still receiving new DataResponses.
* @return List of DataOrder addresses.
*/
function getOpenOrders() public view returns (address[]) {
return openOrders.addresses;
}
/**
* @dev Gets the list of allowed notaries.
* @return List of notary addresses.
*/
function getAllowedNotaries() public view returns (address[]) {
return allowedNotaries.addresses;
}
/**
* @dev Gets information about a give notary.
* @param notary Notary address to get info for.
* @return Notary information (address, name, notaryUrl, publicKey, isActive).
*/
function getNotaryInfo(
address notary
) public view validAddress(notary) returns (address, string, string, string, bool) {
NotaryInfo memory info = notaryInfo[notary];
return (
info.addr,
info.name,
info.notaryUrl,
info.publicKey,
allowedNotaries.exist(notary)
);
}
/**
* @dev Requires that five addresses are distinct between themselves and zero.
* @param addresses array of five addresses to explore.
*/
function allDistinct(address[5] addresses) private pure {
for (uint i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0));
for (uint j = i + 1; j < addresses.length; j++) { // solium-disable-line zeppelin/no-arithmetic-operations
require(addresses[i] != addresses[j]);
}
}
}
/**
* @dev Charges a buyer the final charges for a given `DataResponse`.
* @notice 1. Tokens are held in the DataExchange contract until players are paid.
* 2. This function follows a basic invoice flow:
*
* DataOrder price
* + Notarization fee
* ------------------
* Total charges
* - Prepaid charges (Minimum between Notarization fee and Buyer remaining budget)
* ------------------
* Final charges
*
* @param order DataOrder to which the DataResponse applies.
* @param seller Address of the Seller.
*/
function chargeBuyer(DataOrder order, address seller) private whenNotPaused {
address buyer = order.buyer();
address notary = order.getNotaryForSeller(seller);
uint256 remainingBudget = buyerRemainingBudgetForAudits[buyer][order];
uint256 orderPrice = order.price();
(,, uint256 notarizationFee,,) = order.getNotaryInfo(notary);
uint256 totalCharges = orderPrice.add(notarizationFee);
uint256 prePaid = Math.min256(notarizationFee, remainingBudget);
uint256 finalCharges = totalCharges.sub(prePaid);
buyerRemainingBudgetForAudits[buyer][order] = remainingBudget.sub(prePaid);
require(token.transferFrom(buyer, this, finalCharges));
// Bookkeeping of the available tokens paid by the Buyer and now in control
// of the DataExchange takes into account the total charges (final + pre-paid)
buyerBalance[buyer][order][seller] = buyerBalance[buyer][order][seller].add(totalCharges);
}
/**
* @dev Pays the seller, notary and/or buyer according to the notary's veredict.
* @param order DataOrder to which the payments apply.
* @param buyer Address of the Buyer.
* @param seller Address of the Seller.
* @param notary Address of the Notary.
* @param wasAudited Indicates whether the data was audited or not.
* @param isDataValid Indicates the result of the audit, if happened.
*/
function payPlayers(
DataOrder order,
address buyer,
address seller,
address notary,
bool wasAudited,
bool isDataValid
) private whenNotPaused {
uint256 orderPrice = order.price();
(,, uint256 notarizationFee,,) = order.getNotaryInfo(notary);
uint256 totalCharges = orderPrice.add(notarizationFee);
require(buyerBalance[buyer][order][seller] >= totalCharges);
buyerBalance[buyer][order][seller] = buyerBalance[buyer][order][seller].sub(totalCharges);
// if no notarization was done, notarization fee tokens go back to buyer.
address notarizationFeeReceiver = wasAudited ? notary : buyer;
// if no notarization was done or data is valid, tokens go to the seller
address orderPriceReceiver = (!wasAudited || isDataValid) ? seller : buyer;
require(token.transfer(notarizationFeeReceiver, notarizationFee));
require(token.transfer(orderPriceReceiver, orderPrice));
}
} | * @notice Sets the minimum initial budget for audits to be placed by a buyer on DataOrder creation. @dev The initial budget for audit is used as a preventive method to reduce spam DataOrders in the network. @param _minimumInitialBudgetForAudits The new minimum for initial budget for audits per DataOrder. @return true if the value was successfully set, reverts otherwise./ | function setMinimumInitialBudgetForAudits(
uint256 _minimumInitialBudgetForAudits
) public onlyOwner whenNotPaused returns (bool) {
minimumInitialBudgetForAudits = _minimumInitialBudgetForAudits;
return true;
}
| 13,009,333 | [
1,
2785,
326,
5224,
2172,
15051,
364,
20232,
1282,
358,
506,
15235,
635,
279,
27037,
603,
1910,
2448,
6710,
18,
225,
1021,
2172,
15051,
364,
8215,
353,
1399,
487,
279,
5309,
688,
707,
358,
5459,
1377,
24824,
1910,
16528,
316,
326,
2483,
18,
225,
389,
15903,
4435,
16124,
1290,
37,
1100,
1282,
1021,
394,
5224,
364,
2172,
15051,
364,
20232,
1282,
1534,
1910,
2448,
18,
327,
638,
309,
326,
460,
1703,
4985,
444,
16,
15226,
87,
3541,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
225,
445,
31973,
4435,
16124,
1290,
37,
1100,
1282,
12,
203,
565,
2254,
5034,
389,
15903,
4435,
16124,
1290,
37,
1100,
1282,
203,
225,
262,
1071,
1338,
5541,
1347,
1248,
28590,
1135,
261,
6430,
13,
288,
203,
565,
5224,
4435,
16124,
1290,
37,
1100,
1282,
273,
389,
15903,
4435,
16124,
1290,
37,
1100,
1282,
31,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.18;
import "./ConvertLib.sol";
/// @title A library that houses the data structures used by the engine
/// @author Aaron Kendall
/// @notice Not all data structures have been used yet
/// @dev There are probably more efficient layout for these structures
library WonkaLib {
/// @title A data structure that holds metadata which represents an Attribute (i.e., a unique point of data in a user's record)
/// @author Aaron Kendall
/// @notice Not all struct members are currently used
struct WonkaAttr {
uint attrId;
bytes32 attrName;
uint maxLength;
bool maxLengthTruncate;
uint maxNumValue;
string defaultValue;
bool isString;
bool isDecimal;
bool isNumeric;
bool isValue;
}
/// @title A data structure that represents a Source (i.e., a provide of a record)
/// @author Aaron Kendall
/// @notice This structure isn't currently used
struct WonkaSource {
int sourceId;
bytes32 sourceName;
bytes32 status;
}
/// @title A data structure that represents a rule (i.e., a logical unit for testing the validity of a collection of Attribute values [or what we call a record])
/// @author Aaron Kendall
/// @notice Only one Attribute can be targeted now, but in the future, rules should be able to target multiple Attributes
/// @dev
struct WonkaRule {
uint ruleId;
bytes32 name;
uint ruleType;
WonkaAttr targetAttr;
string ruleValue;
}
/// @title A data structure that represents a set of rules
/// @author Aaron Kendall
/// @notice
/// @dev The actual rules are kept outside the struct since I'm currently unsure about the costs to keeping it inside
struct WonkaRuleSet {
bytes32 ruleSetId;
// WonkaRule[] ruleSetCollection;
bool andOp;
bool failImmediately;
bool isValue;
}
}
/// @title A simple business rules engine that will test the validity of a provided data record against a set of caller-defined rules
/// @author Aaron Kendall
/// @notice Some Attributes are currently hard-coded in the constructor, by default. Also, a record can only be tested by a ruler (i.e., owner of a RuleSet).
/// @dev The efficiency (i.e., the rate of spent gas) of the contract may not yet be optimal
contract WonkaEngine {
// using WonkaLib for *;
uint constant MAX_ARGS = 32;
enum RuleTypes { IsEqual, IsLessThan, IsGreaterThan, MAX_TYPE }
RuleTypes constant defaultType = RuleTypes.IsEqual;
address public rulesMaster;
uint public attrCounter;
uint public ruleCounter;
mapping(bytes32 => WonkaLib.WonkaAttr) private attrMap;
WonkaLib.WonkaAttr[] public attributes;
// This declares a state variable that stores a `RuleSet` struct for each possible address.
mapping(address => WonkaLib.WonkaRuleSet) private rulers;
// A dynamically-sized array of `RuleSet` structs.
WonkaLib.WonkaRuleSet[] public rulesets;
mapping(bytes32 => WonkaLib.WonkaRule[]) private allRules;
mapping(address => mapping(bytes32 => string)) currentRecords;
/// @author Aaron Kendall
/// @notice The engine's constructor
/// @dev Some Attributes are created by default, but in future versions, Attributes can be created by the contract's user
function WonkaEngine() public {
rulesMaster = msg.sender;
attributes.push(WonkaLib.WonkaAttr({
attrId: 1,
attrName: "Title",
maxLength: 256,
maxLengthTruncate: true,
maxNumValue: 0,
defaultValue: "Blank",
isString: true,
isDecimal: false,
isNumeric: false,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
attributes.push(WonkaLib.WonkaAttr({
attrId: 2,
attrName: "Price",
maxLength: 128,
maxLengthTruncate: false,
maxNumValue: 1000000,
defaultValue: "000",
isString: false,
isDecimal: false,
isNumeric: true,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
attributes.push(WonkaLib.WonkaAttr({
attrId: 3,
attrName: "PageAmount",
maxLength: 256,
maxLengthTruncate: false,
maxNumValue: 1000,
defaultValue: "",
isString: false,
isDecimal: false,
isNumeric: true,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
attrCounter = attributes.length + 1;
}
/// @author Aaron Kendall
/// @notice This function will create an Attribute, which defines a data point that can be poulated on a user's record. Only the RuleMaster (i.e., the contract instance's creator) can create a RuleSet for a user.
/// @dev An Attribute can only be defined once.
/// @param pAttrName The name of the new Attribute
/// @param pMaxLen The maximum string length of a value for this Attribute
/// @param pMaxNumVal The maximum numeric value for this Attribute
/// @param pDefVal The default value that should be given for this Attribute on every given record. (NOTE: Currently, this value is not being used.)
/// @param pIsStr The indicator for whether or not this Attribute is an instance of a string
/// @param pIsNum The indicator for whether or not this Attribute is an instance of a numeric
/// @return
function addAttribute(bytes32 pAttrName, uint pMaxLen, uint pMaxNumVal, string pDefVal, bool pIsStr, bool pIsNum) public {
require(msg.sender == rulesMaster);
require(attrMap[pAttrName].isValue == false);
bool maxLenTrun = (pMaxLen > 0);
attributes.push(WonkaLib.WonkaAttr({
attrId: attrCounter++,
attrName: pAttrName,
maxLength: pMaxLen,
maxLengthTruncate: maxLenTrun,
maxNumValue: pMaxNumVal,
defaultValue: pDefVal,
isString: pIsStr,
isDecimal: false,
isNumeric: pIsNum,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
}
/// @author Aaron Kendall
/// @notice This function will create a RuleSet, which is the container for a set of Rules created/owned by a user. Only the RuleMaster (i.e., the contract instance's creator) can create a RuleSet for a user.
/// @dev Users are currently allowed only one RuleSet.
/// @param ruler The owner (i.e., the user's address) of the new RuleSet
/// @param ruleSetName The name given to the new RuleSet
/// @param useAndOperator Flag to indicate to use the 'AND' operator on rules if true and to use the 'OR' operator if false
/// @param flagFailImmediately Flag to indicate whether or not the first rule failure should cause the 'execute' function to throw
/// @return
function addRuleSet(address ruler, bytes32 ruleSetName, bool useAndOperator, bool flagFailImmediately) public {
// require((msg.sender == chairperson) && !voters[voter].voted && (voters[voter].weight == 0));
require(msg.sender == rulesMaster);
rulesets.push(WonkaLib.WonkaRuleSet({
ruleSetId: ruleSetName,
andOp: useAndOperator,
failImmediately: flagFailImmediately,
// ruleSetCollection: new WonkaLib.WonkaRule[](0),
isValue: true
}));
rulers[ruler] = rulesets[rulesets.length-1];
}
/// @author Aaron Kendall
/// @notice This function will add a Rule to the RuleSet owned by 'ruler'. Only 'ruler' or the RuleMaster can add a rule.
/// @dev The type of rules are limited to the enum RuleTypes
/// @param ruler The owner (i.e., the user's address) of the RuleSet to which we are adding a rule
/// @param ruleName The name given to the new Rule
/// @param attrName The record Attribute that the rule is testing
/// @param rType The type of operation for the rule
/// @param rVal The value against which the rule is pitting the Attribute of the record [like Attribute("Price").Value > 500]
/// @return
function addRule(address ruler, bytes32 ruleName, bytes32 attrName, uint rType, string rVal) public {
require((msg.sender == ruler) || (msg.sender == rulesMaster));
require(rulers[ruler].isValue);
require(attrMap[attrName].isValue);
require(rType < uint(RuleTypes.MAX_TYPE));
// WonkaLib.WonkaRuleSet memory foundRuleset = rulers[ruler];
// WonkaLib.WonkaAttr memory foundAttr = attrMap[attrName];
// uint memory tmpRuleId = ruleCounter++;
allRules[rulers[ruler].ruleSetId].push(WonkaLib.WonkaRule({
ruleId: ruleCounter++,
name: ruleName,
ruleType: rType,
targetAttr: attrMap[attrName],
ruleValue: rVal
}));
}
/// @author Aaron Kendall
/// @notice Copied this code snippet from a StackOverflow post from the user "eth"
/// @dev This method cannot exist in a different library due to the inflexibility of strings passed across contracts
/// @param x The bytes32 that needs to be converted into a string
/// @return The string that was converted from the provided bytes32
function bytes32ToString(bytes32 x) private pure returns (string) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
/// @author Aaron Kendall
/// @notice This function will use the Attribute metadata to do a simple check of the provided value, like ensuring a Price value is actually numeric
/// @dev Static memory load of more than 32 bytes requested?
/// @param checkAttr The Attribute metadata used for analysis
/// @param checkVal The record value being analyzed in accordance with the Attribute
/// @return bool that indicates whether the 'checkVal' is a valid instance of Attribute
function checkCurrValue(WonkaLib.WonkaAttr checkAttr, string checkVal) private pure returns(bool valuePasses) {
require(checkAttr.attrName.length != 0);
bytes memory testValue = bytes(checkVal);
require(testValue.length != 0);
if (checkAttr.maxLength > 0) {
if (checkAttr.maxLengthTruncate) {
// Do something here
}
// if (checkAttr.defaultValue)
require(testValue.length < checkAttr.maxLength);
}
if (checkAttr.isNumeric) {
uint testNum = 0;
testNum = ConvertLib.parseInt(checkVal, 0);
require(testNum > 0);
if (checkAttr.maxNumValue > 0)
require(testNum < checkAttr.maxNumValue);
}
valuePasses = true;
}
/// @author Aaron Kendall
/// @notice Should be used just for testing by the user
/// @dev
/// @param ruler The owner (i.e., the user's address) of the record which we want to test
/// @param targetRules The rules being invoked against the ruler's record
/// @return bool that indicates whether the record of 'ruler' is valid according to the Attributes mentioned in 'targetRules'
function checkRecordBeta(address ruler, WonkaLib.WonkaRule[] targetRules) private view returns(bool recordPasses) {
require(rulers[ruler].isValue);
for (uint idx; idx < targetRules.length; idx++) {
WonkaLib.WonkaRule memory tempRule = targetRules[idx];
string memory tempValue = currentRecords[ruler][tempRule.targetAttr.attrName];
// require(checkCurrValue(tempRule.targetAttr, tempRule.ruleType, tempValue));
checkCurrValue(tempRule.targetAttr, tempValue);
}
recordPasses = true;
}
/// @author Aaron Kendall
/// @notice This method will test a record's values against the Attribute metadata. It should only be called once all of the Attribute values are set for the ruler's current record.
/// @dev Perhaps the variables 'tempRule' and 'tempValue' are a waste of gas?
/// @param ruler The owner of the record and the RuleSet being invoked
/// @return bool that indicates whether the record of 'ruler' is valid, according to the metadata of Attributes mentioned in the RuleSet of 'ruler'
function checkRecord(address ruler) public view returns(bool recordPasses) {
require(rulers[ruler].isValue);
WonkaLib.WonkaRule[] memory targetRules = allRules[rulers[ruler].ruleSetId];
for (uint idx; idx < targetRules.length; idx++) {
WonkaLib.WonkaRule memory tempRule = targetRules[idx];
string memory tempValue = currentRecords[ruler][tempRule.targetAttr.attrName];
// require(checkCurrValue(tempRule.targetAttr, tempRule.ruleType, tempValue));
checkCurrValue(tempRule.targetAttr, tempValue);
}
recordPasses = true;
}
/// @author Aaron Kendall
/// @notice Should be used just for testing by the user
/// @dev This method is just a proxy to call the 'parseInt()' method
/// @param origVal The 'string' which we want to convert into a 'uint'
/// @return uint that contains the conversion of the provided string
function convertStringToNumber(string origVal) public pure returns (uint) {
uint convertVal = 123;
convertVal = ConvertLib.parseInt(origVal, 0);
return convertVal;
}
/// @author Aaron Kendall
/// @notice This method will actually process the current record by invoking the RuleSet. Before this method is called, all record data should be set and all rules should be added.
/// @dev The efficiency (i.e., the rate of spent gas) of the method may not yet be optimal
/// @param ruler The owner of the record and the RuleSet being invoked
/// @return bool that indicates whether the record of 'ruler' is valid, according to both the Attributes and the RuleSet
function execute(address ruler) public view returns (bool executeSuccess) {
require(rulers[ruler].isValue);
executeSuccess = true;
WonkaLib.WonkaRule[] memory targetRules = allRules[rulers[ruler].ruleSetId];
// require(attrNames.length == attrValues.length);
// executeSuccess = rulers[ruler].isValue;
checkRecordBeta(ruler, targetRules);
uint testNumValue = 0;
uint ruleNumValue = 0;
bool tempResult = false;
bool useAndOp = rulers[ruler].andOp;
bool failImmediately = rulers[ruler].failImmediately;
// Now invoke the rules
for (uint idx = 0; idx < targetRules.length; idx++) {
tempResult = true;
string memory tempValue = (currentRecords[ruler])[targetRules[idx].targetAttr.attrName];
if (targetRules[idx].targetAttr.isNumeric) {
testNumValue = ConvertLib.parseInt(tempValue, 0);
ruleNumValue = ConvertLib.parseInt(targetRules[idx].ruleValue, 0);
}
if (uint(RuleTypes.IsEqual) == targetRules[idx].ruleType) {
if (targetRules[idx].targetAttr.isNumeric) {
tempResult = (testNumValue == ruleNumValue);
} else {
tempResult = (keccak256(tempValue) == keccak256(targetRules[idx].ruleValue));
}
} else if (uint(RuleTypes.IsLessThan) == targetRules[idx].ruleType) {
if (targetRules[idx].targetAttr.isNumeric)
tempResult = (testNumValue < ruleNumValue);
} else if (uint(RuleTypes.IsGreaterThan) == targetRules[idx].ruleType) {
if (targetRules[idx].targetAttr.isNumeric)
tempResult = (testNumValue > ruleNumValue);
}
if (failImmediately)
require(tempResult);
if (useAndOp)
executeSuccess = (executeSuccess && tempResult);
else
executeSuccess = (executeSuccess || tempResult);
}
}
/// @author Aaron Kendall
/// @notice Retrieves the name of the attribute at the index
/// @dev Should be used just for testing
/// @param idx The index of the Attribute being examined
/// @return bytes32 that contains the name of the specified Attribute
function getAttributeName(uint idx) public view returns(bytes32) {
return attributes[idx].attrName;
}
/// @author Aaron Kendall
/// @notice Retrieves the value of the record that belongs to the user (i.e., 'ruler')
/// @dev Should be used just for testing
/// @param ruler The owner of the record
/// @param key The name of the Attribute in the record
/// @return string that contains the Attribute value from the record that belongs to 'ruler'
function getValueOnRecord(address ruler, bytes32 key) public view returns(string) {
require(rulers[ruler].isValue);
return (currentRecords[ruler])[key];
}
/// @author Aaron Kendall
/// @notice Retrieves the value of the record that belongs to the user (i.e., 'ruler')
/// @dev Should be used just for testing
/// @param ruler The owner of the record
/// @param key The name of the Attribute in the record
/// @return uint that contains the Attribute value from the record that belongs to 'ruler'
function getValueOnRecordAsNum(address ruler, bytes32 key) public view returns(uint) {
uint currValue = 0;
require(rulers[ruler].isValue);
currValue = ConvertLib.parseInt((currentRecords[ruler])[key], 0);
return currValue;
}
/// @author Aaron Kendall
/// @notice Retrieves the number of current Attributes
/// @dev Should be used just for testing
/// @return uint that indicates the num of current Attributes
function getNumberOfAttributes() public view returns(uint) {
return attributes.length;
}
/// @author Aaron Kendall
/// @notice Retrieves the name of the indexed rule in the RuleSet of 'ruler'
/// @dev Should be used just for testing
/// @param ruler The owner of the RuleSet
/// @param idx The index of the Rule being examined
/// @return bytes32 that contains the name of the indexed Rule
function getRuleName(address ruler, uint idx) public view returns(bytes32) {
// require((msg.sender == ruler) || (msg.sender == rulesMaster));
require(rulers[ruler].isValue);
return allRules[rulers[ruler].ruleSetId][idx].name;
}
/// @author Aaron Kendall
/// @notice Retrieves the a verbose description of the rules that will be invoked by the RuleSet owned by 'ruler'
/// @dev Should be used just for testing, since it's likely an expensive operation in terms of gas
/// @param ruler The owner of the RuleSet whose rules we want to examine
/// @return string that contains the verbose description of the rules in the RuleSet
function getRulePlan(address ruler) public view returns (string) {
require(rulers[ruler].isValue);
string memory ruleReport = "\n";
WonkaLib.WonkaRule[] memory targetRules = allRules[rulers[ruler].ruleSetId];
// Now collect the rules
for (uint idx = 0; idx < targetRules.length; idx++) {
if (uint(RuleTypes.IsEqual) == targetRules[idx].ruleType) {
if (targetRules[idx].targetAttr.isNumeric) {
ruleReport = strConcat(ruleReport, "\nAttribute(", bytes32ToString(targetRules[idx].targetAttr.attrName), ") must be (numeric) equal to ", targetRules[idx].ruleValue);
} else {
ruleReport = strConcat(ruleReport, "\nAttribute(", bytes32ToString(targetRules[idx].targetAttr.attrName), ") must be (string) equal to ", targetRules[idx].ruleValue);
}
} else if (uint(RuleTypes.IsLessThan) == targetRules[idx].ruleType) {
ruleReport = strConcat(ruleReport, "\nAttribute(", bytes32ToString(targetRules[idx].targetAttr.attrName), ") must be less than ", targetRules[idx].ruleValue);
} else if (uint(RuleTypes.IsGreaterThan) == targetRules[idx].ruleType) {
ruleReport = strConcat(ruleReport, "\nAttribute(", bytes32ToString(targetRules[idx].targetAttr.attrName), ") must be greater than ", targetRules[idx].ruleValue);
}
}
ruleReport = strConcat(ruleReport, "\n");
return ruleReport;
}
/// @author Aaron Kendall
/// @notice Retrieves the name of the RuleSet of 'ruler'
/// @dev Should be used just for testing
/// @param ruler The owner of the RuleSet
/// @return bytes32 that contains the name of the RuleSet belonging to 'ruler'
function getRulesetName(address ruler) public view returns(bytes32) {
// require((msg.sender == ruler) || (msg.sender == rulesMaster));
require(rulers[ruler].isValue);
return rulers[ruler].ruleSetId;
}
/// @author Aaron Kendall
/// @notice This method will alter the operator used to evaluate the final result of all the rules executed together (i.e., AND vs. OR)
/// @dev This method can only invoked for a RuleSet (whose ID is the owner's account ID) by its owner or the contract's owner.
/// @param ruler The owner of the RuleSet
/// @param flagUseAndOp Flag indicating whether to 'AND' the rules (i.e., true) or to 'OR' the rules (i.e., false)
/// @return
function setRulesetEvalOp(address ruler, bool flagUseAndOp) public {
require((msg.sender == ruler) || (msg.sender == rulesMaster));
require(rulers[ruler].isValue);
rulers[ruler].andOp = flagUseAndOp;
}
/// @author Aaron Kendall
/// @notice This method populates the record of 'ruler' with a value that represents an instance of an Attribute
/// @dev This method does not yet check to see if the provided 'key' is the valid name of an Attribute. Is it worth the gas?
/// @param ruler The owner of the RuleSet
/// @param key The name of the Attribute for the value being inserted into the record
/// @param value The string to insert into the record
/// @return
function setValueOnRecord(address ruler, bytes32 key, string value) public {
require(rulers[ruler].isValue);
(currentRecords[ruler])[key] = value;
}
/// @author Aaron Kendall
/// @notice This method will concatenate 5 strings into one
/// @dev Copied from a code snippet on StackOverflow by Bertani from Oraclize. This method probably isn't gas-efficient, and it should probably only be used for testing.
/// @param _a The seed/base of the string concatenation
/// @param _b The second string to concatenate
/// @param _c The third string to concatenate
/// @param _d The fourth string to concatenate
/// @param _e The fifth string to concatenate
/// @return string that contains the aggregate of all strings that have been concatenated together
function strConcat(string _a, string _b, string _c, string _d, string _e) private pure 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);
}
/// @author Aaron Kendall
/// @notice This method will concatenate 4 strings into one
/// @dev Copied from a code snippet on StackOverflow by Bertani from Oraclize. This method probably isn't gas-efficient, and it should probably only be used for testing.
/// @param _a The seed/base of the string concatenation
/// @param _b The second string to concatenate
/// @param _c The third string to concatenate
/// @param _d The fourth string to concatenate
/// @return string that contains the aggregate of all strings that have been concatenated together
function strConcat(string _a, string _b, string _c, string _d) private pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
/// @author Aaron Kendall
/// @notice This method will concatenate 3 strings into one
/// @dev Copied from a code snippet on StackOverflow by Bertani from Oraclize. This method probably isn't gas-efficient, and it should probably only be used for testing.
/// @param _a The seed/base of the string concatenation
/// @param _b The second string to concatenate
/// @param _c The third string to concatenate
/// @return string that contains the aggregate of all strings that have been concatenated together
function strConcat(string _a, string _b, string _c) private pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
/// @author Aaron Kendall
/// @notice This method will concatenate 2 strings into one
/// @dev Copied from a code snippet on StackOverflow by Bertani from Oraclize. This method probably isn't gas-efficient, and it should probably only be used for testing.
/// @param _a The seed/base of the string concatenation
/// @param _b The second string to concatenate
/// @return string that contains the aggregate of all strings that have been concatenated together
function strConcat(string _a, string _b) private pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
}
| @author Aaron Kendall @notice Retrieves the a verbose description of the rules that will be invoked by the RuleSet owned by 'ruler' @dev Should be used just for testing, since it's likely an expensive operation in terms of gas @param ruler The owner of the RuleSet whose rules we want to examine @return string that contains the verbose description of the rules in the RuleSet Now collect the rules | function getRulePlan(address ruler) public view returns (string) {
require(rulers[ruler].isValue);
string memory ruleReport = "\n";
WonkaLib.WonkaRule[] memory targetRules = allRules[rulers[ruler].ruleSetId];
for (uint idx = 0; idx < targetRules.length; idx++) {
if (uint(RuleTypes.IsEqual) == targetRules[idx].ruleType) {
if (targetRules[idx].targetAttr.isNumeric) {
ruleReport = strConcat(ruleReport, "\nAttribute(", bytes32ToString(targetRules[idx].targetAttr.attrName), ") must be (numeric) equal to ", targetRules[idx].ruleValue);
ruleReport = strConcat(ruleReport, "\nAttribute(", bytes32ToString(targetRules[idx].targetAttr.attrName), ") must be (string) equal to ", targetRules[idx].ruleValue);
}
ruleReport = strConcat(ruleReport, "\nAttribute(", bytes32ToString(targetRules[idx].targetAttr.attrName), ") must be less than ", targetRules[idx].ruleValue);
ruleReport = strConcat(ruleReport, "\nAttribute(", bytes32ToString(targetRules[idx].targetAttr.attrName), ") must be greater than ", targetRules[idx].ruleValue);
}
}
ruleReport = strConcat(ruleReport, "\n");
return ruleReport;
}
| 12,559,375 | [
1,
37,
297,
265,
1475,
409,
454,
225,
20507,
326,
279,
3988,
2477,
434,
326,
2931,
716,
903,
506,
8187,
635,
326,
6781,
694,
16199,
635,
296,
86,
17040,
11,
225,
9363,
506,
1399,
2537,
364,
7769,
16,
3241,
518,
1807,
10374,
392,
19326,
1674,
316,
6548,
434,
16189,
225,
436,
17040,
1021,
3410,
434,
326,
6781,
694,
8272,
2931,
732,
2545,
358,
19707,
558,
327,
533,
716,
1914,
326,
3988,
2477,
434,
326,
2931,
316,
326,
6781,
694,
4494,
3274,
326,
2931,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
19048,
5365,
12,
2867,
436,
17040,
13,
1071,
1476,
1135,
261,
1080,
13,
288,
203,
203,
3639,
2583,
12,
86,
332,
414,
63,
86,
17040,
8009,
291,
620,
1769,
203,
203,
3639,
533,
3778,
1720,
4820,
273,
1548,
82,
14432,
203,
203,
3639,
678,
265,
7282,
5664,
18,
59,
265,
7282,
2175,
8526,
3778,
1018,
4478,
273,
777,
4478,
63,
86,
332,
414,
63,
86,
17040,
8009,
5345,
18523,
15533,
203,
203,
3639,
364,
261,
11890,
2067,
273,
374,
31,
2067,
411,
1018,
4478,
18,
2469,
31,
2067,
27245,
288,
203,
203,
5411,
309,
261,
11890,
12,
2175,
2016,
18,
2520,
5812,
13,
422,
1018,
4478,
63,
3465,
8009,
5345,
559,
13,
288,
203,
203,
7734,
309,
261,
3299,
4478,
63,
3465,
8009,
3299,
3843,
18,
291,
9902,
13,
288,
7010,
10792,
1720,
4820,
273,
609,
15113,
12,
5345,
4820,
16,
1548,
82,
1499,
2932,
16,
1731,
1578,
5808,
12,
3299,
4478,
63,
3465,
8009,
3299,
3843,
18,
1747,
461,
3631,
9369,
1297,
506,
261,
5246,
13,
3959,
358,
3104,
1018,
4478,
63,
3465,
8009,
5345,
620,
1769,
7010,
10792,
1720,
4820,
273,
609,
15113,
12,
5345,
4820,
16,
1548,
82,
1499,
2932,
16,
1731,
1578,
5808,
12,
3299,
4478,
63,
3465,
8009,
3299,
3843,
18,
1747,
461,
3631,
9369,
1297,
506,
261,
1080,
13,
3959,
358,
3104,
1018,
4478,
63,
3465,
8009,
5345,
620,
1769,
7010,
7734,
289,
203,
203,
203,
7734,
1720,
4820,
273,
609,
15113,
12,
5345,
4820,
16,
1548,
82,
1499,
2932,
16,
1731,
1578,
5808,
12,
3299,
2
]
|
./full_match/71402/0x6291C16e5553dc70b54974FE19aE0cBfe0Cd0FD6/sources/_balancer-labs/v2-pool-utils/contracts/BasePool.sol | * @dev Same as `_downscaleUp`, but for an entire array. This function does not return anything, but instead mutates the `amounts` array./ | function _downscaleUpArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal pure {
uint256 length = amounts.length;
InputHelpers.ensureInputLengthMatch(length, scalingFactors.length);
for (uint256 i = 0; i < length; ++i) {
amounts[i] = FixedPoint.divUp(amounts[i], scalingFactors[i]);
}
}
| 7,092,193 | [
1,
8650,
487,
1375,
67,
2378,
5864,
1211,
9191,
1496,
364,
392,
7278,
526,
18,
1220,
445,
1552,
486,
327,
6967,
16,
1496,
3560,
4318,
815,
326,
1375,
8949,
87,
68,
526,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
2378,
5864,
1211,
1076,
12,
11890,
5034,
8526,
3778,
30980,
16,
2254,
5034,
8526,
3778,
10612,
23535,
13,
2713,
16618,
288,
203,
3639,
2254,
5034,
769,
273,
30980,
18,
2469,
31,
203,
3639,
2741,
13375,
18,
15735,
1210,
1782,
2060,
12,
2469,
16,
10612,
23535,
18,
2469,
1769,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
769,
31,
965,
77,
13,
288,
203,
5411,
30980,
63,
77,
65,
273,
15038,
2148,
18,
2892,
1211,
12,
8949,
87,
63,
77,
6487,
10612,
23535,
63,
77,
19226,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
contract Candidate {
/* Structs */
struct CandidateDetails {
uint256 id;
string name;
string nic;
string party;
}
/* Storage */
/** @dev Number of candidates added. */
address[] private candidateAddresses;
/** Mapping of address to candidate details */
mapping (address => CandidateDetails) public candidates;
/* Public Functions */
/**
* @notice Add a candidate.
*
* @dev Adds a new candidate to the system.
* - Checks whether candidate is already added or not.
* - Adds a candidate to the `candidates` mapping.
* - Adds candidate's address to `candidateAddresses` address array.
*
* @param _name - candidate's name
* @param _nic - candidate's nic
* @param _party - candidate's party
*/
function addCandidate(
string memory _name,
string memory _nic,
string memory _party
) public {
require (
candidates[msg.sender].id == uint256(0),
"Candidate must not already exist."
);
uint256 id = candidateAddresses.length + uint(100);
candidates[msg.sender] = CandidateDetails(
id,
_name,
_nic,
_party
);
candidateAddresses.push(msg.sender);
}
/**
* @notice Get candidate details.
*
* @dev Get candidate details by `_address`
* - candidate for `_address` must be available.
*
* @param _address - address of a candidate.
*/
function getCandidate(address _address)
public
view
returns (
uint256 id_,
string memory name_,
string memory nic_,
string memory party_
)
{
require (
candidates[_address].id != uint256(0),
"Candidate not present."
);
CandidateDetails memory candidate = candidates[_address];
return (
candidate.id,
candidate.name,
candidate.nic,
candidate.party
);
}
/**
* Get total candidate count.
*
* @notice Returns total candidate count.
*/
function getCandidateCount() public view returns (uint256 count_) {
count_ = candidateAddresses.length;
}
}
| * Get total candidate count. @notice Returns total candidate count./ | function getCandidateCount() public view returns (uint256 count_) {
count_ = candidateAddresses.length;
}
| 13,115,270 | [
1,
967,
2078,
5500,
1056,
18,
225,
2860,
2078,
5500,
1056,
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,
1927,
8824,
1380,
1435,
1071,
1476,
1135,
261,
11890,
5034,
1056,
67,
13,
288,
203,
3639,
1056,
67,
273,
5500,
7148,
18,
2469,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x6E4762B06e6a05513Ff4c59d5e678A39bABE7999/sources/contracts/CamelCoin.sol | % div FEE_DENOMINATOR
| uint256 public feeMarketing; | 3,547,720 | [
1,
9,
3739,
478,
9383,
67,
13296,
1872,
706,
3575,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
14036,
3882,
21747,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0xAE426d8a5f3ebB56ACe9cb725657314A3A52Df1d/sources/contracts/ERC20.sol | @title TRIAS ERC20 contract @notice TRIAS ERC20 contract @author havefunbc | contract Token is Ownable,ERC20 {
constructor (string memory name, string memory symbol) ERC20(name, symbol) {}
function Issuance(address to, uint256 amount) external onlyOwner(){
_mint(to, amount * (1 ether));
}
}
| 11,634,125 | [
1,
6566,
3033,
4232,
39,
3462,
6835,
225,
22800,
3033,
4232,
39,
3462,
6835,
225,
1240,
12125,
13459,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
3155,
353,
14223,
6914,
16,
654,
39,
3462,
288,
203,
377,
203,
377,
203,
203,
565,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
13,
4232,
39,
3462,
12,
529,
16,
3273,
13,
2618,
203,
565,
445,
9310,
89,
1359,
12,
2867,
358,
16,
2254,
5034,
3844,
13,
3903,
1338,
5541,
1435,
95,
203,
3639,
389,
81,
474,
12,
869,
16,
3844,
380,
261,
21,
225,
2437,
10019,
7010,
565,
289,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/41/0x13D32F87D75934d61Fd4a0007C771aD66a916dDE/sources/contracts/IceToken.sol | * @dev Removes an NFT address from the list/ | function removeNftAddress(address nftAddress) external onlyOwner {
require(nftAddress != address(0), "removeNftAddress: zero address");
require(_nftAddresses.contains(nftAddress), "removeNftAddress: not added");
_nftAddresses.remove(nftAddress);
emit RemoveNftAddress(nftAddress);
}
| 16,373,458 | [
1,
6220,
392,
423,
4464,
1758,
628,
326,
666,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
1206,
50,
1222,
1887,
12,
2867,
290,
1222,
1887,
13,
3903,
1338,
5541,
288,
203,
565,
2583,
12,
82,
1222,
1887,
480,
1758,
12,
20,
3631,
315,
4479,
50,
1222,
1887,
30,
3634,
1758,
8863,
203,
565,
2583,
24899,
82,
1222,
7148,
18,
12298,
12,
82,
1222,
1887,
3631,
315,
4479,
50,
1222,
1887,
30,
486,
3096,
8863,
203,
203,
565,
389,
82,
1222,
7148,
18,
4479,
12,
82,
1222,
1887,
1769,
203,
565,
3626,
3581,
50,
1222,
1887,
12,
82,
1222,
1887,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//Address: 0x8a69a63fca907939e5c7d92a260d8875c8700383
//Contract name: BlobStore
//Balance: 0 Ether
//Verification Date: 10/31/2016
//Transacion Count: 3
// CODE STARTS HERE
pragma solidity ^0.4.3;
/**
* @title AbstractBlobStore
* @author Jonathan Brown <[email protected]>
* @dev Contracts must be able to interact with blobs regardless of which BlobStore contract they are stored in, so it is necessary for there to be an abstract contract that defines an interface for BlobStore contracts.
*/
contract AbstractBlobStore {
/**
* @dev Creates a new blob. It is guaranteed that different users will never receive the same blobId, even before consensus has been reached. This prevents blobId sniping. Consider createWithNonce() if not calling from another contract.
* @param flags Packed blob settings.
* @param contents Contents of the blob to be stored.
* @return blobId Id of the blob.
*/
function create(bytes4 flags, bytes contents) external returns (bytes20 blobId);
/**
* @dev Creates a new blob using provided nonce. It is guaranteed that different users will never receive the same blobId, even before consensus has been reached. This prevents blobId sniping. This method is cheaper than create(), especially if multiple blobs from the same account end up in the same block. However, it is not suitable for calling from other contracts because it will throw if a unique nonce is not provided.
* @param flagsNonce First 4 bytes: Packed blob settings. The parameter as a whole must never have been passed to this function from the same account, or it will throw.
* @param contents Contents of the blob to be stored.
* @return blobId Id of the blob.
*/
function createWithNonce(bytes32 flagsNonce, bytes contents) external returns (bytes20 blobId);
/**
* @dev Create a new blob revision.
* @param blobId Id of the blob.
* @param contents Contents of the new revision.
* @return revisionId The new revisionId.
*/
function createNewRevision(bytes20 blobId, bytes contents) external returns (uint revisionId);
/**
* @dev Update a blob's latest revision.
* @param blobId Id of the blob.
* @param contents Contents that should replace the latest revision.
*/
function updateLatestRevision(bytes20 blobId, bytes contents) external;
/**
* @dev Retract a blob's latest revision. Revision 0 cannot be retracted.
* @param blobId Id of the blob.
*/
function retractLatestRevision(bytes20 blobId) external;
/**
* @dev Delete all a blob's revisions and replace it with a new blob.
* @param blobId Id of the blob.
* @param contents Contents that should be stored.
*/
function restart(bytes20 blobId, bytes contents) external;
/**
* @dev Retract a blob.
* @param blobId Id of the blob. This blobId can never be used again.
*/
function retract(bytes20 blobId) external;
/**
* @dev Enable transfer of the blob to the current user.
* @param blobId Id of the blob.
*/
function transferEnable(bytes20 blobId) external;
/**
* @dev Disable transfer of the blob to the current user.
* @param blobId Id of the blob.
*/
function transferDisable(bytes20 blobId) external;
/**
* @dev Transfer a blob to a new user.
* @param blobId Id of the blob.
* @param recipient Address of the user to transfer to blob to.
*/
function transfer(bytes20 blobId, address recipient) external;
/**
* @dev Disown a blob.
* @param blobId Id of the blob.
*/
function disown(bytes20 blobId) external;
/**
* @dev Set a blob as not updatable.
* @param blobId Id of the blob.
*/
function setNotUpdatable(bytes20 blobId) external;
/**
* @dev Set a blob to enforce revisions.
* @param blobId Id of the blob.
*/
function setEnforceRevisions(bytes20 blobId) external;
/**
* @dev Set a blob to not be retractable.
* @param blobId Id of the blob.
*/
function setNotRetractable(bytes20 blobId) external;
/**
* @dev Set a blob to not be transferable.
* @param blobId Id of the blob.
*/
function setNotTransferable(bytes20 blobId) external;
/**
* @dev Get the id for this BlobStore contract.
* @return Id of the contract.
*/
function getContractId() external constant returns (bytes12);
/**
* @dev Check if a blob exists.
* @param blobId Id of the blob.
* @return exists True if the blob exists.
*/
function getExists(bytes20 blobId) external constant returns (bool exists);
/**
* @dev Get info about a blob.
* @param blobId Id of the blob.
* @return flags Packed blob settings.
* @return owner Owner of the blob.
* @return revisionCount How many revisions the blob has.
* @return blockNumbers The block numbers of the revisions.
*/
function getInfo(bytes20 blobId) external constant returns (bytes4 flags, address owner, uint revisionCount, uint[] blockNumbers);
/**
* @dev Get all a blob's flags.
* @param blobId Id of the blob.
* @return flags Packed blob settings.
*/
function getFlags(bytes20 blobId) external constant returns (bytes4 flags);
/**
* @dev Determine if a blob is updatable.
* @param blobId Id of the blob.
* @return updatable True if the blob is updatable.
*/
function getUpdatable(bytes20 blobId) external constant returns (bool updatable);
/**
* @dev Determine if a blob enforces revisions.
* @param blobId Id of the blob.
* @return enforceRevisions True if the blob enforces revisions.
*/
function getEnforceRevisions(bytes20 blobId) external constant returns (bool enforceRevisions);
/**
* @dev Determine if a blob is retractable.
* @param blobId Id of the blob.
* @return retractable True if the blob is blob retractable.
*/
function getRetractable(bytes20 blobId) external constant returns (bool retractable);
/**
* @dev Determine if a blob is transferable.
* @param blobId Id of the blob.
* @return transferable True if the blob is transferable.
*/
function getTransferable(bytes20 blobId) external constant returns (bool transferable);
/**
* @dev Get the owner of a blob.
* @param blobId Id of the blob.
* @return owner Owner of the blob.
*/
function getOwner(bytes20 blobId) external constant returns (address owner);
/**
* @dev Get the number of revisions a blob has.
* @param blobId Id of the blob.
* @return revisionCount How many revisions the blob has.
*/
function getRevisionCount(bytes20 blobId) external constant returns (uint revisionCount);
/**
* @dev Get the block numbers for all of a blob's revisions.
* @param blobId Id of the blob.
* @return blockNumbers Revision block numbers.
*/
function getAllRevisionBlockNumbers(bytes20 blobId) external constant returns (uint[] blockNumbers);
}
/**
* @title BlobStoreFlags
* @author Jonathan Brown <[email protected]>
*/
contract BlobStoreFlags {
bytes4 constant UPDATABLE = 0x01; // True if the blob is updatable. After creation can only be disabled.
bytes4 constant ENFORCE_REVISIONS = 0x02; // True if the blob is enforcing revisions. After creation can only be enabled.
bytes4 constant RETRACTABLE = 0x04; // True if the blob can be retracted. After creation can only be disabled.
bytes4 constant TRANSFERABLE = 0x08; // True if the blob be transfered to another user or disowned. After creation can only be disabled.
bytes4 constant ANONYMOUS = 0x10; // True if the blob should not have an owner.
}
/**
* @title BlobStoreRegistry
* @author Jonathan Brown <[email protected]>
*/
contract BlobStoreRegistry {
/**
* @dev Mapping of contract id to contract addresses.
*/
mapping (bytes12 => address) contractAddresses;
/**
* @dev An AbstractBlobStore contract has been registered.
* @param contractId Id of the contract.
* @param contractAddress Address of the contract.
*/
event Register(bytes12 indexed contractId, address indexed contractAddress);
/**
* @dev Throw if contract is registered.
* @param contractId Id of the contract.
*/
modifier isNotRegistered(bytes12 contractId) {
if (contractAddresses[contractId] != 0) {
throw;
}
_;
}
/**
* @dev Throw if contract is not registered.
* @param contractId Id of the contract.
*/
modifier isRegistered(bytes12 contractId) {
if (contractAddresses[contractId] == 0) {
throw;
}
_;
}
/**
* @dev Register the calling BlobStore contract.
* @param contractId Id of the BlobStore contract.
*/
function register(bytes12 contractId) external isNotRegistered(contractId) {
// Record the calling contract address.
contractAddresses[contractId] = msg.sender;
// Log the registration.
Register(contractId, msg.sender);
}
/**
* @dev Get an AbstractBlobStore contract.
* @param contractId Id of the contract.
* @return blobStore The AbstractBlobStore contract.
*/
function getBlobStore(bytes12 contractId) external constant isRegistered(contractId) returns (AbstractBlobStore blobStore) {
blobStore = AbstractBlobStore(contractAddresses[contractId]);
}
}
/**
* @title BlobStore
* @author Jonathan Brown <[email protected]>
*/
contract BlobStore is AbstractBlobStore, BlobStoreFlags {
/**
* @dev Single slot structure of blob info.
*/
struct BlobInfo {
bytes4 flags; // Packed blob settings.
uint32 revisionCount; // Number of revisions including revision 0.
uint32 blockNumber; // Block number which contains revision 0.
address owner; // Who owns this blob.
}
/**
* @dev Mapping of blobId to blob info.
*/
mapping (bytes20 => BlobInfo) blobInfo;
/**
* @dev Mapping of blobId to mapping of packed slots of eight 32-bit block numbers.
*/
mapping (bytes20 => mapping (uint => bytes32)) packedBlockNumbers;
/**
* @dev Mapping of blobId to mapping of transfer recipient addresses to enabled.
*/
mapping (bytes20 => mapping (address => bool)) enabledTransfers;
/**
* @dev Id of this instance of BlobStore. Unique across all blockchains.
*/
bytes12 contractId;
/**
* @dev A blob revision has been published.
* @param blobId Id of the blob.
* @param revisionId Id of the revision (the highest at time of logging).
* @param contents Contents of the blob.
*/
event Store(bytes20 indexed blobId, uint indexed revisionId, bytes contents);
/**
* @dev A revision has been retracted.
* @param blobId Id of the blob.
* @param revisionId Id of the revision.
*/
event RetractRevision(bytes20 indexed blobId, uint revisionId);
/**
* @dev An entire blob has been retracted. This cannot be undone.
* @param blobId Id of the blob.
*/
event Retract(bytes20 indexed blobId);
/**
* @dev A blob has been transfered to a new address.
* @param blobId Id of the blob.
* @param recipient The address that now owns the blob.
*/
event Transfer(bytes20 indexed blobId, address recipient);
/**
* @dev A blob has been disowned. This cannot be undone.
* @param blobId Id of the blob.
*/
event Disown(bytes20 indexed blobId);
/**
* @dev A blob has been set as not updatable. This cannot be undone.
* @param blobId Id of the blob.
*/
event SetNotUpdatable(bytes20 indexed blobId);
/**
* @dev A blob has been set as enforcing revisions. This cannot be undone.
* @param blobId Id of the blob.
*/
event SetEnforceRevisions(bytes20 indexed blobId);
/**
* @dev A blob has been set as not retractable. This cannot be undone.
* @param blobId Id of the blob.
*/
event SetNotRetractable(bytes20 indexed blobId);
/**
* @dev A blob has been set as not transferable. This cannot be undone.
* @param blobId Id of the blob.
*/
event SetNotTransferable(bytes20 indexed blobId);
/**
* @dev Throw if the blob has not been used before or it has been retracted.
* @param blobId Id of the blob.
*/
modifier exists(bytes20 blobId) {
BlobInfo info = blobInfo[blobId];
if (info.blockNumber == 0 || info.blockNumber == uint32(-1)) {
throw;
}
_;
}
/**
* @dev Throw if the owner of the blob is not the message sender.
* @param blobId Id of the blob.
*/
modifier isOwner(bytes20 blobId) {
if (blobInfo[blobId].owner != msg.sender) {
throw;
}
_;
}
/**
* @dev Throw if the blob is not updatable.
* @param blobId Id of the blob.
*/
modifier isUpdatable(bytes20 blobId) {
if (blobInfo[blobId].flags & UPDATABLE == 0) {
throw;
}
_;
}
/**
* @dev Throw if the blob is not enforcing revisions.
* @param blobId Id of the blob.
*/
modifier isNotEnforceRevisions(bytes20 blobId) {
if (blobInfo[blobId].flags & ENFORCE_REVISIONS != 0) {
throw;
}
_;
}
/**
* @dev Throw if the blob is not retractable.
* @param blobId Id of the blob.
*/
modifier isRetractable(bytes20 blobId) {
if (blobInfo[blobId].flags & RETRACTABLE == 0) {
throw;
}
_;
}
/**
* @dev Throw if the blob is not transferable.
* @param blobId Id of the blob.
*/
modifier isTransferable(bytes20 blobId) {
if (blobInfo[blobId].flags & TRANSFERABLE == 0) {
throw;
}
_;
}
/**
* @dev Throw if the blob is not transferable to a specific user.
* @param blobId Id of the blob.
* @param recipient Address of the user.
*/
modifier isTransferEnabled(bytes20 blobId, address recipient) {
if (!enabledTransfers[blobId][recipient]) {
throw;
}
_;
}
/**
* @dev Throw if the blob only has one revision.
* @param blobId Id of the blob.
*/
modifier hasAdditionalRevisions(bytes20 blobId) {
if (blobInfo[blobId].revisionCount == 1) {
throw;
}
_;
}
/**
* @dev Throw if a specific blob revision does not exist.
* @param blobId Id of the blob.
* @param revisionId Id of the revision.
*/
modifier revisionExists(bytes20 blobId, uint revisionId) {
if (revisionId >= blobInfo[blobId].revisionCount) {
throw;
}
_;
}
/**
* @dev Constructor.
* @param registry Address of BlobStoreRegistry contract to register with.
*/
function BlobStore(BlobStoreRegistry registry) {
// Create id for this contract.
contractId = bytes12(keccak256(this, block.blockhash(block.number - 1)));
// Register this contract.
registry.register(contractId);
}
/**
* @dev Creates a new blob. It is guaranteed that different users will never receive the same blobId, even before consensus has been reached. This prevents blobId sniping. Consider createWithNonce() if not calling from another contract.
* @param flags Packed blob settings.
* @param contents Contents of the blob to be stored.
* @return blobId Id of the blob.
*/
function create(bytes4 flags, bytes contents) external returns (bytes20 blobId) {
// Generate the blobId.
blobId = bytes20(keccak256(msg.sender, block.blockhash(block.number - 1)));
// Make sure this blobId has not been used before (could be in the same block).
while (blobInfo[blobId].blockNumber != 0) {
blobId = bytes20(keccak256(blobId));
}
// Store blob info in state.
blobInfo[blobId] = BlobInfo({
flags: flags,
revisionCount: 1,
blockNumber: uint32(block.number),
owner: (flags & ANONYMOUS != 0) ? 0 : msg.sender,
});
// Store the first revision in a log in the current block.
Store(blobId, 0, contents);
}
/**
* @dev Creates a new blob using provided nonce. It is guaranteed that different users will never receive the same blobId, even before consensus has been reached. This prevents blobId sniping. This method is cheaper than create(), especially if multiple blobs from the same account end up in the same block. However, it is not suitable for calling from other contracts because it will throw if a unique nonce is not provided.
* @param flagsNonce First 4 bytes: Packed blob settings. The parameter as a whole must never have been passed to this function from the same account, or it will throw.
* @param contents Contents of the blob to be stored.
* @return blobId Id of the blob.
*/
function createWithNonce(bytes32 flagsNonce, bytes contents) external returns (bytes20 blobId) {
// Generate the blobId.
blobId = bytes20(keccak256(msg.sender, flagsNonce));
// Make sure this blobId has not been used before.
if (blobInfo[blobId].blockNumber != 0) {
throw;
}
// Store blob info in state.
blobInfo[blobId] = BlobInfo({
flags: bytes4(flagsNonce),
revisionCount: 1,
blockNumber: uint32(block.number),
owner: (bytes4(flagsNonce) & ANONYMOUS != 0) ? 0 : msg.sender,
});
// Store the first revision in a log in the current block.
Store(blobId, 0, contents);
}
/**
* @dev Store a blob revision block number in a packed slot.
* @param blobId Id of the blob.
* @param offset The offset of the block number should be retreived.
*/
function _setPackedBlockNumber(bytes20 blobId, uint offset) internal {
// Get the slot.
bytes32 slot = packedBlockNumbers[blobId][offset / 8];
// Wipe the previous block number.
slot &= ~bytes32(uint32(-1) * 2**((offset % 8) * 32));
// Insert the current block number.
slot |= bytes32(uint32(block.number) * 2**((offset % 8) * 32));
// Store the slot.
packedBlockNumbers[blobId][offset / 8] = slot;
}
/**
* @dev Create a new blob revision.
* @param blobId Id of the blob.
* @param contents Contents of the new revision.
* @return revisionId The new revisionId.
*/
function createNewRevision(bytes20 blobId, bytes contents) external isOwner(blobId) isUpdatable(blobId) returns (uint revisionId) {
// Increment the number of revisions.
revisionId = blobInfo[blobId].revisionCount++;
// Store the block number.
_setPackedBlockNumber(blobId, revisionId - 1);
// Store the revision in a log in the current block.
Store(blobId, revisionId, contents);
}
/**
* @dev Update a blob's latest revision.
* @param blobId Id of the blob.
* @param contents Contents that should replace the latest revision.
*/
function updateLatestRevision(bytes20 blobId, bytes contents) external isOwner(blobId) isUpdatable(blobId) isNotEnforceRevisions(blobId) {
BlobInfo info = blobInfo[blobId];
uint revisionId = info.revisionCount - 1;
// Update the block number.
if (revisionId == 0) {
info.blockNumber = uint32(block.number);
}
else {
_setPackedBlockNumber(blobId, revisionId - 1);
}
// Store the revision in a log in the current block.
Store(blobId, revisionId, contents);
}
/**
* @dev Retract a blob's latest revision. Revision 0 cannot be retracted.
* @param blobId Id of the blob.
*/
function retractLatestRevision(bytes20 blobId) external isOwner(blobId) isUpdatable(blobId) isNotEnforceRevisions(blobId) hasAdditionalRevisions(blobId) {
uint revisionId = --blobInfo[blobId].revisionCount;
// Delete the slot if it is no longer required.
if (revisionId % 8 == 1) {
delete packedBlockNumbers[blobId][revisionId / 8];
}
// Log the revision retraction.
RetractRevision(blobId, revisionId);
}
/**
* @dev Delete all of a blob's packed revision block numbers.
* @param blobId Id of the blob.
*/
function _deleteAllPackedRevisionBlockNumbers(bytes20 blobId) internal {
// Determine how many slots should be deleted.
// Block number of the first revision is stored in the blob info, so the first slot only needs to be deleted if there are at least 2 revisions.
uint slotCount = (blobInfo[blobId].revisionCount + 6) / 8;
// Delete the slots.
for (uint i = 0; i < slotCount; i++) {
delete packedBlockNumbers[blobId][i];
}
}
/**
* @dev Delete all a blob's revisions and replace it with a new blob.
* @param blobId Id of the blob.
* @param contents Contents that should be stored.
*/
function restart(bytes20 blobId, bytes contents) external isOwner(blobId) isUpdatable(blobId) isNotEnforceRevisions(blobId) {
// Delete the packed revision block numbers.
_deleteAllPackedRevisionBlockNumbers(blobId);
// Update the blob state info.
BlobInfo info = blobInfo[blobId];
info.revisionCount = 1;
info.blockNumber = uint32(block.number);
// Store the blob in a log in the current block.
Store(blobId, 0, contents);
}
/**
* @dev Retract a blob.
* @param blobId Id of the blob. This blobId can never be used again.
*/
function retract(bytes20 blobId) external isOwner(blobId) isRetractable(blobId) {
// Delete the packed revision block numbers.
_deleteAllPackedRevisionBlockNumbers(blobId);
// Mark this blob as retracted.
blobInfo[blobId] = BlobInfo({
flags: 0,
revisionCount: 0,
blockNumber: uint32(-1),
owner: 0,
});
// Log the blob retraction.
Retract(blobId);
}
/**
* @dev Enable transfer of the blob to the current user.
* @param blobId Id of the blob.
*/
function transferEnable(bytes20 blobId) external isTransferable(blobId) {
// Record in state that the current user will accept this blob.
enabledTransfers[blobId][msg.sender] = true;
}
/**
* @dev Disable transfer of the blob to the current user.
* @param blobId Id of the blob.
*/
function transferDisable(bytes20 blobId) external isTransferEnabled(blobId, msg.sender) {
// Record in state that the current user will not accept this blob.
enabledTransfers[blobId][msg.sender] = false;
}
/**
* @dev Transfer a blob to a new user.
* @param blobId Id of the blob.
* @param recipient Address of the user to transfer to blob to.
*/
function transfer(bytes20 blobId, address recipient) external isOwner(blobId) isTransferable(blobId) isTransferEnabled(blobId, recipient) {
// Update ownership of the blob.
blobInfo[blobId].owner = recipient;
// Disable this transfer in future and free up the slot.
enabledTransfers[blobId][recipient] = false;
// Log the transfer.
Transfer(blobId, recipient);
}
/**
* @dev Disown a blob.
* @param blobId Id of the blob.
*/
function disown(bytes20 blobId) external isOwner(blobId) isTransferable(blobId) {
// Remove the owner from the blob's state.
delete blobInfo[blobId].owner;
// Log that the blob has been disowned.
Disown(blobId);
}
/**
* @dev Set a blob as not updatable.
* @param blobId Id of the blob.
*/
function setNotUpdatable(bytes20 blobId) external isOwner(blobId) {
// Record in state that the blob is not updatable.
blobInfo[blobId].flags &= ~UPDATABLE;
// Log that the blob is not updatable.
SetNotUpdatable(blobId);
}
/**
* @dev Set a blob to enforce revisions.
* @param blobId Id of the blob.
*/
function setEnforceRevisions(bytes20 blobId) external isOwner(blobId) {
// Record in state that all changes to this blob must be new revisions.
blobInfo[blobId].flags |= ENFORCE_REVISIONS;
// Log that the blob now forces new revisions.
SetEnforceRevisions(blobId);
}
/**
* @dev Set a blob to not be retractable.
* @param blobId Id of the blob.
*/
function setNotRetractable(bytes20 blobId) external isOwner(blobId) {
// Record in state that the blob is not retractable.
blobInfo[blobId].flags &= ~RETRACTABLE;
// Log that the blob is not retractable.
SetNotRetractable(blobId);
}
/**
* @dev Set a blob to not be transferable.
* @param blobId Id of the blob.
*/
function setNotTransferable(bytes20 blobId) external isOwner(blobId) {
// Record in state that the blob is not transferable.
blobInfo[blobId].flags &= ~TRANSFERABLE;
// Log that the blob is not transferable.
SetNotTransferable(blobId);
}
/**
* @dev Get the id for this BlobStore contract.
* @return Id of the contract.
*/
function getContractId() external constant returns (bytes12) {
return contractId;
}
/**
* @dev Check if a blob exists.
* @param blobId Id of the blob.
* @return exists True if the blob exists.
*/
function getExists(bytes20 blobId) external constant returns (bool exists) {
BlobInfo info = blobInfo[blobId];
exists = info.blockNumber != 0 && info.blockNumber != uint32(-1);
}
/**
* @dev Get the block number for a specific blob revision.
* @param blobId Id of the blob.
* @param revisionId Id of the revision.
* @return blockNumber Block number of the specified revision.
*/
function _getRevisionBlockNumber(bytes20 blobId, uint revisionId) internal returns (uint blockNumber) {
if (revisionId == 0) {
blockNumber = blobInfo[blobId].blockNumber;
}
else {
bytes32 slot = packedBlockNumbers[blobId][(revisionId - 1) / 8];
blockNumber = uint32(uint256(slot) / 2**(((revisionId - 1) % 8) * 32));
}
}
/**
* @dev Get the block numbers for all of a blob's revisions.
* @param blobId Id of the blob.
* @return blockNumbers Revision block numbers.
*/
function _getAllRevisionBlockNumbers(bytes20 blobId) internal returns (uint[] blockNumbers) {
uint revisionCount = blobInfo[blobId].revisionCount;
blockNumbers = new uint[](revisionCount);
for (uint revisionId = 0; revisionId < revisionCount; revisionId++) {
blockNumbers[revisionId] = _getRevisionBlockNumber(blobId, revisionId);
}
}
/**
* @dev Get info about a blob.
* @param blobId Id of the blob.
* @return flags Packed blob settings.
* @return owner Owner of the blob.
* @return revisionCount How many revisions the blob has.
* @return blockNumbers The block numbers of the revisions.
*/
function getInfo(bytes20 blobId) external constant exists(blobId) returns (bytes4 flags, address owner, uint revisionCount, uint[] blockNumbers) {
BlobInfo info = blobInfo[blobId];
flags = info.flags;
owner = info.owner;
revisionCount = info.revisionCount;
blockNumbers = _getAllRevisionBlockNumbers(blobId);
}
/**
* @dev Get all a blob's flags.
* @param blobId Id of the blob.
* @return flags Packed blob settings.
*/
function getFlags(bytes20 blobId) external constant exists(blobId) returns (bytes4 flags) {
flags = blobInfo[blobId].flags;
}
/**
* @dev Determine if a blob is updatable.
* @param blobId Id of the blob.
* @return updatable True if the blob is updatable.
*/
function getUpdatable(bytes20 blobId) external constant exists(blobId) returns (bool updatable) {
updatable = blobInfo[blobId].flags & UPDATABLE != 0;
}
/**
* @dev Determine if a blob enforces revisions.
* @param blobId Id of the blob.
* @return enforceRevisions True if the blob enforces revisions.
*/
function getEnforceRevisions(bytes20 blobId) external constant exists(blobId) returns (bool enforceRevisions) {
enforceRevisions = blobInfo[blobId].flags & ENFORCE_REVISIONS != 0;
}
/**
* @dev Determine if a blob is retractable.
* @param blobId Id of the blob.
* @return retractable True if the blob is blob retractable.
*/
function getRetractable(bytes20 blobId) external constant exists(blobId) returns (bool retractable) {
retractable = blobInfo[blobId].flags & RETRACTABLE != 0;
}
/**
* @dev Determine if a blob is transferable.
* @param blobId Id of the blob.
* @return transferable True if the blob is transferable.
*/
function getTransferable(bytes20 blobId) external constant exists(blobId) returns (bool transferable) {
transferable = blobInfo[blobId].flags & TRANSFERABLE != 0;
}
/**
* @dev Get the owner of a blob.
* @param blobId Id of the blob.
* @return owner Owner of the blob.
*/
function getOwner(bytes20 blobId) external constant exists(blobId) returns (address owner) {
owner = blobInfo[blobId].owner;
}
/**
* @dev Get the number of revisions a blob has.
* @param blobId Id of the blob.
* @return revisionCount How many revisions the blob has.
*/
function getRevisionCount(bytes20 blobId) external constant exists(blobId) returns (uint revisionCount) {
revisionCount = blobInfo[blobId].revisionCount;
}
/**
* @dev Get the block number for a specific blob revision.
* @param blobId Id of the blob.
* @param revisionId Id of the revision.
* @return blockNumber Block number of the specified revision.
*/
function getRevisionBlockNumber(bytes20 blobId, uint revisionId) external constant revisionExists(blobId, revisionId) returns (uint blockNumber) {
blockNumber = _getRevisionBlockNumber(blobId, revisionId);
}
/**
* @dev Get the block numbers for all of a blob's revisions.
* @param blobId Id of the blob.
* @return blockNumbers Revision block numbers.
*/
function getAllRevisionBlockNumbers(bytes20 blobId) external constant exists(blobId) returns (uint[] blockNumbers) {
blockNumbers = _getAllRevisionBlockNumbers(blobId);
}
}
| * @dev Throw if the blob is not enforcing revisions. @param blobId Id of the blob./ | modifier isNotEnforceRevisions(bytes20 blobId) {
if (blobInfo[blobId].flags & ENFORCE_REVISIONS != 0) {
throw;
}
_;
}
| 12,534,274 | [
1,
8282,
309,
326,
4795,
353,
486,
570,
29036,
18325,
18,
225,
4795,
548,
3124,
434,
326,
4795,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
9606,
8827,
664,
5734,
21208,
12,
3890,
3462,
4795,
548,
13,
288,
203,
3639,
309,
261,
10721,
966,
63,
10721,
548,
8009,
7133,
473,
6693,
27817,
67,
862,
25216,
55,
480,
374,
13,
288,
203,
5411,
604,
31,
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
]
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
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 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;
}
}
// pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router {
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 RLDX is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping(address => bool) private _isExcludedFromMaxTx;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 100000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "RLDX";
string private _symbol = "RLDX";
uint8 private _decimals = 9;
uint256 public _taxFee = 0;
uint256 private _previousTaxFee = _taxFee;
uint256 public _devFee = 675;
uint256 private _devTax = 300;
uint256 private _marketingTax = 300;
uint256 private _platformTax = 75;
uint256 private _previousDevFee = _devFee;
uint256 public _liquidityFee = 125;
uint256 private _previousLiquidityFee = _liquidityFee;
uint256 public launchSellFee = 1200;
uint256 private _previousLaunchSellFee = launchSellFee;
uint256 public maxTxAmount = _tTotal.mul(5).div(1000); // 0.5%
address payable private _devWallet = payable(0xAEe7a4584a6629460B78D0a9eF56055e47E1425b);
address payable private _marketingWallet = payable(0xf154F43A4E9D53bD985C0CFBA23E24A4d83E0613);
address payable private _platformWallet = payable(0x70Ab96387335938E6fCe606625552AD3CA41f19E);
uint256 public launchSellFeeDeadline = 0;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 private minTokensBeforeSwap = 100000 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 liquidityEthBalance,
uint256 devEthBalance
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor () public {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
// internal exclude from max tx
_isExcludedFromMaxTx[owner()] = true;
_isExcludedFromMaxTx[address(this)] = true;
// launch sell fee
launchSellFeeDeadline = now + 2 days;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function setRouterAddress(address newRouter) public onlyOwner() {
IUniswapV2Router02 _newUniswapRouter = IUniswapV2Router02(newRouter);
uniswapV2Pair = IUniswapV2Factory(_newUniswapRouter.factory()).createPair(address(this), _newUniswapRouter.WETH());
uniswapV2Router = _newUniswapRouter;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0));
require(spender != address(0));
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function expectedRewards(address _sender) external view returns(uint256){
uint256 _balance = address(this).balance;
address sender = _sender;
uint256 holdersBal = balanceOf(sender);
uint totalExcludedBal;
for (uint256 i = 0; i < _excluded.length; i++){
totalExcludedBal = balanceOf(_excluded[i]).add(totalExcludedBal);
}
uint256 rewards = holdersBal.mul(_balance).div(_tTotal.sub(balanceOf(uniswapV2Pair)).sub(totalExcludedBal));
return rewards;
}
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 (
!_isExcludedFromMaxTx[from] &&
!_isExcludedFromMaxTx[to] // by default false
) {
require(
amount <= maxTxAmount,
"Transfer amount exceeds the maxTxAmount."
);
}
// initial sell fee
uint256 regularDevFee = _devFee;
uint256 regularDevTax = _devTax;
if (launchSellFeeDeadline >= now && to == uniswapV2Pair) {
_devFee = _devFee.add(launchSellFee);
_devTax = _devTax.add(launchSellFee);
}
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
// add liquidity
uint256 tokensToSell = maxTxAmount > contractTokenBalance ? contractTokenBalance : maxTxAmount;
swapAndLiquify(tokensToSell);
}
// indicates if fee should be deducted from transfer
bool takeFee = true;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
// transfer amount, it will take tax, dev fee, liquidity fee
_tokenTransfer(from, to, amount, takeFee);
_devFee = regularDevFee;
_devTax = regularDevTax;
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
// balance token fees based on variable percents
uint256 totalRedirectTokenFee = _devFee.add(_liquidityFee);
if (totalRedirectTokenFee == 0) return;
uint256 liquidityTokenBalance = contractTokenBalance.mul(_liquidityFee).div(totalRedirectTokenFee);
uint256 devTokenBalance = contractTokenBalance.mul(_devFee).div(totalRedirectTokenFee);
// split the liquidity balance into halves
uint256 halfLiquidity = liquidityTokenBalance.div(2);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the fee events include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
if (liquidityTokenBalance == 0 && devTokenBalance == 0) return;
// swap tokens for ETH
swapTokensForEth(devTokenBalance.add(halfLiquidity));
uint256 newBalance = address(this).balance.sub(initialBalance);
if(newBalance > 0) {
// rebalance ETH fees proportionally to half the liquidity
uint256 totalRedirectEthFee = _devFee.add(_liquidityFee.div(2));
uint256 liquidityEthBalance = newBalance.mul(_liquidityFee.div(2)).div(totalRedirectEthFee);
uint256 devEthBalance = newBalance.mul(_devFee).div(totalRedirectEthFee);
//
// for liquidity
// add to uniswap
//
addLiquidity(halfLiquidity, liquidityEthBalance);
//
// for dev fee
// send to the dev address
//
sendEthToDevAddress(devEthBalance);
emit SwapAndLiquify(contractTokenBalance, liquidityEthBalance, devEthBalance);
}
}
function sendEthToDevAddress(uint256 amount) private {
if (amount > 0 && _devFee > 0) {
uint256 ethToDev = amount.mul(_devTax).div(_devFee);
uint256 ethToMarketing = amount.mul(_marketingTax).div(_devFee);
uint256 ethToPlatform = amount.mul(_platformTax).div(_devFee);
if (ethToDev > 0) _devWallet.transfer(ethToDev);
if (ethToMarketing > 0) _marketingWallet.transfer(ethToMarketing);
if (ethToPlatform > 0) _platformWallet.transfer(ethToPlatform);
}
}
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 {
if (tokenAmount > 0 && ethAmount > 0) {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount} (
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee) {
removeAllFee();
}
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee) {
restoreAllFee();
}
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tDev, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeDev(tDev);
_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 tDev, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeDev(tDev);
_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 tDev, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeDev(tDev);
_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 tDev, 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);
_takeDev(tDev);
_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) {
(uint256 tTransferAmount, uint256 tFee, uint256 tDev, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tDev, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tDev, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tDev = calculateDevFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tDev).sub(tLiquidity);
return (tTransferAmount, tFee, tDev, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tDev, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rDev = tDev.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rDev).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
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 _takeDev(uint256 tDev) private {
uint256 currentRate = _getRate();
uint256 rDev = tDev.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rDev);
if(_isExcluded[address(this)]) {
_tOwned[address(this)] = _tOwned[address(this)].add(tDev);
}
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(10000);
}
function calculateDevFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_devFee).div(10000);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(10000);
}
function removeAllFee() private {
if(_taxFee == 0 && _devFee == 0 && _liquidityFee == 0 && launchSellFee == 0) return;
_previousTaxFee = _taxFee;
_previousDevFee = _devFee;
_previousLiquidityFee = _liquidityFee;
_previousLaunchSellFee = launchSellFee;
_taxFee = 0;
_devFee = 0;
_liquidityFee = 0;
launchSellFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_devFee = _previousDevFee;
_liquidityFee = _previousLiquidityFee;
launchSellFee = _previousLaunchSellFee;
}
function manualSwap() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualSend() external onlyOwner() {
uint256 contractEthBalance = address(this).balance;
sendEthToDevAddress(contractEthBalance);
}
function isExcludedFromFee(address account) external view returns(bool) {
return _isExcludedFromFee[account];
}
function excludeFromFee(address account) external onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) external onlyOwner {
_isExcludedFromFee[account] = false;
}
// for 0.5% input 5, for 1% input 10
function setMaxTxPercent(uint256 newMaxTx) external onlyOwner {
require(newMaxTx >= 5, "Max TX should be above 0.5%");
maxTxAmount = _tTotal.mul(newMaxTx).div(1000);
}
function setTaxFeePercent(uint256 taxFee) external onlyOwner() {
require(taxFee <= 800, "Maximum fee limit is 8 percent");
_taxFee = taxFee;
}
function setDevFeePercent(uint256 devFee, uint256 devTax, uint256 marketingTax) external onlyOwner() {
require(devFee <= 1500, "Maximum fee limit is 15 percent");
require(devTax + marketingTax == devFee, "Dev + marketing must equal total fee");
_devFee = devFee + _platformTax;
_devTax = devTax;
_marketingTax = marketingTax;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() {
require(liquidityFee <= 800, "Maximum fee limit is 8 percent");
_liquidityFee = liquidityFee;
}
function setLaunchSellFee(uint256 newLaunchSellFee) external onlyOwner {
require(newLaunchSellFee <= 2500, "Maximum launch sell fee is 25%");
launchSellFee = newLaunchSellFee;
}
function setSwapAndLiquifyEnabled(bool _enabled) external onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
function setMinTokensBeforeSwap(uint256 minTokens) external onlyOwner {
minTokensBeforeSwap = minTokens * 10**9;
emit MinTokensBeforeSwapUpdated(minTokens);
}
// to receive ETH from uniswapV2Router when swaping
receive() external payable {}
} | Create a uniswap pair for this new token set the rest of the contract variablesexclude owner and this contract from fee internal exclude from max tx launch sell fee | constructor () public {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromMaxTx[owner()] = true;
_isExcludedFromMaxTx[address(this)] = true;
launchSellFeeDeadline = now + 2 days;
emit Transfer(address(0), _msgSender(), _tTotal);
}
| 183,106 | [
1,
1684,
279,
640,
291,
91,
438,
3082,
364,
333,
394,
1147,
444,
326,
3127,
434,
326,
6835,
3152,
10157,
3410,
471,
333,
6835,
628,
14036,
2713,
4433,
628,
943,
2229,
8037,
357,
80,
14036,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
1832,
1071,
288,
203,
3639,
389,
86,
5460,
329,
63,
67,
3576,
12021,
1435,
65,
273,
389,
86,
5269,
31,
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,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
540,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
8443,
1435,
65,
273,
638,
31,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
203,
3639,
389,
291,
16461,
1265,
2747,
4188,
63,
8443,
1435,
65,
273,
638,
31,
203,
3639,
389,
291,
16461,
1265,
2747,
4188,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
203,
3639,
8037,
55,
1165,
14667,
15839,
273,
2037,
397,
576,
4681,
31,
203,
540,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
389,
3576,
12021,
9334,
389,
88,
5269,
2
]
|
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol";
import { IController } from "../../interfaces/IController.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { Invoke } from "../lib/Invoke.sol";
import { ModuleBase } from "../lib/ModuleBase.sol";
import { Position } from "../lib/Position.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
/**
* @title AirdropModule
* @author Set Protocol
*
* Module that enables managers to absorb tokens sent to the SetToken into the token's positions. With each SetToken,
* managers are able to specify 1) the airdrops they want to include, 2) an airdrop fee recipient, 3) airdrop fee,
* and 4) whether all users are allowed to trigger an airdrop.
*/
contract AirdropModule is ModuleBase, ReentrancyGuard {
using PreciseUnitMath for uint256;
using SafeMath for uint256;
using Position for uint256;
using SafeCast for int256;
using AddressArrayUtils for address[];
using Invoke for ISetToken;
using Position for ISetToken;
/* ============ Structs ============ */
struct AirdropSettings {
address[] airdrops; // Array of tokens manager is allowing to be absorbed
address feeRecipient; // Address airdrop fees are sent to
uint256 airdropFee; // Percentage in preciseUnits of airdrop sent to feeRecipient (1e16 = 1%)
bool anyoneAbsorb; // Boolean indicating if any address can call absorb or just the manager
}
/* ============ Events ============ */
event ComponentAbsorbed(
ISetToken indexed _setToken,
address _absorbedToken,
uint256 _absorbedQuantity,
uint256 _managerFee,
uint256 _protocolFee
);
/* ============ Modifiers ============ */
/**
* Throws if claim is confined to the manager and caller is not the manager
*/
modifier onlyValidCaller(ISetToken _setToken) {
require(_isValidCaller(_setToken), "Must be valid caller");
_;
}
/* ============ Constants ============ */
uint256 public constant AIRDROP_MODULE_PROTOCOL_FEE_INDEX = 0;
/* ============ State Variables ============ */
mapping(ISetToken => AirdropSettings) public airdropSettings;
/* ============ Constructor ============ */
constructor(IController _controller) public ModuleBase(_controller) {}
/* ============ External Functions ============ */
/**
* Absorb passed tokens into respective positions. If airdropFee defined, send portion to feeRecipient and portion to
* protocol feeRecipient address. Callable only by manager unless manager has set anyoneAbsorb to true.
*
* @param _setToken Address of SetToken
* @param _tokens Array of tokens to absorb
*/
function batchAbsorb(ISetToken _setToken, address[] memory _tokens)
external
nonReentrant
onlyValidCaller(_setToken)
onlyValidAndInitializedSet(_setToken)
{
_batchAbsorb(_setToken, _tokens);
}
/**
* Absorb specified token into position. If airdropFee defined, send portion to feeRecipient and portion to
* protocol feeRecipient address. Callable only by manager unless manager has set anyoneAbsorb to true.
*
* @param _setToken Address of SetToken
* @param _token Address of token to absorb
*/
function absorb(ISetToken _setToken, address _token)
external
nonReentrant
onlyValidCaller(_setToken)
onlyValidAndInitializedSet(_setToken)
{
_absorb(_setToken, _token);
}
/**
* SET MANAGER ONLY. Adds new tokens to be added to positions when absorb is called.
*
* @param _setToken Address of SetToken
* @param _airdrop List of airdrops to add
*/
function addAirdrop(ISetToken _setToken, address _airdrop) external onlyManagerAndValidSet(_setToken) {
require(!isAirdropToken(_setToken, _airdrop), "Token already added.");
airdropSettings[_setToken].airdrops.push(_airdrop);
}
/**
* SET MANAGER ONLY. Removes tokens from list to be absorbed.
*
* @param _setToken Address of SetToken
* @param _airdrop List of airdrops to remove
*/
function removeAirdrop(ISetToken _setToken, address _airdrop) external onlyManagerAndValidSet(_setToken) {
require(isAirdropToken(_setToken, _airdrop), "Token not added.");
airdropSettings[_setToken].airdrops = airdropSettings[_setToken].airdrops.remove(_airdrop);
}
/**
* SET MANAGER ONLY. Update whether manager allows other addresses to call absorb.
*
* @param _setToken Address of SetToken
*/
function updateAnyoneAbsorb(ISetToken _setToken) external onlyManagerAndValidSet(_setToken) {
airdropSettings[_setToken].anyoneAbsorb = !airdropSettings[_setToken].anyoneAbsorb;
}
/**
* SET MANAGER ONLY. Update address manager fees are sent to.
*
* @param _setToken Address of SetToken
* @param _newFeeRecipient Address of new fee recipient
*/
function updateFeeRecipient(
ISetToken _setToken,
address _newFeeRecipient
)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFeeRecipient != address(0), "Passed address must be non-zero");
airdropSettings[_setToken].feeRecipient = _newFeeRecipient;
}
/**
* SET MANAGER ONLY. Update airdrop fee percentage.
*
* @param _setToken Address of SetToken
* @param _newFee Percentage, in preciseUnits, of new airdrop fee (1e16 = 1%)
*/
function updateAirdropFee(
ISetToken _setToken,
uint256 _newFee
)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFee < PreciseUnitMath.preciseUnit(), "Airdrop fee can't exceed 100%");
// Absorb all outstanding tokens before fee is updated
_batchAbsorb(_setToken, airdropSettings[_setToken].airdrops);
airdropSettings[_setToken].airdropFee = _newFee;
}
/**
* SET MANAGER ONLY. Initialize module with SetToken and set initial airdrop tokens as well as specify
* whether anyone can call absorb.
*
* @param _setToken Address of SetToken
* @param _airdropSettings Struct of airdrop setting for Set including accepted airdrops, feeRecipient,
* airdropFee, and indicating if anyone can call an absorb
*/
function initialize(
ISetToken _setToken,
AirdropSettings memory _airdropSettings
)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
require(_airdropSettings.airdrops.length > 0, "At least one token must be passed.");
require(_airdropSettings.airdropFee <= PreciseUnitMath.preciseUnit(), "Fee must be <= 100%.");
airdropSettings[_setToken] = _airdropSettings;
_setToken.initializeModule();
}
/**
* Removes this module from the SetToken, via call by the SetToken. Token's airdrop settings are deleted.
* Airdrops are not absorbed.
*/
function removeModule() external override {
delete airdropSettings[ISetToken(msg.sender)];
}
/**
* Get list of tokens approved to collect airdrops for the SetToken.
*
* @param _setToken Address of SetToken
* @return Array of tokens approved for airdrops
*/
function getAirdrops(ISetToken _setToken) external view returns (address[] memory) {
return _airdrops(_setToken);
}
/**
* Get boolean indicating if token is approved for airdrops.
*
* @param _setToken Address of SetToken
* @return Boolean indicating approval for airdrops
*/
function isAirdropToken(ISetToken _setToken, address _token) public view returns (bool) {
return _airdrops(_setToken).contains(_token);
}
/* ============ Internal Functions ============ */
/**
* Check token approved for airdrops then handle airdropped postion.
*/
function _absorb(ISetToken _setToken, address _token) internal {
require(isAirdropToken(_setToken, _token), "Must be approved token.");
_handleAirdropPosition(_setToken, _token);
}
function _batchAbsorb(ISetToken _setToken, address[] memory _tokens) internal {
for (uint256 i = 0; i < _tokens.length; i++) {
_absorb(_setToken, _tokens[i]);
}
}
/**
* Calculate amount of tokens airdropped since last absorption, then distribute fees and update position.
*
* @param _setToken Address of SetToken
* @param _token Address of airdropped token
*/
function _handleAirdropPosition(ISetToken _setToken, address _token) internal {
uint256 preFeeTokenBalance = ERC20(_token).balanceOf(address(_setToken));
uint256 amountAirdropped = preFeeTokenBalance.sub(_setToken.getDefaultTrackedBalance(_token));
if (amountAirdropped > 0) {
(uint256 managerTake, uint256 protocolTake, uint256 totalFees) = _handleFees(_setToken, _token, amountAirdropped);
uint256 newUnit = _getPostAirdropUnit(_setToken, preFeeTokenBalance, totalFees);
_setToken.editDefaultPosition(_token, newUnit);
emit ComponentAbsorbed(_setToken, _token, amountAirdropped, managerTake, protocolTake);
}
}
/**
* Calculate fee total and distribute between feeRecipient defined on module and the protocol feeRecipient.
*
* @param _setToken Address of SetToken
* @param _component Address of airdropped component
* @param _amountAirdropped Amount of tokens airdropped to the SetToken
* @return Amount of airdropped tokens set aside for manager fees
* @return Amount of airdropped tokens set aside for protocol fees
* @return Total fees paid
*/
function _handleFees(
ISetToken _setToken,
address _component,
uint256 _amountAirdropped
)
internal
returns (uint256, uint256, uint256)
{
uint256 airdropFee = airdropSettings[_setToken].airdropFee;
if (airdropFee > 0) {
uint256 managerTake = _amountAirdropped.preciseMul(airdropFee);
uint256 protocolTake = ModuleBase.getModuleFee(AIRDROP_MODULE_PROTOCOL_FEE_INDEX, managerTake);
uint256 netManagerTake = managerTake.sub(protocolTake);
uint256 totalFees = netManagerTake.add(protocolTake);
_setToken.invokeTransfer(_component, airdropSettings[_setToken].feeRecipient, netManagerTake);
ModuleBase.payProtocolFeeFromSetToken(_setToken, _component, protocolTake);
return (netManagerTake, protocolTake, totalFees);
} else {
return (0, 0, 0);
}
}
/**
* Retrieve new unit, which is the current balance less fees paid divided by total supply
*/
function _getPostAirdropUnit(
ISetToken _setToken,
uint256 _totalComponentBalance,
uint256 _totalFeesPaid
) internal view returns(uint256) {
uint256 totalSupply = _setToken.totalSupply();
return totalSupply.getDefaultPositionUnit(_totalComponentBalance.sub(_totalFeesPaid));
}
/**
* If absorption is confined to the manager, manager must be caller
*/
function _isValidCaller(ISetToken _setToken) internal view returns(bool) {
return airdropSettings[_setToken].anyoneAbsorb || isSetManager(_setToken, msg.sender);
}
function _airdrops(ISetToken _setToken) internal view returns(address[] memory) {
return airdropSettings[_setToken].airdrops;
}
} | * Retrieve new unit, which is the current balance less fees paid divided by total supply/ | function _getPostAirdropUnit(
ISetToken _setToken,
uint256 _totalComponentBalance,
uint256 _totalFeesPaid
) internal view returns(uint256) {
uint256 totalSupply = _setToken.totalSupply();
return totalSupply.getDefaultPositionUnit(_totalComponentBalance.sub(_totalFeesPaid));
}
| 1,804,285 | [
1,
5767,
394,
2836,
16,
1492,
353,
326,
783,
11013,
5242,
1656,
281,
30591,
26057,
635,
2078,
14467,
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,
565,
445,
389,
588,
3349,
37,
6909,
1764,
2802,
12,
203,
3639,
467,
694,
1345,
389,
542,
1345,
16,
203,
3639,
2254,
5034,
389,
4963,
1841,
13937,
16,
203,
3639,
2254,
5034,
389,
4963,
2954,
281,
16507,
350,
203,
203,
565,
262,
2713,
1476,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
2078,
3088,
1283,
273,
389,
542,
1345,
18,
4963,
3088,
1283,
5621,
203,
3639,
327,
2078,
3088,
1283,
18,
588,
1868,
2555,
2802,
24899,
4963,
1841,
13937,
18,
1717,
24899,
4963,
2954,
281,
16507,
350,
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
]
|
./full_match/3/0xD0196FbF234447982417a37FAbD1a5b9086c7cf3/sources/contracts/VotingProd.sol | * @dev Enum for the different step in the voting process/ | event checkVoterInfo(bool present);
| 8,133,110 | [
1,
3572,
364,
326,
3775,
2235,
316,
326,
331,
17128,
1207,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
871,
866,
58,
20005,
966,
12,
6430,
3430,
1769,
7010,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 "./HighStreetPoolBase.sol";
/**
* @title HIGH Core Pool
*
* @notice Core pools represent permanent pools like HIGH or HIGH/ETH Pair pool,
* core pools allow staking for arbitrary periods of time up to 1 year
*
* @dev See HighStreetPoolBase for more details
*
*/
contract HighStreetCorePool is HighStreetPoolBase {
/// @dev Flag indicating pool type, false means "core pool"
bool public constant override isFlashPool = false;
/// @dev Link to deployed vault instance
address public vault;
/// @dev Used to calculate vault rewards
/// @dev This value is different from "reward per token" used in locked pool
/// @dev Note: stakes are different in duration and "weight" reflects that
uint256 public vaultRewardsPerWeight;
/// @dev Pool tokens value available in the pool;
/// pool token examples are HIGH (HIGH core pool) or HIGH/ETH pair (LP core pool)
/// @dev For LP core pool this value doesnt' count for HIGH tokens received as Vault rewards
/// while for HIGH core pool it does count for such tokens as well
uint256 public poolTokenReserve;
/**
* @dev Fired in receiveVaultRewards()
*
* @param _by an address that sent the rewards, always a vault
* @param amount amount of tokens received
*/
event VaultRewardsReceived(address indexed _by, uint256 amount);
/**
* @dev Fired in _processVaultRewards() and dependent functions, like processRewards()
*
* @param _by an address which executed the function
* @param _to an address which received a reward
* @param amount amount of reward received
*/
event VaultRewardsClaimed(address indexed _by, address indexed _to, uint256 amount);
/**
* @dev Fired in setVault()
*
* @param _by an address which executed the function, always a factory owner
*/
event VaultUpdated(address indexed _by, address _fromVal, address _toVal);
/**
* @dev Creates/deploys an instance of the core pool
*
* @param _high HIGH ERC20 Token IlluviumERC20 address
* @param _factory Pool factory HighStreetPoolFactory instance/address
* @param _poolToken token the pool operates on, for example HIGH or HIGH/ETH pair
* @param _initBlock initial block used to calculate the rewards
* @param _weight number representing a weight of the pool, actual weight fraction
* is calculated as that number divided by the total pools weight and doesn't exceed one
*/
constructor(
address _high,
HighStreetPoolFactory _factory,
address _poolToken,
uint256 _initBlock,
uint256 _weight
) HighStreetPoolBase(_high, _factory, _poolToken, _initBlock, _weight) {}
/**
* @notice Calculates current vault rewards value available for address specified
*
* @dev Performs calculations based on current smart contract state only,
* not taking into account any additional time/blocks which might have passed
*
* @param _staker an address to calculate vault rewards value for
* @return pending calculated vault reward value for the given address
*/
function pendingVaultRewards(address _staker) public view returns (uint256 pending) {
User memory user = users[_staker];
return weightToReward(user.totalWeight, vaultRewardsPerWeight) - user.subVaultRewards;
}
/**
* @dev Executed only by the factory owner to Set the vault
*
* @param _vault an address of deployed IlluviumVault instance
*/
function setVault(address _vault) external {
// verify function is executed by the factory owner
require(factory.owner() == msg.sender, "access denied");
// verify input is set
require(_vault != address(0), "zero input");
// emit an event
emit VaultUpdated(msg.sender, vault, _vault);
// update vault address
vault = _vault;
}
/**
* @dev Executed by the vault to transfer vault rewards HIGH from the vault
* into the pool
*
* @dev This function is executed only for HIGH core pools
*
* @param _rewardsAmount amount of HIGH rewards to transfer into the pool
*/
function receiveVaultRewards(uint256 _rewardsAmount) external {
require(msg.sender == vault, "access denied");
// return silently if there is no reward to receive
if (_rewardsAmount == 0) {
return;
}
require(usersLockingWeight > 0, "zero locking weight");
transferHighTokenFrom(msg.sender, address(this), _rewardsAmount);
vaultRewardsPerWeight += rewardToWeight(_rewardsAmount, usersLockingWeight);
// update `poolTokenReserve` only if this is a HIGH Core Pool
if (poolToken == HIGH) {
poolTokenReserve += _rewardsAmount;
}
emit VaultRewardsReceived(msg.sender, _rewardsAmount);
}
/**
* @notice Service function to calculate and pay pending vault and yield rewards to the sender
*
* @dev Internally executes similar function `_processRewards` from the parent smart contract
* to calculate and pay yield rewards; adds vault rewards processing
*
* @dev Can be executed by anyone at any time, but has an effect only when
* executed by deposit holder and when at least one block passes from the
* previous reward processing
* @dev Executed internally when "staking as a pool" (`stakeAsPool`)
* @dev When timing conditions are not met (executed too frequently, or after factory
* end block), function doesn't throw and exits silently
*
* @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant`
*
*/
function processRewards() external override nonReentrant{
_processRewards(msg.sender, true);
User storage user = users[msg.sender];
user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight);
}
/**
* @dev Executed internally by the pool itself (from the parent `HighStreetPoolBase` smart contract)
* as part of yield rewards processing logic (`HighStreetPoolBase._processRewards` function)
*
* @dev Because the reward in all pools should be regarded as a yield staking in HIGH token pool
* thus this function can only be excecuted within HIGH token pool
*
* @param _staker an address which stakes (the yield reward)
* @param _amount amount to be staked (yield reward amount)
*/
function stakeAsPool(address _staker, uint256 _amount) external {
require(factory.poolExists(msg.sender), "access denied");
require(poolToken == HIGH, "not HIGH token pool");
_sync();
User storage user = users[_staker];
if (user.tokenAmount > 0) {
_processRewards(_staker, false);
}
uint256 depositWeight = _amount * YEAR_STAKE_WEIGHT_MULTIPLIER;
Deposit memory newDeposit =
Deposit({
tokenAmount: _amount,
lockedFrom: uint64(now256()),
lockedUntil: uint64(now256() + 365 days),
weight: depositWeight,
isYield: true
});
user.tokenAmount += _amount;
user.rewardAmount += _amount;
user.totalWeight += depositWeight;
user.deposits.push(newDeposit);
usersLockingWeight += depositWeight;
user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight);
user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight);
// update `poolTokenReserve` only if this is a LP Core Pool (stakeAsPool can be executed only for LP pool)
poolTokenReserve += _amount;
}
/**
* @inheritdoc HighStreetPoolBase
*
* @dev Additionally to the parent smart contract, updates vault rewards of the holder,
* and updates (increases) pool token reserve (pool tokens value available in the pool)
*/
function _stake(
address _staker,
uint256 _amount,
uint64 _lockedUntil
) internal override {
super._stake(_staker, _amount, _lockedUntil);
User storage user = users[_staker];
user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight);
poolTokenReserve += _amount;
}
/**
* @inheritdoc HighStreetPoolBase
*
* @dev Additionally to the parent smart contract, updates vault rewards of the holder,
* and updates (decreases) pool token reserve (pool tokens value available in the pool)
*/
function _unstake(
address _staker,
uint256 _depositId,
uint256 _amount
) internal override {
User storage user = users[_staker];
Deposit memory stakeDeposit = user.deposits[_depositId];
require(stakeDeposit.lockedFrom == 0 || now256() > stakeDeposit.lockedUntil, "deposit not yet unlocked");
poolTokenReserve -= _amount;
super._unstake(_staker, _depositId, _amount);
user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight);
}
/**
* @inheritdoc HighStreetPoolBase
*
* @dev Additionally to the parent smart contract, updates vault rewards of the holder,
* and updates (decreases) pool token reserve (pool tokens value available in the pool)
*/
function _emergencyWithdraw(
address _staker
) internal override {
User storage user = users[_staker];
uint256 amount = user.tokenAmount;
poolTokenReserve -= amount;
super._emergencyWithdraw(_staker);
user.subVaultRewards = 0;
}
/**
* @inheritdoc HighStreetPoolBase
*
* @dev Additionally to the parent smart contract, processes vault rewards of the holder,
* and for HIGH pool updates (increases) pool token reserve (pool tokens value available in the pool)
*/
function _processRewards(
address _staker,
bool _withUpdate
) internal override returns (uint256 pendingYield) {
_processVaultRewards(_staker);
pendingYield = super._processRewards(_staker, _withUpdate);
// update `poolTokenReserve` only if this is a HIGH Core Pool
if (poolToken == HIGH) {
poolTokenReserve += pendingYield;
}
}
/**
* @dev Used internally to process vault rewards for the staker
*
* @param _staker address of the user (staker) to process rewards for
*/
function _processVaultRewards(address _staker) private {
User storage user = users[_staker];
uint256 pendingVaultClaim = pendingVaultRewards(_staker);
if (pendingVaultClaim == 0) return;
// read HIGH token balance of the pool via standard ERC20 interface
uint256 highBalance = IERC20(HIGH).balanceOf(address(this));
require(highBalance >= pendingVaultClaim, "contract HIGH balance too low");
// update `poolTokenReserve` only if this is a HIGH Core Pool
if (poolToken == HIGH) {
// protects against rounding errors
poolTokenReserve -= pendingVaultClaim > poolTokenReserve ? poolTokenReserve : pendingVaultClaim;
}
user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight);
// transfer fails if pool HIGH balance is not enough - which is a desired behavior
transferHighToken(_staker, pendingVaultClaim);
emit VaultRewardsClaimed(msg.sender, _staker, pendingVaultClaim);
}
/**
* @dev Executes SafeERC20.safeTransfer on a HIGH token
*
*/
function transferHighToken(address _to, uint256 _value) internal {
// just delegate call to the target
SafeERC20.safeTransfer(IERC20(HIGH), _to, _value);
}
/**
* @dev Executes SafeERC20.safeTransferFrom on a HIGH token
*
*/
function transferHighTokenFrom(
address _from,
address _to,
uint256 _value
) internal {
// just delegate call to the target
SafeERC20.safeTransferFrom(IERC20(HIGH), _from, _to, _value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
/**
* @title High Street Pool
*
* @notice An abstraction representing a pool, see HighStreetPoolBase for details
*
*/
interface IPool {
/**
* @dev Deposit is a key data structure used in staking,
* it represents a unit of stake with its amount, weight and term (time interval)
*/
struct Deposit {
// @dev token amount staked
uint256 tokenAmount;
// @dev stake weight
uint256 weight;
// @dev locking period - from
uint64 lockedFrom;
// @dev locking period - until
uint64 lockedUntil;
// @dev indicates if the stake was created as a yield reward
bool isYield;
}
// for the rest of the functions see Soldoc in HighStreetPoolBase
function HIGH() external view returns (address);
function poolToken() external view returns (address);
function isFlashPool() external view returns (bool);
function weight() external view returns (uint256);
function lastYieldDistribution() external view returns (uint256);
function yieldRewardsPerWeight() external view returns (uint256);
function usersLockingWeight() external view returns (uint256);
function pendingYieldRewards(address _user) external view returns (uint256);
function balanceOf(address _user) external view returns (uint256);
function getDeposit(address _user, uint256 _depositId) external view returns (Deposit memory);
function getDepositsLength(address _user) external view returns (uint256);
function stake(
uint256 _amount,
uint64 _lockedUntil
) external;
function unstake(
uint256 _depositId,
uint256 _amount
) external;
function sync() external;
function processRewards() external;
function setWeight(uint256 _weight) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "./IPool.sol";
interface ICorePool is IPool {
function vaultRewardsPerToken() external view returns (uint256);
function poolTokenReserve() external view returns (uint256);
function stakeAsPool(address _staker, uint256 _amount) external;
function receiveVaultRewards(uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IPool.sol";
/**
* @title HighStreet Pool Factory
*
* @notice HIGH Pool Factory manages HighStreet Yield farming pools, provides a single
* public interface to access the pools, provides an interface for the pools
* to mint yield rewards, access pool-related info, update weights, etc.
*
* @notice The factory is authorized (via its owner) to register new pools, change weights
* of the existing pools, removing the pools (by changing their weights to zero)
*
* @dev The factory requires ROLE_TOKEN_CREATOR permission on the HIGH token to mint yield
* (see `mintYieldTo` function)
*
*/
contract HighStreetPoolFactory is Ownable {
/**
* @dev Smart contract unique identifier, a random number
* @dev Should be regenerated each time smart contact source code is changed
* and changes smart contract itself is to be redeployed
* @dev Generated using https://www.random.org/bytes/
*/
uint256 public constant FACTORY_UID = 0x484a992416a6637667452c709058dccce100b22b278536f5a6d25a14b6a1acdb;
/// @dev Link to HIGH STREET ERC20 Token instance
address public immutable HIGH;
/// @dev Auxiliary data structure used only in getPoolData() view function
struct PoolData {
// @dev pool token address (like HIGH)
address poolToken;
// @dev pool address (like deployed core pool instance)
address poolAddress;
// @dev pool weight (200 for HIGH pools, 800 for HIGH/ETH pools - set during deployment)
uint256 weight;
// @dev flash pool flag
bool isFlashPool;
}
/**
* @dev HIGH/block determines yield farming reward base
* used by the yield pools controlled by the factory
*/
uint256 public highPerBlock;
/**
* @dev The yield is distributed proportionally to pool weights;
* total weight is here to help in determining the proportion
*/
uint256 public totalWeight;
/**
* @dev HIGH/block decreases by 3% every blocks/update (set to 91252 blocks during deployment);
* an update is triggered by executing `updateHighPerBlock` public function
*/
uint256 public immutable blocksPerUpdate;
/**
* @dev End block is the last block when HIGH/block can be decreased;
* it is implied that yield farming stops after that block
*/
uint256 public endBlock;
/**
* @dev Each time the HIGH/block ratio gets updated, the block number
* when the operation has occurred gets recorded into `lastRatioUpdate`
* @dev This block number is then used to check if blocks/update `blocksPerUpdate`
* has passed when decreasing yield reward by 3%
*/
uint256 public lastRatioUpdate;
/// @dev Maps pool token address (like HIGH) -> pool address (like core pool instance)
mapping(address => address) public pools;
/// @dev Keeps track of registered pool addresses, maps pool address -> exists flag
mapping(address => bool) public poolExists;
/**
* @dev Fired in createPool() and registerPool()
*
* @param _by an address which executed an action
* @param poolToken pool token address (like HIGH)
* @param poolAddress deployed pool instance address
* @param weight pool weight
* @param isFlashPool flag indicating if pool is a flash pool
*/
event PoolRegistered(
address indexed _by,
address indexed poolToken,
address indexed poolAddress,
uint256 weight,
bool isFlashPool
);
/**
* @dev Fired in changePoolWeight()
*
* @param _by an address which executed an action
* @param poolAddress deployed pool instance address
* @param weight new pool weight
*/
event WeightUpdated(address indexed _by, address indexed poolAddress, uint256 weight);
/**
* @dev Fired in updateHighPerBlock()
*
* @param _by an address which executed an action
* @param newHighPerBlock new HIGH/block value
*/
event HighRatioUpdated(address indexed _by, uint256 newHighPerBlock);
/**
* @dev Fired in mintYieldTo()
*
* @param _to an address to mint tokens to
* @param amount amount of HIGH tokens to mint
*/
event MintYield(address indexed _to, uint256 amount);
/**
* @dev Creates/deploys a factory instance
*
* @param _high HIGH ERC20 token address
* @param _highPerBlock initial HIGH/block value for rewards
* @param _blocksPerUpdate how frequently the rewards gets updated (decreased by 3%), blocks
* @param _initBlock block number to measure _blocksPerUpdate from
* @param _endBlock block number when farming stops and rewards cannot be updated anymore
*/
constructor(
address _high,
uint256 _highPerBlock,
uint256 _blocksPerUpdate,
uint256 _initBlock,
uint256 _endBlock
) {
// verify the inputs are set
require(_high != address(0) , "HIGH is invalid");
require(_highPerBlock > 0, "HIGH/block not set");
require(_blocksPerUpdate > 0, "blocks/update not set");
require(_initBlock > 0, "init block not set");
require(_endBlock > _initBlock, "invalid end block: must be greater than init block");
// save the inputs into internal state variables
HIGH = _high;
highPerBlock = _highPerBlock;
blocksPerUpdate = _blocksPerUpdate;
lastRatioUpdate = _initBlock;
endBlock = _endBlock;
}
/**
* @notice Given a pool token retrieves corresponding pool address
*
* @dev A shortcut for `pools` mapping
*
* @param poolToken pool token address (like HIGH) to query pool address for
* @return pool address for the token specified
*/
function getPoolAddress(address poolToken) external view returns (address) {
// read the mapping and return
return pools[poolToken];
}
/**
* @notice Reads pool information for the pool defined by its pool token address,
* designed to simplify integration with the front ends
*
* @param _poolToken pool token address to query pool information for
* @return pool information packed in a PoolData struct
*/
function getPoolData(address _poolToken) external view returns (PoolData memory) {
// get the pool address from the mapping
address poolAddr = pools[_poolToken];
// throw if there is no pool registered for the token specified
require(poolAddr != address(0), "pool not found");
// read pool information from the pool smart contract
// via the pool interface (IPool)
bool isFlashPool = IPool(poolAddr).isFlashPool();
uint256 weight = IPool(poolAddr).weight();
// create the in-memory structure and return it
return PoolData({ poolToken: _poolToken, poolAddress: poolAddr, weight: weight, isFlashPool: isFlashPool });
}
/**
* @dev Verifies if `blocksPerUpdate` has passed since last HIGH/block
* ratio update and if HIGH/block reward can be decreased by 3%
*
* @return true if enough time has passed and `updateHighPerBlock` can be executed
*/
function shouldUpdateRatio() public view returns (bool) {
// if yield farming period has ended
if (blockNumber() > endBlock) {
// HIGH/block reward cannot be updated anymore
return false;
}
// check if blocks/update (91252 blocks) have passed since last update
return blockNumber() >= lastRatioUpdate + blocksPerUpdate;
}
/**
* @dev Registers an already deployed pool instance within the factory
*
* @dev Can be executed by the pool factory owner only
*
* @param poolAddr address of the already deployed pool instance
*/
function registerPool(address poolAddr) external onlyOwner {
// read pool information from the pool smart contract
// via the pool interface (IPool)
address poolToken = IPool(poolAddr).poolToken();
bool isFlashPool = IPool(poolAddr).isFlashPool();
uint256 weight = IPool(poolAddr).weight();
// ensure that the pool is not already registered within the factory
require(pools[poolToken] == address(0), "this pool is already registered");
// create pool structure, register it within the factory
pools[poolToken] = poolAddr;
poolExists[poolAddr] = true;
// update total pool weight of the factory
totalWeight += weight;
// emit an event
emit PoolRegistered(msg.sender, poolToken, poolAddr, weight, isFlashPool);
}
/**
* @notice Decreases HIGH/block reward by 3%, can be executed
* no more than once per `blocksPerUpdate` blocks
*/
function updateHighPerBlock() external {
// checks if ratio can be updated i.e. if blocks/update (91252 blocks) have passed
require(shouldUpdateRatio(), "too frequent");
// decreases HIGH/block reward by 3%
highPerBlock = (highPerBlock * 97) / 100;
// set current block as the last ratio update block
lastRatioUpdate = blockNumber();
// emit an event
emit HighRatioUpdated(msg.sender, highPerBlock);
}
/**
* @dev Mints HIGH tokens; executed by HIGH Pool only
*
* @dev Requires factory to have ROLE_TOKEN_CREATOR permission
* on the HIGH ERC20 token instance
*
* @param _to an address to mint tokens to
* @param _amount amount of HIGH tokens to mint
*/
function mintYieldTo(address _to, uint256 _amount) external {
// verify that sender is a pool registered withing the factory
require(poolExists[msg.sender], "access denied");
// transfer HIGH tokens as required
transferHighToken(_to, _amount);
emit MintYield(_to, _amount);
}
/**
* @dev Changes the weight of the pool;
* executed by the pool itself or by the factory owner
*
* @param poolAddr address of the pool to change weight for
* @param weight new weight value to set to
*/
function changePoolWeight(address poolAddr, uint256 weight) external {
// verify function is executed either by factory owner or by the pool itself
require(msg.sender == owner() || poolExists[msg.sender]);
// recalculate total weight
totalWeight = totalWeight + weight - IPool(poolAddr).weight();
// set the new pool weight
IPool(poolAddr).setWeight(weight);
// emit an event
emit WeightUpdated(msg.sender, poolAddr, weight);
}
/**
* @dev Testing time-dependent functionality is difficult and the best way of
* doing it is to override block number in helper test smart contracts
*
* @return `block.number` in mainnet, custom values in testnets (if overridden)
*/
function blockNumber() public view virtual returns (uint256) {
// return current block number
return block.number;
}
/**
* @dev Executes SafeERC20.safeTransfer on a HIGH token
*
*/
function transferHighToken(address _to, uint256 _value) internal {
// just delegate call to the target
SafeERC20.safeTransfer(IERC20(HIGH), _to, _value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IPool.sol";
import "./interfaces/ICorePool.sol";
import "./HighStreetPoolFactory.sol";
/**
* @title HighStreet Pool Base
*
* @notice An abstract contract containing common logic for a core pool (permanent pool like HIGH/ETH or HIGH pool)
*
* @dev Deployment and initialization.
* Any pool deployed must be bound to the deployed pool factory (HighStreetPoolFactory)
* Additionally, 3 token instance addresses must be defined on deployment:
* - HIGH token address
* - pool token address, it can be HIGH token address, HIGH/ETH pair address, and others
*
* @dev Pool weight defines the fraction of the yield current pool receives among the other pools,
* pool factory is responsible for the weight synchronization between the pools.
* @dev The weight is logically 20% for HIGH pool and 80% for HIGH/ETH pool.
* Since Solidity doesn't support fractions the weight is defined by the division of
* pool weight by total pools weight (sum of all registered pools within the factory)
* @dev For HIGH Pool we use 200 as weight and for HIGH/ETH pool - 800.
*
*/
abstract contract HighStreetPoolBase is IPool, ReentrancyGuard {
/// @dev Data structure representing token holder using a pool
struct User {
// @dev Total staked amount
uint256 tokenAmount;
// @dev Total reward amount
uint256 rewardAmount;
// @dev Total weight
uint256 totalWeight;
// @dev Auxiliary variable for yield calculation
uint256 subYieldRewards;
// @dev Auxiliary variable for vault rewards calculation
uint256 subVaultRewards;
// @dev An array of holder's deposits
Deposit[] deposits;
}
/// @dev Link to HIGH STREET ERC20 Token instance
address public immutable override HIGH;
/// @dev Token holder storage, maps token holder address to their data record
mapping(address => User) public users;
/// @dev Link to the pool factory HighStreetPoolFactory instance
HighStreetPoolFactory public immutable factory;
/// @dev Link to the pool token instance, for example HIGH or HIGH/ETH pair
address public immutable override poolToken;
/// @dev Pool weight, 200 for HIGH pool or 800 for HIGH/ETH
uint256 public override weight;
/// @dev Block number of the last yield distribution event
uint256 public override lastYieldDistribution;
/// @dev Used to calculate yield rewards
/// @dev This value is different from "reward per token" used in locked pool
/// @dev Note: stakes are different in duration and "weight" reflects that
uint256 public override yieldRewardsPerWeight;
/// @dev Used to calculate yield rewards, keeps track of the tokens weight locked in staking
uint256 public override usersLockingWeight;
/**
* @dev Stake weight is proportional to deposit amount and time locked, precisely
* "deposit amount wei multiplied by (fraction of the year locked plus one)"
* @dev To avoid significant precision loss due to multiplication by "fraction of the year" [0, 1],
* weight is stored multiplied by 1e24 constant, as an integer
* @dev Corner case 1: if time locked is zero, weight is deposit amount multiplied by 1e24
* @dev Corner case 2: if time locked is one year, fraction of the year locked is one, and
* weight is a deposit amount multiplied by 2 * 1e24
*/
uint256 internal constant WEIGHT_MULTIPLIER = 1e24;
/**
* @dev When we know beforehand that staking is done for a year, and fraction of the year locked is one,
* we use simplified calculation and use the following constant instead previos one
*/
uint256 internal constant YEAR_STAKE_WEIGHT_MULTIPLIER = 2 * WEIGHT_MULTIPLIER;
/**
* @dev Rewards per weight are stored multiplied by 1e48, as integers.
*/
uint256 internal constant REWARD_PER_WEIGHT_MULTIPLIER = 1e48;
/**
* @dev We want to get deposits batched but not one by one, thus here is define the size of each batch.
*/
uint256 internal constant DEPOSIT_BATCH_SIZE = 20;
/**
* @dev Fired in _stake() and stake()
*
* @param _by an address which performed an operation, usually token holder
* @param _from token holder address, the tokens will be returned to that address
* @param amount amount of tokens staked
*/
event Staked(address indexed _by, address indexed _from, uint256 amount);
/**
* @dev Fired in _updateStakeLock() and updateStakeLock()
*
* @param _by an address which performed an operation
* @param depositId updated deposit ID
* @param lockedFrom deposit locked from value
* @param lockedUntil updated deposit locked until value
*/
event StakeLockUpdated(address indexed _by, uint256 depositId, uint64 lockedFrom, uint64 lockedUntil);
/**
* @dev Fired in _unstake() and unstake()
*
* @param _by an address which performed an operation, usually token holder
* @param _to an address which received the unstaked tokens, usually token holder
* @param amount amount of tokens unstaked
*/
event Unstaked(address indexed _by, address indexed _to, uint256 amount);
/**
* @dev Fired in _sync(), sync() and dependent functions (stake, unstake, etc.)
*
* @param _by an address which performed an operation
* @param yieldRewardsPerWeight updated yield rewards per weight value
* @param lastYieldDistribution usually, current block number
*/
event Synchronized(address indexed _by, uint256 yieldRewardsPerWeight, uint256 lastYieldDistribution);
/**
* @dev Fired in _processRewards(), processRewards() and dependent functions (stake, unstake, etc.)
*
* @param _by an address which performed an operation
* @param _to an address which claimed the yield reward
* @param amount amount of yield paid
*/
event YieldClaimed(address indexed _by, address indexed _to, uint256 amount);
/**
* @dev Fired in setWeight()
*
* @param _fromVal old pool weight value
* @param _toVal new pool weight value
*/
event PoolWeightUpdated(uint256 _fromVal, uint256 _toVal);
/**
* @dev Fired in _emergencyWithdraw()
*
* @param _by an address which performed an operation, usually token holder
* @param amount amount of tokens withdraw
*/
event EmergencyWithdraw(address indexed _by, uint256 amount);
/**
* @dev Overridden in sub-contracts to construct the pool
*
* @param _high HIGH ERC20 Token IlluviumERC20 address
* @param _factory Pool factory HighStreetPoolFactory instance/address
* @param _poolToken token the pool operates on, for example HIGH or HIGH/ETH pair
* @param _initBlock initial block used to calculate the rewards
* note: _initBlock can be set to the future effectively meaning _sync() calls will do nothing
* @param _weight number representing a weight of the pool, actual weight fraction
* is calculated as that number divided by the total pools weight and doesn't exceed one
*/
constructor(
address _high,
HighStreetPoolFactory _factory,
address _poolToken,
uint256 _initBlock,
uint256 _weight
) {
// verify the inputs are set
require(_high != address(0), "high token address not set");
require(address(_factory) != address(0), "HIGH Pool fct address not set");
require(_poolToken != address(0), "pool token address not set");
require(_initBlock >= blockNumber(), "Invalid init block");
require(_weight > 0, "pool weight not set");
// verify HighStreetPoolFactory instance supplied
require(
_factory.FACTORY_UID() == 0x484a992416a6637667452c709058dccce100b22b278536f5a6d25a14b6a1acdb,
"unexpected FACTORY_UID"
);
// save the inputs into internal state variables
HIGH = _high;
factory = _factory;
poolToken = _poolToken;
weight = _weight;
// init the dependent internal state variables
lastYieldDistribution = _initBlock;
}
/**
* @notice Calculates current yield rewards value available for address specified
*
* @param _staker an address to calculate yield rewards value for
* @return calculated yield reward value for the given address
*/
function pendingYieldRewards(address _staker) external view override returns (uint256) {
// `newYieldRewardsPerWeight` will store stored or recalculated value for `yieldRewardsPerWeight`
uint256 newYieldRewardsPerWeight;
// if smart contract state was not updated recently, `yieldRewardsPerWeight` value
// is outdated and we need to recalculate it in order to calculate pending rewards correctly
if (blockNumber() > lastYieldDistribution && usersLockingWeight != 0) {
uint256 endBlock = factory.endBlock();
uint256 multiplier =
blockNumber() > endBlock ? endBlock - lastYieldDistribution : blockNumber() - lastYieldDistribution;
uint256 highRewards = (multiplier * weight * factory.highPerBlock()) / factory.totalWeight();
// recalculated value for `yieldRewardsPerWeight`
newYieldRewardsPerWeight = rewardToWeight(highRewards, usersLockingWeight) + yieldRewardsPerWeight;
} else {
// if smart contract state is up to date, we don't recalculate
newYieldRewardsPerWeight = yieldRewardsPerWeight;
}
// based on the rewards per weight value, calculate pending rewards;
User memory user = users[_staker];
uint256 pending = weightToReward(user.totalWeight, newYieldRewardsPerWeight) - user.subYieldRewards;
return pending;
}
/**
* @notice Returns total staked token balance for the given address
*
* @param _user an address to query balance for
* @return total staked token balance
*/
function balanceOf(address _user) external view override returns (uint256) {
// read specified user token amount and return
return users[_user].tokenAmount;
}
/**
* @notice Returns information on the given deposit for the given address
*
* @dev See getDepositsLength
*
* @param _user an address to query deposit for
* @param _depositId zero-indexed deposit ID for the address specified
* @return deposit info as Deposit structure
*/
function getDeposit(address _user, uint256 _depositId) external view override returns (Deposit memory) {
// read deposit at specified index and return
return users[_user].deposits[_depositId];
}
/**
* @notice Returns a batch of deposits on the given pageId for the given address
*
* @dev we separate deposits into serveral of pages, and each page have DEPOSIT_BATCH_SIZE of item.
*
* @param _user an address to query deposit for
* @param _pageId zero-indexed page ID for the address specified
* @return deposits info as Deposit structure
*/
function getDepositsBatch(address _user, uint256 _pageId) external view returns (Deposit[] memory) {
uint256 pageStart = _pageId * DEPOSIT_BATCH_SIZE;
uint256 pageEnd = (_pageId + 1) * DEPOSIT_BATCH_SIZE;
uint256 pageLength = DEPOSIT_BATCH_SIZE;
if(pageEnd > (users[_user].deposits.length - pageStart)) {
pageEnd = users[_user].deposits.length;
pageLength = pageEnd - pageStart;
}
Deposit[] memory deposits = new Deposit[](pageLength);
for(uint256 i = pageStart; i < pageEnd; i++) {
deposits[i-pageStart] = users[_user].deposits[i];
}
return deposits;
}
/**
* @notice Returns number of pages for the given address. Allows iteration over deposits.
*
* @dev See getDepositsBatch
*
* @param _user an address to query deposit length for
* @return number of pages for the given address
*/
function getDepositsBatchLength(address _user) external view returns (uint256) {
if(users[_user].deposits.length == 0) {
return 0;
}
return 1 + (users[_user].deposits.length - 1) / DEPOSIT_BATCH_SIZE;
}
/**
* @notice Returns number of deposits for the given address. Allows iteration over deposits.
*
* @dev See getDeposit
*
* @param _user an address to query deposit length for
* @return number of deposits for the given address
*/
function getDepositsLength(address _user) external view override returns (uint256) {
// read deposits array length and return
return users[_user].deposits.length;
}
/**
* @notice Stakes specified amount of tokens for the specified amount of time,
* and pays pending yield rewards if any
*
* @dev Requires amount to stake to be greater than zero
*
* @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant`
*
* @param _amount amount of tokens to stake
* @param _lockUntil stake period as unix timestamp; zero means no locking
*/
function stake (
uint256 _amount,
uint64 _lockUntil
) external override nonReentrant {
// delegate call to an internal function
_stake(msg.sender, _amount, _lockUntil);
}
/**
* @notice Unstakes specified amount of tokens, and pays pending yield rewards if any
*
* @dev Requires amount to unstake to be greater than zero
*
* @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant`
*
* @param _depositId deposit ID to unstake from, zero-indexed
* @param _amount amount of tokens to unstake
*/
function unstake(
uint256 _depositId,
uint256 _amount
) external override nonReentrant {
// delegate call to an internal function
_unstake(msg.sender, _depositId, _amount);
}
/**
* @notice Extends locking period for a given deposit
*
* @dev Requires new lockedUntil value to be:
* higher than the current one, and
* in the future, but
* no more than 1 year in the future
*
* @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant`
*
* @param depositId updated deposit ID
* @param lockedUntil updated deposit locked until value
*/
function updateStakeLock(
uint256 depositId,
uint64 lockedUntil
) external nonReentrant {
require(users[msg.sender].deposits[depositId].tokenAmount > 0, "Invalid amount");
// sync and call processRewards
_sync();
_processRewards(msg.sender, false);
// delegate call to an internal function
_updateStakeLock(msg.sender, depositId, lockedUntil);
}
/**
* @notice Service function to synchronize pool state with current time
*
* @dev Can be executed by anyone at any time, but has an effect only when
* at least one block passes between synchronizations
* @dev Executed internally when staking, unstaking, processing rewards in order
* for calculations to be correct and to reflect state progress of the contract
* @dev When timing conditions are not met (executed too frequently, or after factory
* end block), function doesn't throw and exits silently
*/
function sync() external override {
// delegate call to an internal function
_sync();
}
/**
* @notice Service function to calculate and pay pending yield rewards to the sender
*
* @dev Can be executed by anyone at any time, but has an effect only when
* executed by deposit holder and when at least one block passes from the
* previous reward processing
* @dev Executed internally when staking and unstaking, executes sync() under the hood
* before making further calculations and payouts
* @dev When timing conditions are not met (executed too frequently, or after factory
* end block), function doesn't throw and exits silently
*
* @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant`
*
*/
function processRewards() external virtual override nonReentrant {
// delegate call to an internal function
_processRewards(msg.sender, true);
}
/**
* @dev Executed by the factory to modify pool weight; the factory is expected
* to keep track of the total pools weight when updating
*
* @dev Set weight to zero to disable the pool
*
* @param _weight new weight to set for the pool
*/
function setWeight(uint256 _weight) external override {
// verify function is executed by the factory
require(msg.sender == address(factory), "access denied");
// emit an event logging old and new weight values
emit PoolWeightUpdated(weight, _weight);
// set the new weight value
weight = _weight;
}
/**
* @dev Similar to public pendingYieldRewards, but performs calculations based on
* current smart contract state only, not taking into account any additional
* time/blocks which might have passed
*
* @param _staker an address to calculate yield rewards value for
* @return pending calculated yield reward value for the given address
*/
function _pendingYieldRewards(address _staker) internal view returns (uint256 pending) {
// read user data structure into memory
User memory user = users[_staker];
// and perform the calculation using the values read
return weightToReward(user.totalWeight, yieldRewardsPerWeight) - user.subYieldRewards;
}
/**
* @dev Used internally, mostly by children implementations, see stake()
*
* @param _staker an address which stakes tokens and which will receive them back
* @param _amount amount of tokens to stake
* @param _lockUntil stake period as unix timestamp; zero means no locking
*/
function _stake(
address _staker,
uint256 _amount,
uint64 _lockUntil
) internal virtual {
// validate the inputs
require(_amount > 0, "zero amount");
require(
_lockUntil == 0 || (_lockUntil > now256() && _lockUntil - now256() <= 365 days),
"invalid lock interval"
);
// update smart contract state
_sync();
// get a link to user data struct, we will write to it later
User storage user = users[_staker];
// process current pending rewards if any
if (user.tokenAmount > 0) {
_processRewards(_staker, false);
}
// in most of the cases added amount `addedAmount` is simply `_amount`
// however for deflationary tokens this can be different
// read the current balance
uint256 previousBalance = IERC20(poolToken).balanceOf(address(this));
// transfer `_amount`; note: some tokens may get burnt here
transferPoolTokenFrom(msg.sender, address(this), _amount);
// read new balance, usually this is just the difference `previousBalance - _amount`
uint256 newBalance = IERC20(poolToken).balanceOf(address(this));
// calculate real amount taking into account deflation
uint256 addedAmount = newBalance - previousBalance;
// set the `lockFrom` and `lockUntil` taking into account that
// zero value for `_lockUntil` means "no locking" and leads to zero values
// for both `lockFrom` and `lockUntil`
uint64 lockFrom = _lockUntil > 0 ? uint64(now256()) : 0;
uint64 lockUntil = _lockUntil;
// stake weight formula rewards for locking
uint256 stakeWeight =
(((lockUntil - lockFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * addedAmount;
// makes sure stakeWeight is valid
require(stakeWeight > 0, "invalid stakeWeight");
// create and save the deposit (append it to deposits array)
Deposit memory deposit =
Deposit({
tokenAmount: addedAmount,
weight: stakeWeight,
lockedFrom: lockFrom,
lockedUntil: lockUntil,
isYield: false
});
// deposit ID is an index of the deposit in `deposits` array
user.deposits.push(deposit);
// update user record
user.tokenAmount += addedAmount;
user.totalWeight += stakeWeight;
user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight);
// update global variable
usersLockingWeight += stakeWeight;
// emit an event
emit Staked(msg.sender, _staker, addedAmount);
}
/**
* @dev Used internally, mostly by children implementations, see unstake()
*
* @param _staker an address which unstakes tokens (which previously staked them)
* @param _depositId deposit ID to unstake from, zero-indexed
* @param _amount amount of tokens to unstake
*/
function _unstake(
address _staker,
uint256 _depositId,
uint256 _amount
) internal virtual {
// verify an amount is set
require(_amount > 0, "zero amount");
// get a link to user data struct, we will write to it later
User storage user = users[_staker];
// get a link to the corresponding deposit, we may write to it later
Deposit storage stakeDeposit = user.deposits[_depositId];
// deposit structure may get deleted, so we save isYield flag to be able to use it
bool isYield = stakeDeposit.isYield;
// verify available balance
// if staker address ot deposit doesn't exist this check will fail as well
require(stakeDeposit.tokenAmount >= _amount, "amount exceeds stake");
// update smart contract state
_sync();
// and process current pending rewards if any
_processRewards(_staker, false);
// recalculate deposit weight
uint256 previousWeight = stakeDeposit.weight;
uint256 newWeight =
(((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) /
365 days +
WEIGHT_MULTIPLIER) * (stakeDeposit.tokenAmount - _amount);
// update the deposit, or delete it if its depleted
if (stakeDeposit.tokenAmount - _amount == 0) {
delete user.deposits[_depositId];
} else {
stakeDeposit.tokenAmount -= _amount;
stakeDeposit.weight = newWeight;
}
// update user record
user.tokenAmount -= _amount;
user.totalWeight = user.totalWeight - previousWeight + newWeight;
user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight);
// update global variable
usersLockingWeight = usersLockingWeight - previousWeight + newWeight;
// if the deposit was created by the pool itself as a yield reward
if (isYield) {
user.rewardAmount -= _amount;
// mint the yield via the factory
factory.mintYieldTo(msg.sender, _amount);
} else {
// otherwise just return tokens back to holder
transferPoolToken(msg.sender, _amount);
}
// emit an event
emit Unstaked(msg.sender, _staker, _amount);
}
/**
* @notice Emergency withdraw specified amount of tokens
*
*
* @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant`
*
*/
function emergencyWithdraw() external nonReentrant {
require(factory.totalWeight() == 0, "totalWeight != 0");
// delegate call to an internal function
_emergencyWithdraw(msg.sender);
}
/**
* @dev Used internally, mostly by children implementations, see emergencyWithdraw()
*
* @param _staker an address which unstakes tokens (which previously staked them)
*/
function _emergencyWithdraw(
address _staker
) internal virtual {
// get a link to user data struct, we will write to it later
User storage user = users[_staker];
uint256 totalWeight = user.totalWeight ;
uint256 amount = user.tokenAmount;
uint256 reward = user.rewardAmount;
// update user record
user.tokenAmount = 0;
user.rewardAmount = 0;
user.totalWeight = 0;
user.subYieldRewards = 0;
// delete entire array directly
delete user.deposits;
// update global variable
usersLockingWeight = usersLockingWeight - totalWeight;
// just return tokens back to holder
transferPoolToken(msg.sender, amount - reward);
// mint the yield via the factory
factory.mintYieldTo(msg.sender, reward);
emit EmergencyWithdraw(msg.sender, amount);
}
/**
* @dev Used internally, mostly by children implementations, see sync()
*
* @dev Updates smart contract state (`yieldRewardsPerWeight`, `lastYieldDistribution`),
* updates factory state via `updatehighPerBlock`
*/
function _sync() internal virtual {
// update HIGH per block value in factory if required
if (factory.shouldUpdateRatio()) {
factory.updateHighPerBlock();
}
// check bound conditions and if these are not met -
// exit silently, without emitting an event
uint256 endBlock = factory.endBlock();
if (lastYieldDistribution >= endBlock) {
return;
}
if (blockNumber() <= lastYieldDistribution) {
return;
}
// if locking weight is zero - update only `lastYieldDistribution` and exit
if (usersLockingWeight == 0) {
lastYieldDistribution = blockNumber();
return;
}
// to calculate the reward we need to know how many blocks passed, and reward per block
uint256 currentBlock = blockNumber() > endBlock ? endBlock : blockNumber();
uint256 blocksPassed = currentBlock - lastYieldDistribution;
uint256 highPerBlock = factory.highPerBlock();
// calculate the reward
uint256 highReward = (blocksPassed * highPerBlock * weight) / factory.totalWeight();
// update rewards per weight and `lastYieldDistribution`
yieldRewardsPerWeight += rewardToWeight(highReward, usersLockingWeight);
lastYieldDistribution = currentBlock;
// emit an event
emit Synchronized(msg.sender, yieldRewardsPerWeight, lastYieldDistribution);
}
/**
* @dev Used internally, mostly by children implementations, see processRewards()
*
* @param _staker an address which receives the reward (which has staked some tokens earlier)
* @param _withUpdate flag allowing to disable synchronization (see sync()) if set to false
* @return pendingYield the rewards calculated and optionally re-staked
*/
function _processRewards(
address _staker,
bool _withUpdate
) internal virtual returns (uint256 pendingYield) {
// update smart contract state if required
if (_withUpdate) {
_sync();
}
// calculate pending yield rewards, this value will be returned
pendingYield = _pendingYieldRewards(_staker);
// if pending yield is zero - just return silently
if (pendingYield == 0) return 0;
// get link to a user data structure, we will write into it later
User storage user = users[_staker];
if (poolToken == HIGH) {
// calculate pending yield weight,
// 2e6 is the bonus weight when staking for 1 year
uint256 depositWeight = pendingYield * YEAR_STAKE_WEIGHT_MULTIPLIER;
// if the pool is HIGH Pool - create new HIGH deposit
// and save it - push it into deposits array
Deposit memory newDeposit =
Deposit({
tokenAmount: pendingYield,
lockedFrom: uint64(now256()),
lockedUntil: uint64(now256() + 365 days), // staking yield for 1 year
weight: depositWeight,
isYield: true
});
user.deposits.push(newDeposit);
// update user record
user.tokenAmount += pendingYield;
user.rewardAmount += pendingYield;
user.totalWeight += depositWeight;
// update global variable
usersLockingWeight += depositWeight;
} else {
// for other pools - stake as pool
address highPool = factory.getPoolAddress(HIGH);
require(highPool != address(0),"invalid high pool address");
ICorePool(highPool).stakeAsPool(_staker, pendingYield);
}
// update users's record for `subYieldRewards` if requested
if (_withUpdate) {
user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight);
}
// emit an event
emit YieldClaimed(msg.sender, _staker, pendingYield);
}
/**
* @dev See updateStakeLock()
*
* @param _staker an address to update stake lock
* @param _depositId updated deposit ID
* @param _lockedUntil updated deposit locked until value
*/
function _updateStakeLock(
address _staker,
uint256 _depositId,
uint64 _lockedUntil
) internal {
// validate the input time
require(_lockedUntil > now256(), "lock should be in the future");
// get a link to user data struct, we will write to it later
User storage user = users[_staker];
// get a link to the corresponding deposit, we may write to it later
Deposit storage stakeDeposit = user.deposits[_depositId];
// validate the input against deposit structure
require(_lockedUntil > stakeDeposit.lockedUntil, "invalid new lock");
// verify locked from and locked until values
if (stakeDeposit.lockedFrom == 0) {
require(_lockedUntil - now256() <= 365 days, "max lock period is 365 days");
stakeDeposit.lockedFrom = uint64(now256());
} else {
require(_lockedUntil - stakeDeposit.lockedFrom <= 365 days, "max lock period is 365 days");
}
// update locked until value, calculate new weight
stakeDeposit.lockedUntil = _lockedUntil;
uint256 newWeight =
(((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) /
365 days +
WEIGHT_MULTIPLIER) * stakeDeposit.tokenAmount;
// save previous weight
uint256 previousWeight = stakeDeposit.weight;
// update weight
stakeDeposit.weight = newWeight;
// update user total weight and global locking weight
user.totalWeight = user.totalWeight - previousWeight + newWeight;
usersLockingWeight = usersLockingWeight - previousWeight + newWeight;
// emit an event
emit StakeLockUpdated(_staker, _depositId, stakeDeposit.lockedFrom, _lockedUntil);
}
/**
* @dev Converts stake weight (not to be mixed with the pool weight) to
* HIGH reward value, applying the 10^48 division on weight
*
* @param _weight stake weight
* @param rewardPerWeight HIGH reward per weight
* @return reward value normalized to 10^48
*/
function weightToReward(uint256 _weight, uint256 rewardPerWeight) public pure returns (uint256) {
// apply the formula and return
return (_weight * rewardPerWeight) / REWARD_PER_WEIGHT_MULTIPLIER;
}
/**
* @dev Converts reward HIGH value to stake weight (not to be mixed with the pool weight),
* applying the 10^12 multiplication on the reward
* - OR -
* @dev Converts reward HIGH value to reward/weight if stake weight is supplied as second
* function parameter instead of reward/weight
*
* @param reward yield reward
* @param rewardPerWeight reward/weight (or stake weight)
* @return stake weight (or reward/weight)
*/
function rewardToWeight(uint256 reward, uint256 rewardPerWeight) public pure returns (uint256) {
// apply the reverse formula and return
return (reward * REWARD_PER_WEIGHT_MULTIPLIER) / rewardPerWeight;
}
/**
* @dev Testing time-dependent functionality is difficult and the best way of
* doing it is to override block number in helper test smart contracts
*
* @return `block.number` in mainnet, custom values in testnets (if overridden)
*/
function blockNumber() public view virtual returns (uint256) {
// return current block number
return block.number;
}
/**
* @dev Testing time-dependent functionality is difficult and the best way of
* doing it is to override time in helper test smart contracts
*
* @return `block.timestamp` in mainnet, custom values in testnets (if overridden)
*/
function now256() public view virtual returns (uint256) {
// return current block timestamp
return block.timestamp;
}
/**
* @dev Executes SafeERC20.safeTransfer on a pool token
*
*/
function transferPoolToken(address _to, uint256 _value) internal {
SafeERC20.safeTransfer(IERC20(poolToken), _to, _value);
}
/**
* @dev Executes SafeERC20.safeTransferFrom on a pool token
*
*/
function transferPoolTokenFrom(
address _from,
address _to,
uint256 _value
) internal {
SafeERC20.safeTransferFrom(IERC20(poolToken), _from, _to, _value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../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 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;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../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);
}
} | * @inheritdoc HighStreetPoolBase @dev Additionally to the parent smart contract, updates vault rewards of the holder, and updates (decreases) pool token reserve (pool tokens value available in the pool)/ | function _emergencyWithdraw(
address _staker
) internal override {
User storage user = users[_staker];
uint256 amount = user.tokenAmount;
poolTokenReserve -= amount;
super._emergencyWithdraw(_staker);
user.subVaultRewards = 0;
}
| 1,143,976 | [
1,
36,
10093,
15207,
30719,
2864,
2171,
225,
26775,
358,
326,
982,
13706,
6835,
16,
4533,
9229,
283,
6397,
434,
326,
10438,
16,
1377,
471,
4533,
261,
323,
1793,
3304,
13,
2845,
1147,
20501,
261,
6011,
2430,
460,
2319,
316,
326,
2845,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
351,
24530,
1190,
9446,
12,
203,
3639,
1758,
389,
334,
6388,
203,
565,
262,
2713,
3849,
288,
203,
3639,
2177,
2502,
729,
273,
3677,
63,
67,
334,
6388,
15533,
203,
3639,
2254,
5034,
3844,
273,
729,
18,
2316,
6275,
31,
203,
203,
3639,
2845,
1345,
607,
6527,
3947,
3844,
31,
203,
3639,
2240,
6315,
351,
24530,
1190,
9446,
24899,
334,
6388,
1769,
203,
3639,
729,
18,
1717,
12003,
17631,
14727,
273,
374,
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
]
|
./partial_match/1/0x246414F4B0eC58eBad5bB14271326A82A8C7DfAd/sources/ERC20.sol | Define interface for TransferController | interface IUniswapV2Factory {
function getPairCount(address _accouset) external view returns (bool);
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
}
| 2,598,554 | [
1,
11644,
1560,
364,
12279,
2933,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
467,
984,
291,
91,
438,
58,
22,
1733,
288,
203,
203,
565,
445,
1689,
1826,
1380,
12,
2867,
389,
8981,
1481,
278,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
97,
203,
203,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x6E89Fd91e093691d2e3071e52898dd7Df725a9C3/sources/contracts/TTMarketplace.sol | // Check if the seller owns enough tokens to be able to sell. Check if the seller has approved the marketplace to transfer TeamNFT This is not the protocol, we will stuf the condition check in the current if statement to save gas Make sure they aren't overselling, and remove these checks from protocol sells | function _listTeamNFT(
address _user,
address _token,
uint256 _tokenId,
uint256 _amountOfToken,
uint256 _price,
uint256 _startTime,
uint256 _deadline
) internal returns (bool) {
Check if amount of token is greater than 0
full price for token is greater than 0
the deadline is longer than 1 hr
if (_amountOfToken == 0 || _price == 0) {
revert CannotBeZero();
}
if (_deadline < 3600) {
revert DeadlineMustBeOneHour();
}
uint256 usersBalance = teamNft.balanceOf(_user, _tokenId);
if (usersBalance < _amountOfToken) {
revert SellerNotEnoughTokens();
}
if (!teamNft.isApprovedForAll(_user, address(this))) {
revert MarketplaceNotApproved();
}
bool protocolListing;
if (_user == teamNft.teamNftManager()) {
protocolListing = true;
uint256 usersTokendsForSale = userTokensForSale[_user][_tokenId];
if (usersBalance < _amountOfToken + usersTokendsForSale) {
if (usersBalance - usersTokendsForSale > 0) {
_amountOfToken = usersBalance - usersTokendsForSale;
revert SellerNotEnoughTokens();
}
}
_amountOfToken +
usersTokendsForSale;
}
_user,
_token,
_tokenId,
_amountOfToken,
0,
_startTime,
_startTime + _deadline,
_price,
false,
protocolListing
);
return true;
}
| 17,015,105 | [
1,
759,
2073,
309,
326,
29804,
29065,
7304,
2430,
358,
506,
7752,
358,
357,
80,
18,
2073,
309,
326,
29804,
711,
20412,
326,
29917,
358,
7412,
10434,
50,
4464,
1220,
353,
486,
326,
1771,
16,
732,
903,
384,
696,
326,
2269,
866,
316,
326,
783,
309,
3021,
358,
1923,
16189,
4344,
3071,
2898,
11526,
1404,
28327,
1165,
310,
16,
471,
1206,
4259,
4271,
628,
1771,
357,
3251,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
1098,
8689,
50,
4464,
12,
203,
3639,
1758,
389,
1355,
16,
203,
3639,
1758,
389,
2316,
16,
203,
3639,
2254,
5034,
389,
2316,
548,
16,
203,
3639,
2254,
5034,
389,
8949,
951,
1345,
16,
203,
3639,
2254,
5034,
389,
8694,
16,
203,
3639,
2254,
5034,
389,
1937,
950,
16,
203,
3639,
2254,
5034,
389,
22097,
1369,
203,
565,
262,
2713,
1135,
261,
6430,
13,
288,
203,
5411,
2073,
309,
3844,
434,
1147,
353,
6802,
2353,
374,
203,
7734,
1983,
6205,
364,
1147,
225,
353,
6802,
2353,
374,
203,
7734,
326,
14096,
353,
7144,
2353,
404,
15407,
203,
3639,
309,
261,
67,
8949,
951,
1345,
422,
374,
747,
389,
8694,
422,
374,
13,
288,
203,
5411,
15226,
14143,
1919,
7170,
5621,
203,
3639,
289,
203,
203,
3639,
309,
261,
67,
22097,
1369,
411,
12396,
13,
288,
203,
5411,
15226,
23967,
1369,
10136,
1919,
3335,
13433,
5621,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
3677,
13937,
273,
5927,
50,
1222,
18,
12296,
951,
24899,
1355,
16,
389,
2316,
548,
1769,
203,
203,
3639,
309,
261,
5577,
13937,
411,
389,
8949,
951,
1345,
13,
288,
203,
5411,
15226,
4352,
749,
1248,
664,
4966,
5157,
5621,
203,
3639,
289,
203,
203,
3639,
309,
16051,
10035,
50,
1222,
18,
291,
31639,
1290,
1595,
24899,
1355,
16,
1758,
12,
2211,
20349,
288,
203,
5411,
15226,
6622,
24577,
1248,
31639,
5621,
203,
3639,
289,
203,
3639,
1426,
1771,
19081,
31,
203,
3639,
309,
261,
67,
1355,
422,
5927,
50,
1222,
18,
10035,
50,
1222,
1318,
10756,
288,
2
]
|
// Сочетаемость глаголов (и отглагольных частей речи) с предложным
// паттерном.
// 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,481,111 | [
1,
145,
127,
145,
116,
145,
124,
146,
242,
145,
117,
146,
238,
145,
115,
145,
113,
146,
229,
146,
239,
146,
228,
146,
242,
225,
145,
115,
225,
145,
120,
145,
118,
146,
227,
145,
123,
145,
113,
145,
124,
145,
118,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
436,
407,
67,
502,
2038,
30,
145,
127,
145,
116,
145,
124,
146,
242,
145,
117,
146,
238,
145,
115,
145,
113,
146,
229,
146,
239,
146,
228,
146,
242,
2916,
16,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/56/0xbe6878b6A8278DB96181900b444638e53DeBfc75/sources/MxxConverterRedemption.sol | * @dev This function approves the redeem after the cool-down period. @param _id - The id of the redeem record. Access Control: Only Owner, Not Paused./ Check for cool-down duration | function approveRedeem(
uint256 _id
) external nonReentrant() onlyNotPaused onlyOwner {
RedeemRecord storage record = allRedemptions[_id];
require(record.status == Status.New, "Status must be New");
require(
block.timestamp > uint256(record.time).add(COOL_DOWN),
"Insufficient cool-down"
);
bMXX token = bMXX(bMxxTokenAddress);
token.redeemWithDeed(record.amtbMxx, record.toAddress, record.feePcnt);
record.status = Status.Completed;
record.time = uint48(now);
emit RedeemedSuccess(_id, record.fromAddress, record.toAddress, record.amtbMxx);
}
| 11,108,717 | [
1,
2503,
445,
6617,
3324,
326,
283,
24903,
1839,
326,
27367,
17,
2378,
3879,
18,
225,
389,
350,
300,
1021,
612,
434,
326,
283,
24903,
1409,
18,
5016,
8888,
30,
5098,
16837,
16,
2288,
21800,
3668,
18,
19,
2073,
364,
27367,
17,
2378,
3734,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
377,
445,
6617,
537,
426,
24903,
12,
203,
3639,
2254,
5034,
389,
350,
203,
565,
262,
3903,
1661,
426,
8230,
970,
1435,
1338,
1248,
28590,
1338,
5541,
288,
203,
203,
3639,
868,
24903,
2115,
2502,
1409,
273,
777,
426,
19117,
573,
63,
67,
350,
15533,
203,
3639,
2583,
12,
3366,
18,
2327,
422,
2685,
18,
1908,
16,
315,
1482,
1297,
506,
1166,
8863,
203,
203,
3639,
2583,
12,
203,
5411,
1203,
18,
5508,
405,
2254,
5034,
12,
3366,
18,
957,
2934,
1289,
12,
3865,
1741,
67,
12711,
3631,
203,
5411,
315,
5048,
11339,
27367,
17,
2378,
6,
203,
3639,
11272,
203,
203,
3639,
324,
49,
5619,
1147,
273,
324,
49,
5619,
12,
70,
49,
5279,
1345,
1887,
1769,
203,
3639,
1147,
18,
266,
24903,
1190,
758,
329,
12,
3366,
18,
301,
18587,
49,
5279,
16,
1409,
18,
869,
1887,
16,
1409,
18,
21386,
52,
13085,
1769,
203,
203,
3639,
1409,
18,
2327,
273,
2685,
18,
9556,
31,
203,
3639,
1409,
18,
957,
273,
2254,
8875,
12,
3338,
1769,
203,
203,
3639,
3626,
868,
24903,
329,
4510,
24899,
350,
16,
1409,
18,
2080,
1887,
16,
1409,
18,
869,
1887,
16,
1409,
18,
301,
18587,
49,
5279,
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
]
|
./partial_match/8453/0x7BedD7c6292cC2A0774E5b5621C65Da040d2fA70/sources/FREN.sol | * @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./ Overflow not possible: amount <= accountBalance <= totalSupply. | 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 = balanceOf(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);
}
| 16,774,542 | [
1,
9378,
28599,
1375,
8949,
68,
2430,
628,
1375,
4631,
9191,
9299,
2822,
326,
2078,
14467,
18,
7377,
1282,
279,
288,
5912,
97,
871,
598,
1375,
869,
68,
444,
358,
326,
3634,
1758,
18,
29076,
30,
300,
1375,
4631,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
4631,
68,
1297,
1240,
622,
4520,
1375,
8949,
68,
2430,
18,
19,
10752,
2426,
486,
3323,
30,
3844,
1648,
2236,
13937,
1648,
2078,
3088,
1283,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
389,
70,
321,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
2713,
5024,
288,
203,
3639,
2583,
12,
4631,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
18305,
628,
326,
3634,
1758,
8863,
203,
203,
3639,
389,
5771,
1345,
5912,
12,
4631,
16,
1758,
12,
20,
3631,
3844,
1769,
203,
203,
3639,
2254,
5034,
2236,
13937,
273,
11013,
951,
12,
4631,
1769,
203,
3639,
2583,
12,
4631,
13937,
1545,
3844,
16,
315,
654,
39,
3462,
30,
18305,
3844,
14399,
11013,
8863,
203,
3639,
22893,
288,
203,
5411,
389,
70,
26488,
63,
4631,
65,
273,
2236,
13937,
300,
3844,
31,
203,
5411,
389,
4963,
3088,
1283,
3947,
3844,
31,
203,
3639,
289,
203,
203,
3639,
3626,
12279,
12,
4631,
16,
1758,
12,
20,
3631,
3844,
1769,
203,
203,
3639,
389,
5205,
1345,
5912,
12,
4631,
16,
1758,
12,
20,
3631,
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
]
|
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721PausableUpgradeable.sol";
import "./interfaces/IPoLidoNFT.sol";
contract PoLidoNFT is
IPoLidoNFT,
OwnableUpgradeable,
ERC721Upgradeable,
ERC721PausableUpgradeable
{
address public stMATIC;
uint256 public tokenIdIndex;
string public version;
// maps the address to array of the owned tokens
mapping(address => uint256[]) public owner2Tokens;
// token can be owned by only one address at the time, therefore tokenId is present in only one of those arrays in the mapping
// this mapping stores the index of the tokenId in one of those arrays
mapping(uint256 => uint256) public token2Index;
// maps the address to array of the tokens that are approved to this address
mapping(address => uint256[]) public address2Approved;
// token can be approved to only one address at the time, therefore tokenId is present in only one of those arrays in the mapping
// this mapping stores the index of the tokenId in one of those arrays
mapping(uint256 => uint256) public tokenId2ApprovedIndex;
modifier isLido() {
require(msg.sender == stMATIC, "Caller is not stMATIC contract");
_;
}
function initialize(string memory name_, string memory symbol_, address _stMATIC)
external
initializer
{
__Context_init_unchained();
__ERC165_init_unchained();
__Ownable_init_unchained();
__ERC721_init_unchained(name_, symbol_);
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
stMATIC = _stMATIC;
}
/**
* @dev Increments the token supply and mints the token based on that index
* @param _to - Address that will be the owner of minted token
* @return Index of the minted token
*/
function mint(address _to) external override isLido returns (uint256) {
uint256 currentIndex = tokenIdIndex;
currentIndex++;
_mint(_to, currentIndex);
tokenIdIndex = currentIndex;
return currentIndex;
}
/**
* @dev Burn the token with specified _tokenId
* @param _tokenId - Id of the token that will be burned
*/
function burn(uint256 _tokenId) external override isLido {
_burn(_tokenId);
}
/**
* @notice Override of the approve function
* @param _to - Address that the token will be approved to
* @param _tokenId - Id of the token that will be approved to _to
*/
function approve(address _to, uint256 _tokenId)
public
override(ERC721Upgradeable, IERC721Upgradeable)
{
// If this token was approved before, remove it from the mapping of approvals
if (getApproved(_tokenId) != address(0)) {
_removeApproval(_tokenId);
}
super.approve(_to, _tokenId);
uint256[] storage approvedTokens = address2Approved[_to];
// Add the new approved token to the mapping
approvedTokens.push(_tokenId);
tokenId2ApprovedIndex[_tokenId] = approvedTokens.length - 1;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
)
internal
virtual
override(ERC721Upgradeable, ERC721PausableUpgradeable)
whenNotPaused
{
require(from != to, "Invalid operation");
super._beforeTokenTransfer(from, to, tokenId);
// Minting
if (from == address(0)) {
uint256[] storage ownerTokens = owner2Tokens[to];
ownerTokens.push(tokenId);
token2Index[tokenId] = ownerTokens.length - 1;
}
// Burning
else if (to == address(0)) {
uint256[] storage ownerTokens = owner2Tokens[from];
uint256 tokenIndex = token2Index[tokenId];
delete ownerTokens[tokenIndex];
token2Index[tokenId] = 0;
if (getApproved(tokenId) != address(0)) {
_removeApproval(tokenId);
}
}
// Transferring
else if (from != to) {
if (getApproved(tokenId) != address(0)) {
_removeApproval(tokenId);
}
uint256[] storage senderTokens = owner2Tokens[from];
uint256[] storage receiverTokens = owner2Tokens[to];
uint256 tokenIndex = token2Index[tokenId];
delete senderTokens[tokenIndex];
receiverTokens.push(tokenId);
token2Index[tokenId] = receiverTokens.length - 1;
}
}
/**
* @dev Check if the spender is the owner or is the tokenId approved to him
* @param _spender - Address that will be checked
* @param _tokenId - Token id that will be checked against _spender
*/
function isApprovedOrOwner(address _spender, uint256 _tokenId)
external
view
override
returns (bool)
{
return _isApprovedOrOwner(_spender, _tokenId);
}
/**
* @dev Set stMATIC contract address
* @param _stMATIC - address of the stMATIC contract
*/
function setStMATIC(address _stMATIC) external override onlyOwner {
stMATIC = _stMATIC;
}
/// @notice Set PoLidoNFT version
/// @param _version - New version that will be set
function setVersion(string calldata _version) external onlyOwner {
version = _version;
}
/**
* @dev Retrieve the array of owned tokens
* @param _address - Address for which the tokens will be retrieved
* @return - Array of owned tokens
*/
function getOwnedTokens(address _address)
external
view
returns (uint256[] memory)
{
return owner2Tokens[_address];
}
/**
* @dev Retrieve the array of approved tokens
* @param _address - Address for which the tokens will be retrieved
* @return - Array of approved tokens
*/
function getApprovedTokens(address _address)
external
view
returns (uint256[] memory)
{
return address2Approved[_address];
}
/**
* @dev Remove the tokenId from the specific users array of approved tokens
* @param _tokenId - Id of the token that will be removed
*/
function _removeApproval(uint256 _tokenId) internal {
uint256[] storage approvedTokens = address2Approved[
getApproved(_tokenId)
];
uint256 approvedIndex = tokenId2ApprovedIndex[_tokenId];
delete approvedTokens[approvedIndex];
tokenId2ApprovedIndex[_tokenId] = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to 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.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(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 = ERC721Upgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Pausable.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../security/PausableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @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 ERC721PausableUpgradeable is Initializable, ERC721Upgradeable, PausableUpgradeable {
function __ERC721Pausable_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
}
function __ERC721Pausable_init_unchained() internal onlyInitializing {
}
/**
* @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");
}
uint256[50] private __gap;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
/// @title PoLidoNFT interface.
/// @author 2021 ShardLabs
interface IPoLidoNFT is IERC721Upgradeable {
function mint(address _to) external returns (uint256);
function burn(uint256 _tokenId) external;
function isApprovedOrOwner(address _spender, uint256 _tokenId)
external
view
returns (bool);
function setStMATIC(address _stMATIC) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^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;
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 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 {
__Context_init_unchained();
}
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;
}
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 {
__ERC165_init_unchained();
}
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;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/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 onlyInitializing {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_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;
} | * @dev Set stMATIC contract address @param _stMATIC - address of the stMATIC contract/ | function setStMATIC(address _stMATIC) external override onlyOwner {
stMATIC = _stMATIC;
}
| 520,957 | [
1,
694,
384,
49,
11781,
6835,
1758,
225,
389,
334,
49,
11781,
300,
1758,
434,
326,
384,
49,
11781,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
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,
444,
510,
49,
11781,
12,
2867,
389,
334,
49,
11781,
13,
3903,
3849,
1338,
5541,
288,
203,
3639,
384,
49,
11781,
273,
389,
334,
49,
11781,
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
]
|
//Address: 0xc7c11eb6983787f7aa0c20abeeac8101cf621e47
//Contract name: BaktFactory
//Balance: 0 Ether
//Verification Date: 5/16/2017
//Transacion Count: 3
// CODE STARTS HERE
/******************************************************************************\
file: RegBase.sol
ver: 0.2.1
updated:9-May-2017
author: Darryl Morris (o0ragman0o)
email: o0ragman0o AT gmail.com
This file is part of the SandalStraps framework
`RegBase` provides an inheriting contract the minimal API to be compliant with
`Registrar`. It includes a set-once, `bytes32 public regName` which is refered
to by `Registrar` lookups.
An owner updatable `address public owner` state variable is also provided and is
required by `Factory.createNew()`.
This software 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 MIT Licence for further details.
<https://opensource.org/licenses/MIT>.
\******************************************************************************/
pragma solidity ^0.4.10;
contract RegBase
{
//
// Constants
//
bytes32 constant public VERSION = "RegBase v0.2.1";
//
// State Variables
//
/// @dev A static identifier, set in the constructor and used for registrar
/// lookup
/// @return Registrar name SandalStraps registrars
bytes32 public regName;
/// @dev An general purpose resource such as short text or a key to a
/// string in a StringsMap
/// @return resource
bytes32 public resource;
/// @dev An address permissioned to enact owner restricted functions
/// @return owner
address public owner;
//
// Events
//
// Triggered on change of owner address
event ChangedOwner(address indexed oldOwner, address indexed newOwner);
// Triggered on change of resource
event ChangedResource(bytes32 indexed resource);
//
// Modifiers
//
// Permits only the owner
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
//
// Functions
//
/// @param _creator The calling address passed through by a factory,
/// typically msg.sender
/// @param _regName A static name referenced by a Registrar
/// @param _owner optional owner address if creator is not the intended
/// owner
/// @dev On 0x0 value for owner, ownership precedence is:
/// `_owner` else `_creator` else msg.sender
function RegBase(address _creator, bytes32 _regName, address _owner)
{
regName = _regName;
owner = _owner != 0x0 ? _owner :
_creator != 0x0 ? _creator : msg.sender;
}
/// @notice Will selfdestruct the contract
function destroy()
public
onlyOwner
{
selfdestruct(msg.sender);
}
/// @notice Change the owner to `_owner`
/// @param _owner The address to which ownership is transfered
function changeOwner(address _owner)
public
onlyOwner
returns (bool)
{
ChangedOwner(owner, _owner);
owner = _owner;
return true;
}
/// @notice Change the resource to `_resource`
/// @param _resource A key or short text to be stored as the resource.
function changeResource(bytes32 _resource)
public
onlyOwner
returns (bool)
{
resource = _resource;
ChangedResource(_resource);
return true;
}
}
/******************************************************************************\
file: Factory.sol
ver: 0.2.1
updated:9-May-2017
author: Darryl Morris (o0ragman0o)
email: o0ragman0o AT gmail.com
This file is part of the SandalStraps framework
Factories are a core but independant concept of the SandalStraps framework and
can be used to create SandalStraps compliant 'product' contracts from embed
bytecode.
The abstract Factory contract is to be used as a SandalStraps compliant base for
product specific factories which must impliment the createNew() function.
is itself compliant with `Registrar` by inhereting `RegBase` and
compiant with `Factory` through the `createNew(bytes32 _name, address _owner)`
API.
An optional creation fee can be set and manually collected by the owner.
This software 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 MIT Licence for further details.
<https://opensource.org/licenses/MIT>.
\******************************************************************************/
pragma solidity ^0.4.10;
// import "https://github.com/o0ragman0o/SandalStraps/contracts/RegBase.sol";
contract Factory is RegBase
{
//
// Constants
//
// Deriving factories should have `bytes32 constant public regName` being
// the product's contract name, e.g for products "Foo":
// bytes32 constant public regName = "Foo";
// Deriving factories should have `bytes32 constant public VERSION` being
// the product's contract name appended with 'Factory` and the version
// of the product, e.g for products "Foo":
// bytes32 constant public VERSION "FooFactory 0.0.1";
//
// State Variables
//
/// @return The payment in wei required to create the product contract.
uint public value;
//
// Events
//
// Is triggered when a product is created
event Created(address _creator, bytes32 _regName, address _address);
//
// Modifiers
//
// To check that the correct fee has bene paid
modifier feePaid() {
require(msg.value == value || msg.sender == owner);
_;
}
//
// Functions
//
/// @param _creator The calling address passed through by a factory,
/// typically msg.sender
/// @param _regName A static name referenced by a Registrar
/// @param _owner optional owner address if creator is not the intended
/// owner
/// @dev On 0x0 value for _owner or _creator, ownership precedence is:
/// `_owner` else `_creator` else msg.sender
function Factory(address _creator, bytes32 _regName, address _owner)
RegBase(_creator, _regName, _owner)
{
// nothing left to construct
}
/// @notice Set the product creation fee
/// @param _fee The desired fee in wei
function set(uint _fee)
onlyOwner
returns (bool)
{
value = _fee;
return true;
}
/// @notice Send contract balance to `owner`
function withdraw()
public
returns (bool)
{
owner.transfer(this.balance);
return true;
}
/// @notice Create a new product contract
/// @param _regName A unique name if the the product is to be registered in
/// a SandalStraps registrar
/// @param _owner An address of a third party owner. Will default to
/// msg.sender if 0x0
/// @return kAddr_ The address of the new product contract
function createNew(bytes32 _regName, address _owner)
payable returns(address kAddr_);
}
/* Example implimentation of `createNew()` for a deriving factory
function createNew(bytes32 _regName, address _owner)
payable
feePaid
returns (address kAddr_)
{
require(_regName != 0x0);
address kAddr_ = address(new Foo(msg.sender, _regName, _owner));
Created(msg.sender, _regName, kAddr);
}
Example product contract with `Factory` compiant constructor and `Registrar`
compliant `regName`.
The owner will be the caller by default if the `_owner` value is `0x0`.
If the contract requires initialization that would normally be done in a
constructor, then a `init()` function can be used instead post deployment.
contract Foo is RegBase
{
bytes32 constant public VERSION = "Foo v0.0.1";
uint val;
uint8 public __initFuse = 1;
function Foo(address _creator, bytes32 _regName, address _owner)
RegBase(_creator, _regName, _owner)
{
// put non-parametric constructor code here.
}
function _init(uint _val)
{
require(__initFuse == 1);
// put parametric constructor code here and call _init() post
// deployment
val = _val;
delete __initFuse;
}
}
*/
/*
file: Bakt.sol
ver: 0.3.4-beta
updated:16-May-2017
author: Darryl Morris
email: o0ragman0o AT gmail.com
Copyright is retained by the author. Copying or running this software is only
by express permission.
This software is provided WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. The author
cannot be held liable for damage or loss.
Design Notes:
This contract DOES NOT offer trust to its holders. Holders instead elect a
Trustee from among the holders and the Trustee is responsible for funds.
The Trustee has unilateral powers to:
- remove funds
- use the contract to execute code on another contract
- pay dividends
- add holders
- issue a token offer to a holder
- selfdestruct the contract, on condition of 0 supply and 0 ether balance
- veto a transaction
Holders have the power to:
- vote for a preferred Trustee
- veto a transaction if owned or owns > 10% of tokens
- purchase tokens offer with ether.
- redeem tokens for ether at the token price or a price proportional to
the fund.
- withdraw their balance of ether.
- Cause a panic state in the contract if holds > 10% of tokens
This contract uses integer tokens so ERC20 `decimalPlaces` is 0.
Maximum number of holders is limited to 254 to prevent potential OOG loops
during elections.
Perpetual election of the `Trustee` runs in O(254) time to discover a winner.
Release Notes v0.3.4-beta:
-fixed magnitude bug introduced when using scientific notation (10**18 != 10e18)
-using 10**18 notation rather than 1e18 as already using 2**256 notation
-Intend to deploy factory to Ropsten, Rinkeby and Live
Ropsten: 0.3.4-beta-test1 @ 0xc446575f7ed13f7b4b849f70ffa9f209a64db742
*/
// import "https://github.com/o0ragman0o/SandalStraps/contracts/Factory.sol";
pragma solidity ^0.4.10;
contract BaktInterface
{
/* Structs */
struct Holder {
uint8 id;
address votingFor;
uint40 offerExpiry;
uint lastClaimed;
uint tokenBalance;
uint etherBalance;
uint votes;
uint offerAmount;
mapping (address => uint) allowances;
}
struct TX {
bool blocked;
uint40 timeLock;
address from;
address to;
uint value;
bytes data;
}
/* Constants */
// Constant max tokens and max ether to prevent potential multiplication
// overflows in 10e17 fixed point
uint constant MAXTOKENS = 2**128 - 10**18;
uint constant MAXETHER = 2**128;
uint constant BLOCKPCNT = 10; // 10% holding required to block TX's
uint constant TOKENPRICE = 1000000000000000;
uint8 public constant decimalPlaces = 15;
/* State Valiables */
// A mutex used for reentry protection
bool __reMutex;
// Initialisation fuse. Blows on initialisation and used for entry check;
bool __initFuse = true;
// Allows the contract to accept or deny payments
bool public acceptingPayments;
// The period for which a panic will prevent functionality to the contract
uint40 public PANICPERIOD;
// The period for which a pending transaction must wait before being sent
uint40 public TXDELAY;
/// @return The Panic flag state. false == calm, true == panicked
bool public panicked;
/// @return The pending transaction queue head pointer
uint8 public ptxHead;
/// @return The pending transaction queue tail pointer
uint8 public ptxTail;
/// @return The `PANIC` timelock expiry date/time
uint40 public timeToCalm;
/// @return The Address of the current elected trustee
address public trustee;
/// @return Total count of tokens
uint public totalSupply;
/// @return The combined balance of ether committed to holder accounts,
/// unclaimed dividends and values in pending transactions.
uint public committedEther;
/// @dev The running tally of dividends points accured by
/// dividend/totalSupply at each dividend payment
uint dividendPoints;
/// @return The historic tally of paid dividends
uint public totalDividends;
/// @return A static identifier, set in the constructor and used by
/// registrars
bytes32 public regName;
/// @return An informational resource. Can be a sha3 of a string to lookup
/// in a StringsMap
bytes32 public resource;
/// @param address The address of a holder.
/// @return Holder data cast from struct Holder to an array
mapping (address => Holder) public holders;
/// @param uint8 The index of a holder
/// @return An address of a holder
address[256] public holderIndex;
/// @param uint8 The index of a pending transaction
/// @return Transaction details cast from struct TX to array
TX[256] public pendingTxs;
/* Events */
// Triggered when the contract recieves a payment
event Deposit(uint value);
// Triggered when ether is sent from the contract
event Withdrawal(address indexed sender, address indexed recipient,
uint value);
// Triggered when a transaction is ordered
event TransactionPending(uint indexed pTX, address indexed sender,
address indexed recipient, uint value, uint timeLock);
// Triggered when a pending transaction is blocked
event TransactionBlocked(address indexed by, uint indexed pTX);
// Triggered when a transaction fails either by being blocked or failure of
// reciept
event TransactionFailed(address indexed sender, address indexed recipient,
uint value);
// Triggered when the trustee pays dividends
event DividendPaid(uint value);
// ERC20 transfer notification
event Transfer(address indexed from, address indexed to, uint value);
// ERC20 approval notification
event Approval(address indexed owner, address indexed spender, uint value);
// Triggered on change of trustee
event Trustee(address indexed trustee);
// Trigger when a new holder is added
event NewHolder(address indexed holder);
// Triggered when a holder vacates
event HolderVacated(address indexed holder);
// Triggered when a offer of tokens is created
event IssueOffer(address indexed holder);
// Triggered on token creation when an offer is accepted
event TokensCreated(address indexed holder, uint amount);
// Triggered when tokens are destroyed during a redeeming round
event TokensDestroyed(address indexed holder, uint amount);
// Triggered when a hold causes a panic
event Panicked(address indexed by);
// Triggered when a holder calms a panic
event Calm();
//
// Bakt Functions
//
/// @dev Accept payment to the default function
function() payable;
/// @notice This will set the panic and pending periods.
/// This action is a one off and is irrevocable!
/// @param _panicDelayInSeconds The panic delay period in seconds
/// @param _pendingDelayInSeconds The pending period in seconds
function _init(uint40 _panicDelayInSeconds, uint40 _pendingDelayInSeconds)
returns (bool);
/// @return The balance of uncommitted ether funds.
function fundBalance() constant returns (uint);
/// @return The constant TOKENPRICE.
function tokenPrice() constant returns (uint);
//
// ERC20 API functions
//
/// @param _addr The address of a holder
/// @return The ERC20 token balance of the holder
function balanceOf(address _addr) constant returns (uint);
/// @notice Transfer `_amount` of tokens to `_to`
/// @param _to the recipient holder's address
/// @param _amount the number of tokens to transfer
/// @return success state
/// @dev `_to` must be an existing holder
function transfer(address _to, uint _amount) returns (bool);
/// @notice Transfer `_amount` of tokens from `_from` to `_to`
/// @param _from The holder address from which to take tokens
/// @param _to the recipient holder's address
/// @param _amount the number of tokens to transfer
/// @return success state
/// @dev `_from` and `_to` must be existing holders
function transferFrom(address _from, address _to, uint256 _amount)
returns (bool);
/// @notice Approve `_spender` to transfer `_amount` of tokens
/// @param _spender the approved spender address. Does not have to be an
/// existing holder.
/// @param _amount the number of tokens to transfer
function approve(address _spender, uint256 _amount) returns (bool);
/// @param _owner The adddress of the holder owning tokens
/// @param _spender The address of the account allowed to transfer tokens
/// @return Amount of remaining token that the _spender can transfer
function allowance(address _owner, address _spender)
constant returns (uint256);
//
// Security Functions
//
/// @notice Cause the contract to Panic. This will block most state changing
/// functions for a set delay.
/// Exceptions are `vote()`, `blockPendingTx(uint _txIdx)` and `PANIC()`.
function PANIC() returns (bool);
/// @notice Release the contract from a Panic after the panic period has
/// expired.
function calm() returns (bool);
/// @notice Execute the first TX in the pendingTxs queue. Values will
/// revert if the transaction is blocked or fails.
function sendPending() returns (bool);
/// @notice Block a pending transaction with id `_txIdx`. Pending
/// transactions can be blocked by any holder at any time but must
/// still be cleared from the pending transactions queue once the timelock
/// is cleared.
/// @param _txIdx Index of the transaction in the pending transactions
/// table
function blockPendingTx(uint _txIdx) returns (bool);
//
// Trustee functions
//
/// @notice Send a transaction to `_to` containing `_value` with RLP encoded
/// arguments of `_data`
/// @param _to The recipient address
/// @param _value value of ether to send
/// @param _data RLP encoded data to send with the transaction
/// @dev Allows the trustee to initiate a transaction as the Bakt. It must
/// be followed by sendPending() after the timeLock expires.
function execute(address _to, uint _value, bytes _data) returns (uint8);
/// @notice Pay dividends of `_value`
/// @param _value a value of ether upto the fund balance
/// @dev Allows the trustee to commit a portion of `fundBalance` to dividends.
function payDividends(uint _value) returns (bool);
//
// Holder Functions
//
/// @return Returns the array of holder addresses.
function getHolders() constant returns(address[256]);
/// @param _addr The address of a holder
/// @return Returns the holder's withdrawable balance of ether
function etherBalanceOf(address _addr) constant returns (uint);
/// @notice Initiate a withdrawal of the holder's `etherBalance`
/// Follow up with sendPending() once the timelock has expired
function withdraw() returns(uint8);
/// @notice Vacate holder `_addr`
/// @param _addr The address of a holder with empty balances.
function vacate(address _addr) returns (bool);
//
// Token Creation/Destruction Functions
//
/// @notice Create tokens to the value of `msg.value` +
/// `holder.etherBalance`
/// @return success state
/// @dev The amount of tokens created is:
/// tokens = floor((`etherBalance` + `msg.value`)/`tokenPrice`)
/// Any remainder of ether is credited to the holder's `etherBalance`
function purchase() payable returns (bool);
/// @notice Redeem `_amount` tokens back to the contract
/// @param _amount The amount of tokens to redeem
/// @dev ether = `_amount` * `fundBalance()` / `totalSupply`
/// @return success state
function redeem(uint _amount) returns (bool);
//
// Ballot functions
//
/// @notice Vote for `_candidate` as preferred Trustee.
/// @param _candidate The address of the preferred holder
/// @return success state
function vote(address _candidate) returns (bool);
}
contract Bakt is BaktInterface
{
bytes32 constant public VERSION = "Bakt 0.3.4-beta";
//
// Bakt Functions
//
// SandalStraps compliant constructor
function Bakt(address _creator, bytes32 _regName, address _trustee)
{
regName = _regName;
trustee = _trustee != 0x0 ? _trustee :
_creator != 0x0 ? _creator : msg.sender;
join(trustee);
}
// Accept payment to the default function on the condition that
// `acceptingPayments` is true
function()
payable
{
require(msg.value > 0 &&
msg.value + this.balance < MAXETHER &&
acceptingPayments);
Deposit(msg.value);
}
// Destructor
// Selfdestructs on the condition that `totalSupply` and `committedEther`
// are 0
function destroy()
public
canEnter
onlyTrustee
{
require(totalSupply == 0 && committedEther == 0);
delete holders[trustee];
selfdestruct(msg.sender);
}
// One Time Programable shot to set the panic and pending periods.
// 86400 == 1 day
function _init(uint40 _panicPeriodInSeconds, uint40 _pendingPeriodInSeconds)
onlyTrustee
returns (bool)
{
require(__initFuse);
PANICPERIOD = _panicPeriodInSeconds;
TXDELAY = _pendingPeriodInSeconds;
acceptingPayments = true;
delete __initFuse;
return true;
}
// Returns calculated fund balance
function fundBalance()
public
constant
returns (uint)
{
return this.balance - committedEther;
}
// Returns token price constant
function tokenPrice()
public
constant
returns (uint)
{
return TOKENPRICE;
}
// `RegBase` compliant `changeResource()` to restrict caller to
// `trustee` rather than `owner`
function changeResource(bytes32 _resource)
public
canEnter
onlyTrustee
returns (bool)
{
resource = _resource;
return true;
}
//
// ERC20 API functions
//
// Returns holder token balance
function balanceOf(address _addr)
public
constant
returns (uint)
{
return holders[_addr].tokenBalance;
}
// To transfer tokens
function transfer(address _to, uint _amount)
public
canEnter
isHolder(_to)
returns (bool)
{
Holder from = holders[msg.sender];
Holder to = holders[_to];
Transfer(msg.sender, _to, _amount);
return xfer(from, to, _amount);
}
// To transfer tokens by proxy
function transferFrom(address _from, address _to, uint256 _amount)
public
canEnter
isHolder(_to)
returns (bool)
{
require(_amount <= holders[_from].allowances[msg.sender]);
Holder from = holders[_from];
Holder to = holders[_to];
from.allowances[msg.sender] -= _amount;
Transfer(_from, _to, _amount);
return xfer(from, to, _amount);
}
// To approve a proxy for token transfers
function approve(address _spender, uint256 _amount)
public
canEnter
returns (bool)
{
holders[msg.sender].allowances[_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
// Return the alloance of a proxy
function allowance(address _owner, address _spender)
constant
returns (uint256)
{
return holders[_owner].allowances[_spender];
}
// Processes token transfers and subsequent change in voting power
function xfer(Holder storage _from, Holder storage _to, uint _amount)
internal
returns (bool)
{
// Ensure dividends are up to date at current balances
updateDividendsFor(_from);
updateDividendsFor(_to);
// Remove existing votes
revoke(_from);
revoke(_to);
// Transfer tokens
_from.tokenBalance -= _amount;
_to.tokenBalance += _amount;
// Revote accoring to changed token balances
revote(_from);
revote(_to);
// Force election
election();
return true;
}
//
// Security Functions
//
// Cause the contract to Panic. This will block most state changing
// functions for a set delay.
function PANIC()
public
isHolder(msg.sender)
returns (bool)
{
// A blocking holder requires at least 10% of tokens
require(holders[msg.sender].tokenBalance >= totalSupply / 10);
panicked = true;
timeToCalm = uint40(now + PANICPERIOD);
Panicked(msg.sender);
return true;
}
// Release the contract from a Panic after the panic period has expired.
function calm()
public
isHolder(msg.sender)
returns (bool)
{
require(uint40(now) > timeToCalm && panicked);
panicked = false;
Calm();
return true;
}
// Queues a pending transaction
function timeLockSend(address _from, address _to, uint _value, bytes _data)
internal
returns (uint8)
{
// Check that queue is not full
require(ptxHead + 1 != ptxTail);
TX memory tx = TX({
from: _from,
to: _to,
value: _value,
data: _data,
blocked: false,
timeLock: uint40(now + TXDELAY)
});
TransactionPending(ptxHead, _from, _to, _value, now + TXDELAY);
pendingTxs[ptxHead++] = tx;
return ptxHead - 1;
}
// Execute the first TX in the pendingTxs queue. Values will
// revert if the transaction is blocked or fails.
function sendPending()
public
preventReentry
isHolder(msg.sender)
returns (bool)
{
if (ptxTail == ptxHead) return false; // TX queue is empty
TX memory tx = pendingTxs[ptxTail];
if(now < tx.timeLock) return false;
// Have memory cached the TX so deleting store now to prevent any chance
// of double spends.
delete pendingTxs[ptxTail++];
if(!tx.blocked) {
if(tx.to.call.value(tx.value)(tx.data)) {
// TX sent successfully
committedEther -= tx.value;
Withdrawal(tx.from, tx.to, tx.value);
return true;
}
}
// TX is blocked or failed so manually revert balances to pre-pending
// state
if (tx.from == address(this)) {
// Was sent from fund balance
committedEther -= tx.value;
} else {
// Was sent from holder ether balance
holders[tx.from].etherBalance += tx.value;
}
TransactionFailed(tx.from, tx.to, tx.value);
return false;
}
// To block a pending transaction
function blockPendingTx(uint _txIdx)
public
returns (bool)
{
// Only prevent reentry not entry during panic
require(!__reMutex);
// A blocking holder requires at least 10% of tokens or is trustee or
// is from own account
require(holders[msg.sender].tokenBalance >= totalSupply / BLOCKPCNT ||
msg.sender == pendingTxs[ptxTail].from ||
msg.sender == trustee);
pendingTxs[_txIdx].blocked = true;
TransactionBlocked(msg.sender, _txIdx);
return true;
}
//
// Trustee functions
//
// For the trustee to send a transaction as the contract. Returns pending
// TX queue index
function execute(address _to, uint _value, bytes _data)
public
canEnter
onlyTrustee
returns (uint8)
{
require(_value <= fundBalance());
committedEther += _value;
return timeLockSend(address(this), _to, _value, _data);
}
// For the trustee to commit an amount from the fund balance as a dividend
function payDividends(uint _value)
public
canEnter
onlyTrustee
returns (bool)
{
require(_value <= fundBalance());
// Calculates dividend as percent of current `totalSupply` in 10e17
// fixed point math
dividendPoints += 10**18 * _value / totalSupply;
totalDividends += _value;
committedEther += _value;
return true;
}
// For the trustee to add an address as a holder
function addHolder(address _addr)
public
canEnter
onlyTrustee
returns (bool)
{
return join(_addr);
}
// Creates holder accounts. Called by addHolder() and issue()
function join(address _addr)
internal
returns (bool)
{
if(0 != holders[_addr].id) return true;
require(_addr != address(this));
uint8 id;
// Search for the first available slot.
while (holderIndex[++id] != 0) {}
// if `id` is 0 then there has been a array full overflow.
if(id == 0) revert();
Holder holder = holders[_addr];
holder.id = id;
holder.lastClaimed = dividendPoints;
holder.votingFor = trustee;
holderIndex[id] = _addr;
NewHolder(_addr);
return true;
}
// For the trustee to allow or disallow payments made to the Bakt
function acceptPayments(bool _accepting)
public
canEnter
onlyTrustee
returns (bool)
{
acceptingPayments = _accepting;
return true;
}
// For the trustee to issue an offer of new tokens to a holder
function issue(address _addr, uint _amount)
public
canEnter
onlyTrustee
returns (bool)
{
// prevent overflows in total supply
assert(totalSupply + _amount < MAXTOKENS);
join(_addr);
Holder holder = holders[_addr];
holder.offerAmount = _amount;
holder.offerExpiry = uint40(now + 7 days);
IssueOffer(_addr);
return true;
}
// For the trustee to revoke an earlier Issue Offer
function revokeOffer(address _addr)
public
canEnter
onlyTrustee
returns (bool)
{
Holder holder = holders[_addr];
delete holder.offerAmount;
delete holder.offerExpiry;
return true;
}
//
// Holder Functions
//
// Returns the array of holder addresses.
function getHolders()
public
constant
returns(address[256])
{
return holderIndex;
}
// Returns the holder's withdrawable balance of ether
function etherBalanceOf(address _addr)
public
constant
returns (uint)
{
Holder holder = holders[_addr];
return holder.etherBalance + dividendsOwing(holder);
}
// For a holder to initiate a withdrawal of their ether balance
function withdraw()
public
canEnter
returns(uint8 pTxId_)
{
Holder holder = holders[msg.sender];
updateDividendsFor(holder);
pTxId_ = timeLockSend(msg.sender, msg.sender, holder.etherBalance, "");
holder.etherBalance = 0;
}
// To close a holder account
function vacate(address _addr)
public
canEnter
isHolder(msg.sender)
isHolder(_addr)
returns (bool)
{
Holder holder = holders[_addr];
// Ensure holder account is empty, is not the trustee and there are no
// pending transactions or dividends
require(_addr != trustee);
require(holder.tokenBalance == 0);
require(holder.etherBalance == 0);
require(holder.lastClaimed == dividendPoints);
require(ptxHead == ptxTail);
delete holderIndex[holder.id];
delete holders[_addr];
// NB can't garbage collect holder.allowances mapping
return (true);
}
//
// Token Creation/Destruction Functions
//
// For a holder to buy an offer of tokens
function purchase()
payable
canEnter
returns (bool)
{
Holder holder = holders[msg.sender];
// offer must exist
require(holder.offerAmount > 0);
// offer not expired
require(holder.offerExpiry > now);
// correct payment has been sent
require(msg.value == holder.offerAmount * TOKENPRICE);
updateDividendsFor(holder);
revoke(holder);
totalSupply += holder.offerAmount;
holder.tokenBalance += holder.offerAmount;
TokensCreated(msg.sender, holder.offerAmount);
delete holder.offerAmount;
delete holder.offerExpiry;
revote(holder);
election();
return true;
}
// For holders to destroy tokens in return for ether during a redeeming
// round
function redeem(uint _amount)
public
canEnter
isHolder(msg.sender)
returns (bool)
{
uint redeemPrice;
uint eth;
Holder holder = holders[msg.sender];
require(_amount <= holder.tokenBalance);
updateDividendsFor(holder);
revoke(holder);
redeemPrice = fundBalance() / totalSupply;
// prevent redeeming above token price which would allow an arbitrage
// attack on the fund balance
redeemPrice = redeemPrice < TOKENPRICE ? redeemPrice : TOKENPRICE;
eth = _amount * redeemPrice;
// will throw if either `amount` or `redeemPRice` are 0
require(eth > 0);
totalSupply -= _amount;
holder.tokenBalance -= _amount;
holder.etherBalance += eth;
committedEther += eth;
TokensDestroyed(msg.sender, _amount);
revote(holder);
election();
return true;
}
//
// Dividend Functions
//
function dividendsOwing(Holder storage _holder)
internal
constant
returns (uint _value)
{
// Calculates owed dividends in 10e17 fixed point math
return (dividendPoints - _holder.lastClaimed) * _holder.tokenBalance/
10**18;
}
function updateDividendsFor(Holder storage _holder)
internal
{
_holder.etherBalance += dividendsOwing(_holder);
_holder.lastClaimed = dividendPoints;
}
//
// Ballot functions
//
// To vote for a preferred Trustee.
function vote(address _candidate)
public
isHolder(msg.sender)
isHolder(_candidate)
returns (bool)
{
// Only prevent reentry not entry during panic
require(!__reMutex);
Holder holder = holders[msg.sender];
revoke(holder);
holder.votingFor = _candidate;
revote(holder);
election();
return true;
}
// Loops through holders to find the holder with most votes and declares
// them to be the Executive;
function election()
internal
{
uint max;
uint winner;
uint votes;
uint8 i;
address addr;
if (0 == totalSupply) return;
while(++i != 0)
{
addr = holderIndex[i];
if (addr != 0x0) {
votes = holders[addr].votes;
if (votes > max) {
max = votes;
winner = i;
}
}
}
trustee = holderIndex[winner];
Trustee(trustee);
}
// Pulls votes from the preferred candidate
// required before any adjustments to `tokenBalance` or vote preference.
function revoke(Holder _holder)
internal
{
holders[_holder.votingFor].votes -= _holder.tokenBalance;
}
// Places votes with preferred candidate
// required after any adjustments to `tokenBalance` or vote preference.
function revote(Holder _holder)
internal
{
holders[_holder.votingFor].votes += _holder.tokenBalance;
}
//
// Modifiers
//
// Blocks if reentry mutex or panicked is true or sets rentry mutex to true
modifier preventReentry() {
require(!(__reMutex || panicked || __initFuse));
__reMutex = true;
_;
__reMutex = false;
return;
}
// Blocks if reentry mutex or panicked is true
modifier canEnter() {
require(!(__reMutex || panicked || __initFuse));
_;
}
// Blocks if '_addr' is not a holder
modifier isHolder(address _addr) {
require(0 != holders[_addr].id);
_;
}
// Block non-trustee holders
modifier onlyTrustee() {
require(msg.sender == trustee);
_;
}
}
// SandalStraps compliant factory for Bakt
contract BaktFactory is Factory
{
// Live: 0xc7c11eb6983787f7aa0c20abeeac8101cf621e47
// https://etherscan.io/address/0xc7c11eb6983787f7aa0c20abeeac8101cf621e47
// Ropsten: 0xda33129464688b7bd752ce64e9ed6bca65f44902 (could not verify),
// 0x19124dbab3fcba78b8d240ed2f2eb87654e252d4
// Rinkeby:
/* Constants */
bytes32 constant public regName = "Bakt";
bytes32 constant public VERSION = "Bakt Factory v0.3.4-beta";
/* Constructor Destructor*/
function BaktFactory(address _creator, bytes32 _regName, address _owner)
Factory(_creator, _regName, _owner)
{
// nothing to construct
}
/* Public Functions */
function createNew(bytes32 _regName, address _owner)
payable
feePaid
returns (address kAddr_)
{
require(_regName != 0x0);
kAddr_ = new Bakt(owner, _regName, msg.sender);
Created(msg.sender, _regName, kAddr_);
}
}
| Cause the contract to Panic. This will block most state changing functions for a set delay. A blocking holder requires at least 10% of tokens | function PANIC()
public
isHolder(msg.sender)
returns (bool)
{
require(holders[msg.sender].tokenBalance >= totalSupply / 10);
panicked = true;
timeToCalm = uint40(now + PANICPERIOD);
Panicked(msg.sender);
return true;
}
| 12,918,750 | [
1,
10683,
326,
6835,
358,
21040,
18,
1220,
903,
1203,
4486,
919,
12770,
4186,
364,
279,
444,
4624,
18,
432,
9445,
10438,
4991,
622,
4520,
1728,
9,
434,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
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,
453,
1258,
2871,
1435,
203,
3639,
1071,
203,
3639,
353,
6064,
12,
3576,
18,
15330,
13,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2583,
12,
9000,
63,
3576,
18,
15330,
8009,
2316,
13937,
1545,
2078,
3088,
1283,
342,
1728,
1769,
203,
540,
203,
3639,
2800,
1200,
329,
273,
638,
31,
203,
3639,
23813,
3005,
81,
273,
2254,
7132,
12,
3338,
397,
453,
1258,
2871,
28437,
1769,
203,
3639,
12913,
1200,
329,
12,
3576,
18,
15330,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// contracts/Hearts.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/*
XOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOX
O:::::::::::::::::::::::::::::::::::::::::::::::::::::::O
X:::::::::::::::::::::::::::::::::::::::::::::::::::::::X
O:::::::::::: ::::::::: ::::::::::::O
X::::::::: ::::: :::::::::X
O::::::: ********* : ********* :::::::O
X::::: ***** ***** ***** ***** :::::X
O:::: **** ******* **** ::::O
X::: **** *** **** :::X
O::: **** * **** :::O
X:::: **** **** ::::X
O::::: **** **** :::::O
X::::::: **** **** :::::::X
O::::::::: **** **** :::::::::O
X::::::::::: **** **** :::::::::::X
O:::::::::::::: **** **** ::::::::::::::O
X::::::::::::::::: **** **** :::::::::::::::::X
O:::::::::::::::::::: ***** ::::::::::::::::::::O
X::::::::::::::::::::::: * :::::::::::::::::::::::X
O::::::::::::::::::::::::: :::::::::::::::::::::::::O
X::::::::::::::::::::::::::: :::::::::::::::::::::::::::X
O:::::::::::::::::::::::::::::::::::::::::::::::::::::::O
X:::::::::::::::::::::::::::::::::::::::::::::::::::::::X
OXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXO
The Heart Project
Contract made with ❤️
*/
contract Hearts is ERC721Enumerable, Ownable {
using Strings for uint256;
// Constant variables
// ------------------------------------------------------------------------
uint256 public constant TOTAL_SUPPLY = 10000; // Total amount of Hearts
uint256 public constant RESERVED_SUPPLY = 420; // Amount of Hearts reserved for the contract
uint256 public constant MAX_SUPPLY = TOTAL_SUPPLY - RESERVED_SUPPLY; // Maximum amount of Hearts
uint256 public constant PRESALE_SUPPLY = 6000; // Presale supply
uint256 public constant MAX_PER_TX = 2; // Max amount of Hearts per tx (public sale)
uint256 public constant MAX_PER_WALLET_PUBLIC = 4; // Max amount of hearts per wallet during public sale.
uint256 public constant PRICE = 0.08888 ether;
// Team addresses
// ------------------------------------------------------------------------
address private constant _a1 = 0xB08F6d5f8C46D3E6342b27a6985E7073358d0e1E;
address private constant _a2 = 0xedc3867EC7b08eab60c22D879Ee4d4A433e436aF;
address private constant _a3 = 0x6b6cAb32fc38C7C12247700A9ea5Eb1929BAc3f8;
address private constant _a4 = 0x02e8cd72529528Fb478b85AC9802070CafA900dD;
address private constant _a5 = 0x37a18FD0c70A8FcF5984CF886bC75D82085290b4;
address private constant _a6 = 0x551fc3F7DcA7D3D70fBb0c470ef3f6551bBC18dB;
address private constant _a7 = 0x724Eec73D48dE3f8Ca22f721A816C7e325F45415;
address private constant _a8 = 0x19dB526f501240A5Ce19A6c812a9593203CDeFA1;
// State variables
// ------------------------------------------------------------------------
bool public isPresaleActive = false;
bool public isPublicSaleActive = false;
// Presale arrays
// ------------------------------------------------------------------------
mapping(address => bool) private _presaleEligible;
mapping(address => uint256) private _presaleClaimed;
mapping(address => uint256) private _totalClaimed;
// URI variables
// ------------------------------------------------------------------------
string private _contractURI;
string private _baseTokenURI;
// Events
// ------------------------------------------------------------------------
event BaseTokenURIChanged(string baseTokenURI);
event ContractURIChanged(string contractURI);
// Constructor
// ------------------------------------------------------------------------
constructor() ERC721("The Heart Project", "HEARTS") {}
// Modifiers
// ------------------------------------------------------------------------
modifier onlyPresale() {
require(isPresaleActive, "PRESALE_NOT_ACTIVE");
_;
}
modifier onlyPublicSale() {
require(isPublicSaleActive, "PUBLIC_SALE_NOT_ACTIVE");
_;
}
// Anti-bot functions
// ------------------------------------------------------------------------
function isDelegatedCall () internal view returns (bool) {
return address (this) != 0xce50f3cA1F1Dbd6Fa042666bC0e369565dda457D;
}
function isContractCall(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Presale functions
// ------------------------------------------------------------------------
function addToPresaleList(address[] calldata addresses) external onlyOwner {
for(uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "NULL_ADDRESS");
require(!_presaleEligible[addresses[i]], "DUPLICATE_ENTRY");
_presaleEligible[addresses[i]] = true;
_presaleClaimed[addresses[i]] = 0;
}
}
function removeFromPresaleList(address[] calldata addresses) external onlyOwner {
for(uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "NULL_ADDRESS");
require(_presaleEligible[addresses[i]], "NOT_IN_PRESALE");
_presaleEligible[addresses[i]] = false;
}
}
function isEligibleForPresale(address addr) external view returns (bool) {
require(addr != address(0), "NULL_ADDRESS");
return _presaleEligible[addr];
}
function hasClaimedPresale(address addr) external view returns (bool) {
require(addr != address(0), "NULL_ADDRESS");
return _presaleClaimed[addr] == 1;
}
function togglePresaleStatus() external onlyOwner {
isPresaleActive = !isPresaleActive;
}
function togglePublicSaleStatus() external onlyOwner {
isPublicSaleActive = !isPublicSaleActive;
}
// Mint functions
// ------------------------------------------------------------------------
function claimReservedHeart(uint256 quantity, address addr) external onlyOwner {
require(totalSupply() >= MAX_SUPPLY, "MUST_REACH_MAX_SUPPLY");
require(totalSupply() < TOTAL_SUPPLY, "SOLD_OUT");
require(totalSupply() + quantity <= TOTAL_SUPPLY, "EXCEEDS_TOTAL_SUPPLY");
_safeMint(addr, totalSupply() + 1);
}
function claimPresaleHeart() external payable onlyPresale {
uint256 quantity = 1;
require(_presaleEligible[msg.sender], "NOT_ELIGIBLE_FOR_PRESALE");
require(_presaleClaimed[msg.sender] < 1, "ALREADY_CLAIMED");
require(totalSupply() < PRESALE_SUPPLY, "PRESALE_SOLD_OUT");
require(totalSupply() + quantity <= PRESALE_SUPPLY, "EXCEEDS_PRESALE_SUPPLY");
require(PRICE * quantity == msg.value, "INVALID_ETH_AMOUNT");
for (uint256 i = 0; i < quantity; i++) {
_presaleClaimed[msg.sender] += 1;
_safeMint(msg.sender, totalSupply() + 1);
}
}
function mint(uint256 quantity) external payable onlyPublicSale {
require(tx.origin == msg.sender, "GO_AWAY_BOT_ORIGIN");
require(!isDelegatedCall(), "GO_AWAY_BOT_DELEGATED");
require(!isContractCall(msg.sender), "GO_AWAY_BOT_CONTRACT");
require(totalSupply() < MAX_SUPPLY, "SOLD_OUT");
require(quantity > 0, "QUANTITY_CANNOT_BE_ZERO");
require(quantity <= MAX_PER_TX, "EXCEEDS_MAX_MINT");
require(totalSupply() + quantity <= MAX_SUPPLY, "EXCEEDS_MAX_SUPPLY");
require(_totalClaimed[msg.sender] + quantity <= MAX_PER_WALLET_PUBLIC, "EXCEEDS_MAX_ALLOWANCE");
require(PRICE * quantity == msg.value, "INVALID_ETH_AMOUNT");
for (uint256 i = 0; i < quantity; i++) {
_totalClaimed[msg.sender] += 1;
_safeMint(msg.sender, totalSupply() + 1);
}
}
// Base URI Functions
// ------------------------------------------------------------------------
function setContractURI(string calldata URI) external onlyOwner {
_contractURI = URI;
emit ContractURIChanged(URI);
}
function contractURI() public view returns (string memory) {
return _contractURI;
}
function setBaseTokenURI(string calldata URI) external onlyOwner {
_baseTokenURI = URI;
emit BaseTokenURIChanged(URI);
}
function baseTokenURI() public view returns (string memory) {
return _baseTokenURI;
}
function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) {
require(_exists(tokenId), "Cannot query non-existent token");
return string(abi.encodePacked(_baseTokenURI, tokenId.toString()));
}
// Withdrawal functions
// ------------------------------------------------------------------------
function withdrawAll() external onlyOwner {
uint _a1amount = address(this).balance * 20/100;
uint _a2amount = address(this).balance * 20/100;
uint _a3amount = address(this).balance * 20/100;
uint _a4amount = address(this).balance * 10/100;
uint _a5amount = address(this).balance * 14/100;
uint _a6amount = address(this).balance * 2/100;
uint _a7amount = address(this).balance * 10/100;
uint _a8amount = address(this).balance * 4/100;
require(payable(_a1).send(_a1amount), "FAILED_TO_SEND_TO_A1");
require(payable(_a2).send(_a2amount), "FAILED_TO_SEND_TO_A2");
require(payable(_a3).send(_a3amount), "FAILED_TO_SEND_TO_A3");
require(payable(_a4).send(_a4amount), "FAILED_TO_SEND_TO_A4");
require(payable(_a5).send(_a5amount), "FAILED_TO_SEND_TO_A5");
require(payable(_a6).send(_a6amount), "FAILED_TO_SEND_TO_A6");
require(payable(_a7).send(_a7amount), "FAILED_TO_SEND_TO_A7");
require(payable(_a8).send(_a8amount), "FAILED_TO_SEND_TO_A8");
}
function emergencyWithdraw() external onlyOwner {
payable(_a3).transfer(address(this).balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../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 "../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 "../../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 "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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);
}
| Withdrawal functions ------------------------------------------------------------------------ | function withdrawAll() external onlyOwner {
uint _a1amount = address(this).balance * 20/100;
uint _a2amount = address(this).balance * 20/100;
uint _a3amount = address(this).balance * 20/100;
uint _a4amount = address(this).balance * 10/100;
uint _a5amount = address(this).balance * 14/100;
uint _a6amount = address(this).balance * 2/100;
uint _a7amount = address(this).balance * 10/100;
uint _a8amount = address(this).balance * 4/100;
require(payable(_a1).send(_a1amount), "FAILED_TO_SEND_TO_A1");
require(payable(_a2).send(_a2amount), "FAILED_TO_SEND_TO_A2");
require(payable(_a3).send(_a3amount), "FAILED_TO_SEND_TO_A3");
require(payable(_a4).send(_a4amount), "FAILED_TO_SEND_TO_A4");
require(payable(_a5).send(_a5amount), "FAILED_TO_SEND_TO_A5");
require(payable(_a6).send(_a6amount), "FAILED_TO_SEND_TO_A6");
require(payable(_a7).send(_a7amount), "FAILED_TO_SEND_TO_A7");
require(payable(_a8).send(_a8amount), "FAILED_TO_SEND_TO_A8");
}
| 14,431,340 | [
1,
1190,
9446,
287,
4186,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
598,
9446,
1595,
1435,
3903,
1338,
5541,
288,
203,
3639,
2254,
389,
69,
21,
8949,
273,
1758,
12,
2211,
2934,
12296,
380,
4200,
19,
6625,
31,
203,
3639,
2254,
389,
69,
22,
8949,
273,
1758,
12,
2211,
2934,
12296,
380,
4200,
19,
6625,
31,
203,
3639,
2254,
389,
69,
23,
8949,
273,
1758,
12,
2211,
2934,
12296,
380,
4200,
19,
6625,
31,
203,
3639,
2254,
389,
69,
24,
8949,
273,
1758,
12,
2211,
2934,
12296,
380,
1728,
19,
6625,
31,
203,
3639,
2254,
389,
69,
25,
8949,
273,
1758,
12,
2211,
2934,
12296,
380,
5045,
19,
6625,
31,
203,
3639,
2254,
389,
69,
26,
8949,
273,
1758,
12,
2211,
2934,
12296,
380,
576,
19,
6625,
31,
203,
3639,
2254,
389,
69,
27,
8949,
273,
1758,
12,
2211,
2934,
12296,
380,
1728,
19,
6625,
31,
203,
3639,
2254,
389,
69,
28,
8949,
273,
1758,
12,
2211,
2934,
12296,
380,
1059,
19,
6625,
31,
203,
203,
3639,
2583,
12,
10239,
429,
24899,
69,
21,
2934,
4661,
24899,
69,
21,
8949,
3631,
315,
11965,
67,
4296,
67,
21675,
67,
4296,
67,
37,
21,
8863,
203,
3639,
2583,
12,
10239,
429,
24899,
69,
22,
2934,
4661,
24899,
69,
22,
8949,
3631,
315,
11965,
67,
4296,
67,
21675,
67,
4296,
67,
37,
22,
8863,
203,
3639,
2583,
12,
10239,
429,
24899,
69,
23,
2934,
4661,
24899,
69,
23,
8949,
3631,
315,
11965,
67,
4296,
67,
21675,
67,
4296,
67,
37,
23,
8863,
203,
3639,
2583,
12,
10239,
429,
24899,
69,
24,
2934,
4661,
24899,
69,
24,
8949,
2
]
|
pragma solidity ^0.4.24;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract DavinCoin {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = 18000000000000000000000000; // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = "DavinCoin"; // Set the name for display purposes
symbol = "DVC" ; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
} | Update total supply with the decimal amount
| totalSupply = 18000000000000000000000000; | 14,971,680 | [
1,
1891,
2078,
14467,
598,
326,
6970,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2078,
3088,
1283,
273,
6549,
12648,
12648,
12648,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2020-07-02
*/
pragma solidity 0.5.16;
interface MassetStructs {
/** @dev Stores high level basket info */
struct Basket {
/** @dev Array of Bassets currently active */
Basset[] bassets;
/** @dev Max number of bAssets that can be present in any Basket */
uint8 maxBassets;
/** @dev Some bAsset is undergoing re-collateralisation */
bool undergoingRecol;
/**
* @dev In the event that we do not raise enough funds from the auctioning of a failed Basset,
* The Basket is deemed as failed, and is undercollateralised to a certain degree.
* The collateralisation ratio is used to calc Masset burn rate.
*/
bool failed;
uint256 collateralisationRatio;
}
/** @dev Stores bAsset info. The struct takes 5 storage slots per Basset */
struct Basset {
/** @dev Address of the bAsset */
address addr;
/** @dev Status of the basset, */
BassetStatus status; // takes uint8 datatype (1 byte) in storage
/** @dev An ERC20 can charge transfer fee, for example USDT, DGX tokens. */
bool isTransferFeeCharged; // takes a byte in storage
/**
* @dev 1 Basset * ratio / ratioScale == x Masset (relative value)
* If ratio == 10e8 then 1 bAsset = 10 mAssets
* A ratio is divised as 10^(18-tokenDecimals) * measurementMultiple(relative value of 1 base unit)
*/
uint256 ratio;
/** @dev Target weights of the Basset (100% == 1e18) */
uint256 maxWeight;
/** @dev Amount of the Basset that is held in Collateral */
uint256 vaultBalance;
}
/** @dev Status of the Basset - has it broken its peg? */
enum BassetStatus {
Default,
Normal,
BrokenBelowPeg,
BrokenAbovePeg,
Blacklisted,
Liquidating,
Liquidated,
Failed
}
/** @dev Internal details on Basset */
struct BassetDetails {
Basset bAsset;
address integrator;
uint8 index;
}
/** @dev All details needed to Forge with multiple bAssets */
struct ForgePropsMulti {
bool isValid; // Flag to signify that forge bAssets have passed validity check
Basset[] bAssets;
address[] integrators;
uint8[] indexes;
}
/** @dev All details needed for proportionate Redemption */
struct RedeemPropsMulti {
uint256 colRatio;
Basset[] bAssets;
address[] integrators;
uint8[] indexes;
}
}
contract IMasset is MassetStructs {
/** @dev Calc interest */
function collectInterest() external returns (uint256 massetMinted, uint256 newTotalSupply);
/** @dev Minting */
function mint(address _basset, uint256 _bassetQuantity)
external returns (uint256 massetMinted);
function mintTo(address _basset, uint256 _bassetQuantity, address _recipient)
external returns (uint256 massetMinted);
function mintMulti(address[] calldata _bAssets, uint256[] calldata _bassetQuantity, address _recipient)
external returns (uint256 massetMinted);
/** @dev Swapping */
function swap( address _input, address _output, uint256 _quantity, address _recipient)
external returns (uint256 output);
function getSwapOutput( address _input, address _output, uint256 _quantity)
external view returns (bool, string memory, uint256 output);
/** @dev Redeeming */
function redeem(address _basset, uint256 _bassetQuantity)
external returns (uint256 massetRedeemed);
function redeemTo(address _basset, uint256 _bassetQuantity, address _recipient)
external returns (uint256 massetRedeemed);
function redeemMulti(address[] calldata _bAssets, uint256[] calldata _bassetQuantities, address _recipient)
external returns (uint256 massetRedeemed);
function redeemMasset(uint256 _mAssetQuantity, address _recipient) external;
/** @dev Setters for the Manager or Gov to update module info */
function upgradeForgeValidator(address _newForgeValidator) external;
/** @dev Setters for Gov to set system params */
function setSwapFee(uint256 _swapFee) external;
/** @dev Getters */
function getBasketManager() external view returns(address);
}
interface ISavingsContract {
/** @dev Manager privs */
function depositInterest(uint256 _amount) external;
/** @dev Saver privs */
function depositSavings(uint256 _amount) external returns (uint256 creditsIssued);
function redeem(uint256 _amount) external returns (uint256 massetReturned);
}
interface ISavingsManager {
/** @dev Admin privs */
function withdrawUnallocatedInterest(address _mAsset, address _recipient) external;
/** @dev Public privs */
function collectAndDistributeInterest(address _mAsset) external;
}
contract ModuleKeys {
// Governance
// ===========
// Phases
// keccak256("Governance"); // 2.x
bytes32 internal constant KEY_GOVERNANCE = 0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d;
//keccak256("Staking"); // 1.2
bytes32 internal constant KEY_STAKING = 0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034;
//keccak256("ProxyAdmin"); // 1.0
bytes32 internal constant KEY_PROXY_ADMIN = 0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1;
// mStable
// =======
// keccak256("OracleHub"); // 1.2
bytes32 internal constant KEY_ORACLE_HUB = 0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040;
// keccak256("Manager"); // 1.2
bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f;
//keccak256("Recollateraliser"); // 2.x
bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f;
//keccak256("MetaToken"); // 1.1
bytes32 internal constant KEY_META_TOKEN = 0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2;
// keccak256("SavingsManager"); // 1.0
bytes32 internal constant KEY_SAVINGS_MANAGER = 0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1;
}
interface INexus {
function governor() external view returns (address);
function getModule(bytes32 key) external view returns (address);
function proposeModule(bytes32 _key, address _addr) external;
function cancelProposedModule(bytes32 _key) external;
function acceptProposedModule(bytes32 _key) external;
function acceptProposedModules(bytes32[] calldata _keys) external;
function requestLockModule(bytes32 _key) external;
function cancelLockModule(bytes32 _key) external;
function lockModule(bytes32 _key) external;
}
contract Module is ModuleKeys {
INexus public nexus;
/**
* @dev Initialises the Module by setting publisher addresses,
* and reading all available system module information
*/
constructor(address _nexus) internal {
require(_nexus != address(0), "Nexus is zero address");
nexus = INexus(_nexus);
}
/**
* @dev Modifier to allow function calls only from the Governor.
*/
modifier onlyGovernor() {
require(msg.sender == _governor(), "Only governor can execute");
_;
}
/**
* @dev Modifier to allow function calls only from the Governance.
* Governance is either Governor address or Governance address.
*/
modifier onlyGovernance() {
require(
msg.sender == _governor() || msg.sender == _governance(),
"Only governance can execute"
);
_;
}
/**
* @dev Modifier to allow function calls only from the ProxyAdmin.
*/
modifier onlyProxyAdmin() {
require(
msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute"
);
_;
}
/**
* @dev Modifier to allow function calls only from the Manager.
*/
modifier onlyManager() {
require(msg.sender == _manager(), "Only manager can execute");
_;
}
/**
* @dev Returns Governor address from the Nexus
* @return Address of Governor Contract
*/
function _governor() internal view returns (address) {
return nexus.governor();
}
/**
* @dev Returns Governance Module address from the Nexus
* @return Address of the Governance (Phase 2)
*/
function _governance() internal view returns (address) {
return nexus.getModule(KEY_GOVERNANCE);
}
/**
* @dev Return Staking Module address from the Nexus
* @return Address of the Staking Module contract
*/
function _staking() internal view returns (address) {
return nexus.getModule(KEY_STAKING);
}
/**
* @dev Return ProxyAdmin Module address from the Nexus
* @return Address of the ProxyAdmin Module contract
*/
function _proxyAdmin() internal view returns (address) {
return nexus.getModule(KEY_PROXY_ADMIN);
}
/**
* @dev Return MetaToken Module address from the Nexus
* @return Address of the MetaToken Module contract
*/
function _metaToken() internal view returns (address) {
return nexus.getModule(KEY_META_TOKEN);
}
/**
* @dev Return OracleHub Module address from the Nexus
* @return Address of the OracleHub Module contract
*/
function _oracleHub() internal view returns (address) {
return nexus.getModule(KEY_ORACLE_HUB);
}
/**
* @dev Return Manager Module address from the Nexus
* @return Address of the Manager Module contract
*/
function _manager() internal view returns (address) {
return nexus.getModule(KEY_MANAGER);
}
/**
* @dev Return SavingsManager Module address from the Nexus
* @return Address of the SavingsManager Module contract
*/
function _savingsManager() internal view returns (address) {
return nexus.getModule(KEY_SAVINGS_MANAGER);
}
/**
* @dev Return Recollateraliser Module address from the Nexus
* @return Address of the Recollateraliser Module contract (Phase 2)
*/
function _recollateraliser() internal view returns (address) {
return nexus.getModule(KEY_RECOLLATERALISER);
}
}
contract PausableModule is Module {
/**
* @dev Emitted when the pause is triggered by Governor
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by Governor
*/
event Unpaused(address account);
bool private _paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Initializes the contract in unpaused state.
* Hooks into the Module to give the Governor ability to pause
* @param _nexus Nexus contract address
*/
constructor (address _nexus) internal Module(_nexus) {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
* @return Returns `true` when paused, otherwise `false`
*/
function paused() external view returns (bool) {
return _paused;
}
/**
* @dev Called by the Governor to pause, triggers stopped state.
*/
function pause() external onlyGovernor whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev Called by Governor to unpause, returns to normal state.
*/
function unpause() external onlyGovernor whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
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 (block.timestamp > 0) { // Return data is optional //injected CONTRACT AFFECTED BY MINERS
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library StableMath {
using SafeMath for uint256;
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/**
* @notice Token Ratios are used when converting between units of bAsset, mAsset and MTA
* Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold)
* @dev bAsset ratio unit for use in exact calculations,
* where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit
*/
uint256 private constant RATIO_SCALE = 1e8;
/**
* @dev Provides an interface to the scaling unit
* @return Scaling unit (1e18 or 1 * 10**18)
*/
function getFullScale() internal pure returns (uint256) {
return FULL_SCALE;
}
/**
* @dev Provides an interface to the ratio unit
* @return Ratio scale unit (1e8 or 1 * 10**8)
*/
function getRatioScale() internal pure returns (uint256) {
return RATIO_SCALE;
}
/**
* @dev Scales a given integer to the power of the full scale.
* @param x Simple uint256 to scale
* @return Scaled value a to an exact number
*/
function scaleInteger(uint256 x)
internal
pure
returns (uint256)
{
return x.mul(FULL_SCALE);
}
/***************************************
PRECISE ARITHMETIC
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(uint256 x, uint256 y, uint256 scale)
internal
pure
returns (uint256)
{
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e38 / 1e18 = 9e18
return z.div(scale);
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
/***************************************
RATIO FUNCS
****************************************/
/**
* @dev Multiplies and truncates a token ratio, essentially flooring the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand operand to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the ratio scale
*/
function mulRatioTruncate(uint256 x, uint256 ratio)
internal
pure
returns (uint256 c)
{
return mulTruncateScale(x, ratio, RATIO_SCALE);
}
/**
* @dev Multiplies and truncates a token ratio, rounding up the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand input to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the shared
* ratio scale, rounded up to the closest base unit.
*/
function mulRatioTruncateCeil(uint256 x, uint256 ratio)
internal
pure
returns (uint256)
{
// e.g. How much mAsset should I burn for this bAsset (x)?
// 1e18 * 1e8 = 1e26
uint256 scaled = x.mul(ratio);
// 1e26 + 9.99e7 = 100..00.999e8
uint256 ceil = scaled.add(RATIO_SCALE.sub(1));
// return 100..00.999e8 / 1e8 = 1e18
return ceil.div(RATIO_SCALE);
}
/**
* @dev Precisely divides two ratioed units, by first scaling the left hand operand
* i.e. How much bAsset is this mAsset worth?
* @param x Left hand operand in division
* @param ratio bAsset ratio
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divRatioPrecisely(uint256 x, uint256 ratio)
internal
pure
returns (uint256 c)
{
// e.g. 1e14 * 1e8 = 1e22
uint256 y = x.mul(RATIO_SCALE);
// return 1e22 / 1e12 = 1e10
return y.div(ratio);
}
/***************************************
HELPERS
****************************************/
/**
* @dev Calculates minimum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Minimum of the two inputs
*/
function min(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return x > y ? y : x;
}
/**
* @dev Calculated maximum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Maximum of the two inputs
*/
function max(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return x > y ? x : y;
}
/**
* @dev Clamps a value to an upper bound
* @param x Left hand input
* @param upperBound Maximum possible value to return
* @return Input x clamped to a maximum value, upperBound
*/
function clamp(uint256 x, uint256 upperBound)
internal
pure
returns (uint256)
{
return x > upperBound ? upperBound : x;
}
}
/**
* @title SavingsManager
* @author Stability Labs Pty. Ltd.
* @notice Savings Manager collects interest from mAssets and sends them to the
* corresponding Savings Contract, performing some validation in the process.
* @dev VERSION: 1.1
* DATE: 2020-07-01
*/
contract SavingsManager is ISavingsManager, PausableModule {
using SafeMath for uint256;
using StableMath for uint256;
using SafeERC20 for IERC20;
// Core admin events
event SavingsContractAdded(address indexed mAsset, address savingsContract);
event SavingsContractUpdated(address indexed mAsset, address savingsContract);
event SavingsRateChanged(uint256 newSavingsRate);
// Interest collection
event InterestCollected(address indexed mAsset, uint256 interest, uint256 newTotalSupply, uint256 apy);
event InterestDistributed(address indexed mAsset, uint256 amountSent);
event InterestWithdrawnByGovernor(address indexed mAsset, address recipient, uint256 amount);
// Locations of each mAsset savings contract
mapping(address => ISavingsContract) public savingsContracts;
// Time at which last collection was made
mapping(address => uint256) public lastCollection;
// Amount of collected interest that will be sent to Savings Contract (100%)
uint256 private savingsRate = 1e18;
// Utils to help keep interest under check
uint256 constant private SECONDS_IN_YEAR = 365 days;
// Theoretical cap on APY to avoid excess inflation
uint256 constant private MAX_APY = 15e18;
uint256 constant private TEN_BPS = 1e15;
uint256 constant private THIRTY_MINUTES = 30 minutes;
constructor(
address _nexus,
address _mUSD,
address _savingsContract
)
public
PausableModule(_nexus)
{
_updateSavingsContract(_mUSD, _savingsContract);
emit SavingsContractAdded(_mUSD, _savingsContract);
}
/***************************************
STATE
****************************************/
/**
* @dev Adds a new savings contract
* @param _mAsset Address of underlying mAsset
* @param _savingsContract Address of the savings contract
*/
function addSavingsContract(address _mAsset, address _savingsContract)
external
onlyGovernor
{
require(address(savingsContracts[_mAsset]) == address(0), "Savings contract already exists");
_updateSavingsContract(_mAsset, _savingsContract);
emit SavingsContractAdded(_mAsset, _savingsContract);
}
/**
* @dev Updates an existing savings contract
* @param _mAsset Address of underlying mAsset
* @param _savingsContract Address of the savings contract
*/
function updateSavingsContract(address _mAsset, address _savingsContract)
external
onlyGovernor
{
require(address(savingsContracts[_mAsset]) != address(0), "Savings contract does not exist");
_updateSavingsContract(_mAsset, _savingsContract);
emit SavingsContractUpdated(_mAsset, _savingsContract);
}
function _updateSavingsContract(address _mAsset, address _savingsContract)
internal
{
require(_mAsset != address(0) && _savingsContract != address(0), "Must be valid address");
savingsContracts[_mAsset] = ISavingsContract(_savingsContract);
IERC20(_mAsset).safeApprove(address(_savingsContract), 0);
IERC20(_mAsset).safeApprove(address(_savingsContract), uint256(-1));
}
/**
* @dev Sets a new savings rate for interest distribution
* @param _savingsRate Rate of savings sent to SavingsContract (100% = 1e18)
*/
function setSavingsRate(uint256 _savingsRate)
external
onlyGovernor
{
// Greater than 90% upto 100%
require(_savingsRate > 9e17 && _savingsRate <= 1e18, "Must be a valid rate");
savingsRate = _savingsRate;
emit SavingsRateChanged(_savingsRate);
}
/***************************************
COLLECTION
****************************************/
/**
* @dev Collects interest from a target mAsset and distributes to the SavingsContract.
* Applies constraints such that the max APY since the last fee collection cannot
* exceed the "MAX_APY" variable.
* @param _mAsset mAsset for which the interest should be collected
*/
function collectAndDistributeInterest(address _mAsset)
external
whenNotPaused
{
ISavingsContract savingsContract = savingsContracts[_mAsset];
require(address(savingsContract) != address(0), "Must have a valid savings contract");
// Get collection details
uint256 previousCollection = lastCollection[_mAsset];
lastCollection[_mAsset] = now;
// 1. Collect the new interest from the mAsset
IMasset mAsset = IMasset(_mAsset);
(uint256 interestCollected, uint256 totalSupply) = mAsset.collectInterest();
if(block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
// 2. Validate that the interest has been collected and is within certain limits
require(
IERC20(_mAsset).balanceOf(address(this)) >= interestCollected,
"Must receive mUSD"
);
// Avoid division by 0 by adding a minimum elapsed time of 1 second
uint256 timeSinceLastCollection = StableMath.max(1, now.sub(previousCollection));
// e.g. day: (86400 * 1e18) / 3.154e7 = 2.74..e15
// e.g. 30 mins: (1800 * 1e18) / 3.154e7 = 5.7..e13
// e.g. epoch: (1593596907 * 1e18) / 3.154e7 = 50.4..e18
uint256 yearsSinceLastCollection =
timeSinceLastCollection.divPrecisely(SECONDS_IN_YEAR);
// Percentage increase in total supply
// e.g. (1e20 * 1e18) / 1e24 = 1e14 (or a 0.01% increase)
// e.g. (5e18 * 1e18) / 1.2e24 = 4.1667e12
// e.g. (1e19 * 1e18) / 1e21 = 1e16
uint256 oldSupply = totalSupply.sub(interestCollected);
uint256 percentageIncrease = interestCollected.divPrecisely(oldSupply);
// e.g. 0.01% (1e14 * 1e18) / 2.74..e15 = 3.65e16 or 3.65% apr
// e.g. (4.1667e12 * 1e18) / 5.7..e13 = 7.1e16 or 7.1% apr
// e.g. (1e16 * 1e18) / 50e18 = 2e14
uint256 extrapolatedAPY = percentageIncrease.divPrecisely(yearsSinceLastCollection);
// 2.1. If over 30 mins, extrapolate APY
if(block.timestamp > THIRTY_MINUTES) { //injected CONTRACT AFFECTED BY MINERS
require(extrapolatedAPY < MAX_APY, "Interest protected from inflating past maxAPY");
} else {
require(percentageIncrease < TEN_BPS, "Interest protected from inflating past 10 Bps");
}
emit InterestCollected(_mAsset, interestCollected, totalSupply, extrapolatedAPY);
// 3. Distribute the interest
// Calculate the share for savers (95e16 or 95%)
uint256 saversShare = interestCollected.mulTruncate(savingsRate);
// Call depositInterest on contract
savingsContract.depositInterest(saversShare);
emit InterestDistributed(_mAsset, saversShare);
} else {
emit InterestCollected(_mAsset, 0, totalSupply, 0);
}
}
/***************************************
MANAGEMENT
****************************************/
/**
* @dev Withdraws any unallocated interest, i.e. that which has been saved for use
* elsewhere in the system, based on the savingsRate
* @param _mAsset mAsset to collect from
* @param _recipient Address of mAsset recipient
*/
function withdrawUnallocatedInterest(address _mAsset, address _recipient)
external
onlyGovernor
{
IERC20 mAsset = IERC20(_mAsset);
uint256 balance = mAsset.balanceOf(address(this));
emit InterestWithdrawnByGovernor(_mAsset, _recipient, balance);
mAsset.safeTransfer(_recipient, balance);
}
} | * @dev Collects interest from a target mAsset and distributes to the SavingsContract. Applies constraints such that the max APY since the last fee collection cannot exceed the "MAX_APY" variable. @param _mAsset mAsset for which the interest should be collected/ Get collection details 1. Collect the new interest from the mAsset 2. Validate that the interest has been collected and is within certain limits Avoid division by 0 by adding a minimum elapsed time of 1 second e.g. day: (86400 * 1e18) / 3.154e7 = 2.74..e15 e.g. 30 mins: (1800 * 1e18) / 3.154e7 = 5.7..e13 e.g. epoch: (1593596907 * 1e18) / 3.154e7 = 50.4..e18 Percentage increase in total supply e.g. (1e20 * 1e18) / 1e24 = 1e14 (or a 0.01% increase) e.g. (5e18 * 1e18) / 1.2e24 = 4.1667e12 e.g. (1e19 * 1e18) / 1e21 = 1e16 e.g. 0.01% (1e14 * 1e18) / 2.74..e15 = 3.65e16 or 3.65% apr e.g. (4.1667e12 * 1e18) / 5.7..e13 = 7.1e16 or 7.1% apr e.g. (1e16 * 1e18) / 50e18 = 2e14 2.1. If over 30 mins, extrapolate APY | function collectAndDistributeInterest(address _mAsset)
external
whenNotPaused
{
ISavingsContract savingsContract = savingsContracts[_mAsset];
require(address(savingsContract) != address(0), "Must have a valid savings contract");
uint256 previousCollection = lastCollection[_mAsset];
lastCollection[_mAsset] = now;
IMasset mAsset = IMasset(_mAsset);
(uint256 interestCollected, uint256 totalSupply) = mAsset.collectInterest();
require(
IERC20(_mAsset).balanceOf(address(this)) >= interestCollected,
"Must receive mUSD"
);
uint256 timeSinceLastCollection = StableMath.max(1, now.sub(previousCollection));
uint256 yearsSinceLastCollection =
timeSinceLastCollection.divPrecisely(SECONDS_IN_YEAR);
uint256 oldSupply = totalSupply.sub(interestCollected);
uint256 percentageIncrease = interestCollected.divPrecisely(oldSupply);
uint256 extrapolatedAPY = percentageIncrease.divPrecisely(yearsSinceLastCollection);
require(extrapolatedAPY < MAX_APY, "Interest protected from inflating past maxAPY");
require(percentageIncrease < TEN_BPS, "Interest protected from inflating past 10 Bps");
}
emit InterestCollected(_mAsset, interestCollected, totalSupply, extrapolatedAPY);
emit InterestDistributed(_mAsset, saversShare);
emit InterestCollected(_mAsset, 0, totalSupply, 0);
| 12,681,959 | [
1,
28791,
16513,
628,
279,
1018,
312,
6672,
471,
1015,
1141,
358,
326,
348,
27497,
8924,
18,
1377,
1716,
5259,
6237,
4123,
716,
326,
943,
14410,
61,
3241,
326,
1142,
14036,
1849,
2780,
1377,
9943,
326,
315,
6694,
67,
2203,
61,
6,
2190,
18,
225,
389,
81,
6672,
4202,
312,
6672,
364,
1492,
326,
16513,
1410,
506,
12230,
19,
968,
1849,
3189,
404,
18,
9302,
326,
394,
16513,
628,
326,
312,
6672,
576,
18,
3554,
716,
326,
16513,
711,
2118,
12230,
471,
353,
3470,
8626,
8181,
17843,
16536,
635,
374,
635,
6534,
279,
5224,
9613,
813,
434,
404,
2205,
425,
18,
75,
18,
2548,
30,
261,
28,
1105,
713,
225,
404,
73,
2643,
13,
342,
890,
18,
29003,
73,
27,
273,
576,
18,
5608,
838,
73,
3600,
425,
18,
75,
18,
5196,
26381,
30,
261,
2643,
713,
225,
404,
73,
2643,
13,
342,
890,
18,
29003,
73,
27,
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,
565,
445,
3274,
1876,
1669,
887,
29281,
12,
2867,
389,
81,
6672,
13,
203,
3639,
3903,
203,
3639,
1347,
1248,
28590,
203,
565,
288,
203,
3639,
4437,
27497,
8924,
4087,
899,
8924,
273,
4087,
899,
20723,
63,
67,
81,
6672,
15533,
203,
3639,
2583,
12,
2867,
12,
87,
27497,
8924,
13,
480,
1758,
12,
20,
3631,
315,
10136,
1240,
279,
923,
4087,
899,
6835,
8863,
203,
203,
3639,
2254,
5034,
2416,
2532,
273,
1142,
2532,
63,
67,
81,
6672,
15533,
203,
3639,
1142,
2532,
63,
67,
81,
6672,
65,
273,
2037,
31,
203,
203,
3639,
6246,
9406,
312,
6672,
273,
6246,
9406,
24899,
81,
6672,
1769,
203,
3639,
261,
11890,
5034,
16513,
10808,
329,
16,
2254,
5034,
2078,
3088,
1283,
13,
273,
312,
6672,
18,
14676,
29281,
5621,
203,
203,
5411,
2583,
12,
203,
7734,
467,
654,
39,
3462,
24899,
81,
6672,
2934,
12296,
951,
12,
2867,
12,
2211,
3719,
1545,
16513,
10808,
329,
16,
203,
7734,
315,
10136,
6798,
312,
3378,
40,
6,
203,
5411,
11272,
203,
203,
5411,
2254,
5034,
813,
9673,
3024,
2532,
273,
934,
429,
10477,
18,
1896,
12,
21,
16,
2037,
18,
1717,
12,
11515,
2532,
10019,
203,
203,
5411,
2254,
5034,
11387,
9673,
3024,
2532,
273,
203,
7734,
813,
9673,
3024,
2532,
18,
2892,
1386,
71,
291,
2357,
12,
11609,
67,
706,
67,
15137,
1769,
203,
203,
5411,
2254,
5034,
1592,
3088,
1283,
273,
2078,
3088,
1283,
18,
1717,
12,
2761,
395,
10808,
329,
1769,
203,
5411,
2254,
5034,
11622,
382,
11908,
273,
16513,
10808,
329,
18,
2892,
2
]
|
./partial_match/3/0x16E3b323E02F3E8f7Ad3e6251fA261035668DcE9/sources/lifeStage.sol | * @dev To lock/unlock the contract @param _lockStatus status in bool/ | function contractLock(bool _lockStatus) public returns (bool) {
require(msg.sender == owner, "Invalid ownerWallet");
lockStatus = _lockStatus;
return true;
}
| 5,301,449 | [
1,
774,
2176,
19,
26226,
326,
6835,
225,
389,
739,
1482,
225,
1267,
316,
1426,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
6835,
2531,
12,
6430,
389,
739,
1482,
13,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3410,
16,
315,
1941,
3410,
16936,
8863,
203,
203,
3639,
2176,
1482,
273,
389,
739,
1482,
31,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
377,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-02-02
*/
/// SurplusAuctionHouse.sol
// Copyright (C) 2018 Rain <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pragma solidity 0.6.7;
abstract contract SAFEEngineLike {
function transferInternalCoins(address,address,uint256) virtual external;
function coinBalance(address) virtual external view returns (uint256);
function approveSAFEModification(address) virtual external;
function denySAFEModification(address) virtual external;
}
abstract contract TokenLike {
function approve(address, uint256) virtual public returns (bool);
function balanceOf(address) virtual public view returns (uint256);
function move(address,address,uint256) virtual external;
function burn(address,uint256) virtual external;
}
/*
This thing lets you auction some coins in return for protocol tokens that are then burnt
*/
contract BurningSurplusAuctionHouse {
// --- Auth ---
mapping (address => uint256) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
/**
* @notice Remove auth from an account
* @param account Account to remove auth from
*/
function removeAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 0;
emit RemoveAuthorization(account);
}
/**
* @notice Checks whether msg.sender can call an authed function
**/
modifier isAuthorized {
require(authorizedAccounts[msg.sender] == 1, "BurningSurplusAuctionHouse/account-not-authorized");
_;
}
// --- Data ---
struct Bid {
// Bid size (how many protocol tokens are offered per system coins sold)
uint256 bidAmount; // [wad]
// How many system coins are sold in an auction
uint256 amountToSell; // [rad]
// Who the high bidder is
address highBidder;
// When the latest bid expires and the auction can be settled
uint48 bidExpiry; // [unix epoch time]
// Hard deadline for the auction after which no more bids can be placed
uint48 auctionDeadline; // [unix epoch time]
}
// Bid data for each separate auction
mapping (uint256 => Bid) public bids;
// SAFE database
SAFEEngineLike public safeEngine;
// Protocol token address
TokenLike public protocolToken;
uint256 constant ONE = 1.00E18; // [wad]
// Minimum bid increase compared to the last bid in order to take the new one in consideration
uint256 public bidIncrease = 1.05E18; // [wad]
// How long the auction lasts after a new bid is submitted
uint48 public bidDuration = 3 hours; // [seconds]
// Total length of the auction
uint48 public totalAuctionLength = 2 days; // [seconds]
// Number of auctions started up until now
uint256 public auctionsStarted = 0;
// Whether the contract is settled or not
uint256 public contractEnabled;
bytes32 public constant AUCTION_HOUSE_TYPE = bytes32("SURPLUS");
bytes32 public constant SURPLUS_AUCTION_TYPE = bytes32("BURNING");
// --- Events ---
event AddAuthorization(address account);
event RemoveAuthorization(address account);
event ModifyParameters(bytes32 parameter, uint256 data);
event RestartAuction(uint256 id, uint256 auctionDeadline);
event IncreaseBidSize(uint256 id, address highBidder, uint256 amountToBuy, uint256 bid, uint256 bidExpiry);
event StartAuction(
uint256 indexed id,
uint256 auctionsStarted,
uint256 amountToSell,
uint256 initialBid,
uint256 auctionDeadline
);
event SettleAuction(uint256 indexed id);
event DisableContract();
event TerminateAuctionPrematurely(uint256 indexed id, address sender, address highBidder, uint256 bidAmount);
// --- Init ---
constructor(address safeEngine_, address protocolToken_) public {
authorizedAccounts[msg.sender] = 1;
safeEngine = SAFEEngineLike(safeEngine_);
protocolToken = TokenLike(protocolToken_);
contractEnabled = 1;
emit AddAuthorization(msg.sender);
}
// --- Math ---
function addUint48(uint48 x, uint48 y) internal pure returns (uint48 z) {
require((z = x + y) >= x, "BurningSurplusAuctionHouse/add-uint48-overflow");
}
function multiply(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "BurningSurplusAuctionHouse/mul-overflow");
}
// --- Admin ---
/**
* @notice Modify auction parameters
* @param parameter The name of the parameter modified
* @param data New value for the parameter
*/
function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {
if (parameter == "bidIncrease") bidIncrease = data;
else if (parameter == "bidDuration") bidDuration = uint48(data);
else if (parameter == "totalAuctionLength") totalAuctionLength = uint48(data);
else revert("BurningSurplusAuctionHouse/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
// --- Auction ---
/**
* @notice Start a new surplus auction
* @param amountToSell Total amount of system coins to sell (rad)
* @param initialBid Initial protocol token bid (wad)
*/
function startAuction(uint256 amountToSell, uint256 initialBid) external isAuthorized returns (uint256 id) {
require(contractEnabled == 1, "BurningSurplusAuctionHouse/contract-not-enabled");
require(auctionsStarted < uint256(-1), "BurningSurplusAuctionHouse/overflow");
id = ++auctionsStarted;
bids[id].bidAmount = initialBid;
bids[id].amountToSell = amountToSell;
bids[id].highBidder = msg.sender;
bids[id].auctionDeadline = addUint48(uint48(now), totalAuctionLength);
safeEngine.transferInternalCoins(msg.sender, address(this), amountToSell);
emit StartAuction(id, auctionsStarted, amountToSell, initialBid, bids[id].auctionDeadline);
}
/**
* @notice Restart an auction if no bids were submitted for it
* @param id ID of the auction to restart
*/
function restartAuction(uint256 id) external {
require(bids[id].auctionDeadline < now, "BurningSurplusAuctionHouse/not-finished");
require(bids[id].bidExpiry == 0, "BurningSurplusAuctionHouse/bid-already-placed");
bids[id].auctionDeadline = addUint48(uint48(now), totalAuctionLength);
emit RestartAuction(id, bids[id].auctionDeadline);
}
/**
* @notice Submit a higher protocol token bid for the same amount of system coins
* @param id ID of the auction you want to submit the bid for
* @param amountToBuy Amount of system coins to buy (rad)
* @param bid New bid submitted (wad)
*/
function increaseBidSize(uint256 id, uint256 amountToBuy, uint256 bid) external {
require(contractEnabled == 1, "BurningSurplusAuctionHouse/contract-not-enabled");
require(bids[id].highBidder != address(0), "BurningSurplusAuctionHouse/high-bidder-not-set");
require(bids[id].bidExpiry > now || bids[id].bidExpiry == 0, "BurningSurplusAuctionHouse/bid-already-expired");
require(bids[id].auctionDeadline > now, "BurningSurplusAuctionHouse/auction-already-expired");
require(amountToBuy == bids[id].amountToSell, "BurningSurplusAuctionHouse/amounts-not-matching");
require(bid > bids[id].bidAmount, "BurningSurplusAuctionHouse/bid-not-higher");
require(multiply(bid, ONE) >= multiply(bidIncrease, bids[id].bidAmount), "BurningSurplusAuctionHouse/insufficient-increase");
if (msg.sender != bids[id].highBidder) {
protocolToken.move(msg.sender, bids[id].highBidder, bids[id].bidAmount);
bids[id].highBidder = msg.sender;
}
protocolToken.move(msg.sender, address(this), bid - bids[id].bidAmount);
bids[id].bidAmount = bid;
bids[id].bidExpiry = addUint48(uint48(now), bidDuration);
emit IncreaseBidSize(id, msg.sender, amountToBuy, bid, bids[id].bidExpiry);
}
/**
* @notice Settle/finish an auction
* @param id ID of the auction to settle
*/
function settleAuction(uint256 id) external {
require(contractEnabled == 1, "BurningSurplusAuctionHouse/contract-not-enabled");
require(bids[id].bidExpiry != 0 && (bids[id].bidExpiry < now || bids[id].auctionDeadline < now), "BurningSurplusAuctionHouse/not-finished");
safeEngine.transferInternalCoins(address(this), bids[id].highBidder, bids[id].amountToSell);
protocolToken.burn(address(this), bids[id].bidAmount);
delete bids[id];
emit SettleAuction(id);
}
/**
* @notice Disable the auction house (usually called by AccountingEngine)
**/
function disableContract() external isAuthorized {
contractEnabled = 0;
safeEngine.transferInternalCoins(address(this), msg.sender, safeEngine.coinBalance(address(this)));
emit DisableContract();
}
/**
* @notice Terminate an auction prematurely.
* @param id ID of the auction to settle/terminate
*/
function terminateAuctionPrematurely(uint256 id) external {
require(contractEnabled == 0, "BurningSurplusAuctionHouse/contract-still-enabled");
require(bids[id].highBidder != address(0), "BurningSurplusAuctionHouse/high-bidder-not-set");
protocolToken.move(address(this), bids[id].highBidder, bids[id].bidAmount);
emit TerminateAuctionPrematurely(id, msg.sender, bids[id].highBidder, bids[id].bidAmount);
delete bids[id];
}
} | --- Admin ---* @notice Modify auction parameters @param parameter The name of the parameter modified @param data New value for the parameter/ | function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {
if (parameter == "bidIncrease") bidIncrease = data;
else if (parameter == "bidDuration") bidDuration = uint48(data);
else if (parameter == "totalAuctionLength") totalAuctionLength = uint48(data);
else revert("BurningSurplusAuctionHouse/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
| 1,095,940 | [
1,
6062,
7807,
9948,
225,
9518,
279,
4062,
1472,
225,
1569,
1021,
508,
434,
326,
1569,
4358,
225,
501,
1166,
460,
364,
326,
1569,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
5612,
2402,
12,
3890,
1578,
1569,
16,
2254,
5034,
501,
13,
3903,
353,
15341,
288,
203,
3639,
309,
261,
6775,
422,
315,
19773,
382,
11908,
7923,
9949,
382,
11908,
273,
501,
31,
203,
3639,
469,
309,
261,
6775,
422,
315,
19773,
5326,
7923,
9949,
5326,
273,
2254,
8875,
12,
892,
1769,
203,
3639,
469,
309,
261,
6775,
422,
315,
4963,
37,
4062,
1782,
7923,
2078,
37,
4062,
1782,
273,
2254,
8875,
12,
892,
1769,
203,
3639,
469,
15226,
2932,
38,
321,
310,
7719,
10103,
37,
4062,
44,
3793,
19,
17042,
17,
318,
12916,
17,
891,
8863,
203,
3639,
3626,
9518,
2402,
12,
6775,
16,
501,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2021-06-25
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// 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);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/InterestCalculator.sol
pragma solidity ^0.6.12;
contract InterestCalculator {
using SafeMath for uint;
uint private constant MAX_DAYS = 365;
function _initCumulativeInterestForDays() internal pure returns(uint[] memory) {
uint[] memory cumulativeInterestForDays = new uint[](MAX_DAYS.add(1));
cumulativeInterestForDays[0] = 0;
cumulativeInterestForDays[1] = 1;
cumulativeInterestForDays[2] = 2;
cumulativeInterestForDays[3] = 3;
cumulativeInterestForDays[4] = 4;
cumulativeInterestForDays[5] = 6;
cumulativeInterestForDays[6] = 8;
cumulativeInterestForDays[7] = 11;
cumulativeInterestForDays[8] = 14;
cumulativeInterestForDays[9] = 17;
cumulativeInterestForDays[10] = 21;
cumulativeInterestForDays[11] = 25;
cumulativeInterestForDays[12] = 30;
cumulativeInterestForDays[13] = 35;
cumulativeInterestForDays[14] = 40;
cumulativeInterestForDays[15] = 46;
cumulativeInterestForDays[16] = 52;
cumulativeInterestForDays[17] = 58;
cumulativeInterestForDays[18] = 65;
cumulativeInterestForDays[19] = 72;
cumulativeInterestForDays[20] = 80;
cumulativeInterestForDays[21] = 88;
cumulativeInterestForDays[22] = 96;
cumulativeInterestForDays[23] = 105;
cumulativeInterestForDays[24] = 114;
cumulativeInterestForDays[25] = 124;
cumulativeInterestForDays[26] = 134;
cumulativeInterestForDays[27] = 144;
cumulativeInterestForDays[28] = 155;
cumulativeInterestForDays[29] = 166;
cumulativeInterestForDays[30] = 178;
cumulativeInterestForDays[31] = 190;
cumulativeInterestForDays[32] = 202;
cumulativeInterestForDays[33] = 215;
cumulativeInterestForDays[34] = 228;
cumulativeInterestForDays[35] = 242;
cumulativeInterestForDays[36] = 256;
cumulativeInterestForDays[37] = 271;
cumulativeInterestForDays[38] = 286;
cumulativeInterestForDays[39] = 301;
cumulativeInterestForDays[40] = 317;
cumulativeInterestForDays[41] = 333;
cumulativeInterestForDays[42] = 350;
cumulativeInterestForDays[43] = 367;
cumulativeInterestForDays[44] = 385;
cumulativeInterestForDays[45] = 403;
cumulativeInterestForDays[46] = 421;
cumulativeInterestForDays[47] = 440;
cumulativeInterestForDays[48] = 459;
cumulativeInterestForDays[49] = 479;
cumulativeInterestForDays[50] = 499;
cumulativeInterestForDays[51] = 520;
cumulativeInterestForDays[52] = 541;
cumulativeInterestForDays[53] = 563;
cumulativeInterestForDays[54] = 585;
cumulativeInterestForDays[55] = 607;
cumulativeInterestForDays[56] = 630;
cumulativeInterestForDays[57] = 653;
cumulativeInterestForDays[58] = 677;
cumulativeInterestForDays[59] = 701;
cumulativeInterestForDays[60] = 726;
cumulativeInterestForDays[61] = 751;
cumulativeInterestForDays[62] = 777;
cumulativeInterestForDays[63] = 803;
cumulativeInterestForDays[64] = 830;
cumulativeInterestForDays[65] = 857;
cumulativeInterestForDays[66] = 884;
cumulativeInterestForDays[67] = 912;
cumulativeInterestForDays[68] = 940;
cumulativeInterestForDays[69] = 969;
cumulativeInterestForDays[70] = 998;
cumulativeInterestForDays[71] = 1028;
cumulativeInterestForDays[72] = 1058;
cumulativeInterestForDays[73] = 1089;
cumulativeInterestForDays[74] = 1120;
cumulativeInterestForDays[75] = 1152;
cumulativeInterestForDays[76] = 1184;
cumulativeInterestForDays[77] = 1217;
cumulativeInterestForDays[78] = 1250;
cumulativeInterestForDays[79] = 1284;
cumulativeInterestForDays[80] = 1318;
cumulativeInterestForDays[81] = 1353;
cumulativeInterestForDays[82] = 1388;
cumulativeInterestForDays[83] = 1424;
cumulativeInterestForDays[84] = 1460;
cumulativeInterestForDays[85] = 1497;
cumulativeInterestForDays[86] = 1534;
cumulativeInterestForDays[87] = 1572;
cumulativeInterestForDays[88] = 1610;
cumulativeInterestForDays[89] = 1649;
cumulativeInterestForDays[90] = 1688;
cumulativeInterestForDays[91] = 1728;
cumulativeInterestForDays[92] = 1768;
cumulativeInterestForDays[93] = 1809;
cumulativeInterestForDays[94] = 1850;
cumulativeInterestForDays[95] = 1892;
cumulativeInterestForDays[96] = 1934;
cumulativeInterestForDays[97] = 1977;
cumulativeInterestForDays[98] = 2020;
cumulativeInterestForDays[99] = 2064;
cumulativeInterestForDays[100] = 2108;
cumulativeInterestForDays[101] = 2153;
cumulativeInterestForDays[102] = 2199;
cumulativeInterestForDays[103] = 2245;
cumulativeInterestForDays[104] = 2292;
cumulativeInterestForDays[105] = 2339;
cumulativeInterestForDays[106] = 2387;
cumulativeInterestForDays[107] = 2435;
cumulativeInterestForDays[108] = 2484;
cumulativeInterestForDays[109] = 2533;
cumulativeInterestForDays[110] = 2583;
cumulativeInterestForDays[111] = 2633;
cumulativeInterestForDays[112] = 2684;
cumulativeInterestForDays[113] = 2736;
cumulativeInterestForDays[114] = 2788;
cumulativeInterestForDays[115] = 2841;
cumulativeInterestForDays[116] = 2894;
cumulativeInterestForDays[117] = 2948;
cumulativeInterestForDays[118] = 3002;
cumulativeInterestForDays[119] = 3057;
cumulativeInterestForDays[120] = 3113;
cumulativeInterestForDays[121] = 3169;
cumulativeInterestForDays[122] = 3226;
cumulativeInterestForDays[123] = 3283;
cumulativeInterestForDays[124] = 3341;
cumulativeInterestForDays[125] = 3399;
cumulativeInterestForDays[126] = 3458;
cumulativeInterestForDays[127] = 3518;
cumulativeInterestForDays[128] = 3578;
cumulativeInterestForDays[129] = 3639;
cumulativeInterestForDays[130] = 3700;
cumulativeInterestForDays[131] = 3762;
cumulativeInterestForDays[132] = 3825;
cumulativeInterestForDays[133] = 3888;
cumulativeInterestForDays[134] = 3952;
cumulativeInterestForDays[135] = 4016;
cumulativeInterestForDays[136] = 4081;
cumulativeInterestForDays[137] = 4147;
cumulativeInterestForDays[138] = 4213;
cumulativeInterestForDays[139] = 4280;
cumulativeInterestForDays[140] = 4347;
cumulativeInterestForDays[141] = 4415;
cumulativeInterestForDays[142] = 4484;
cumulativeInterestForDays[143] = 4553;
cumulativeInterestForDays[144] = 4623;
cumulativeInterestForDays[145] = 4694;
cumulativeInterestForDays[146] = 4765;
cumulativeInterestForDays[147] = 4837;
cumulativeInterestForDays[148] = 4909;
cumulativeInterestForDays[149] = 4982;
cumulativeInterestForDays[150] = 5056;
cumulativeInterestForDays[151] = 5130;
cumulativeInterestForDays[152] = 5205;
cumulativeInterestForDays[153] = 5281;
cumulativeInterestForDays[154] = 5357;
cumulativeInterestForDays[155] = 5434;
cumulativeInterestForDays[156] = 5512;
cumulativeInterestForDays[157] = 5590;
cumulativeInterestForDays[158] = 5669;
cumulativeInterestForDays[159] = 5749;
cumulativeInterestForDays[160] = 5829;
cumulativeInterestForDays[161] = 5910;
cumulativeInterestForDays[162] = 5992;
cumulativeInterestForDays[163] = 6074;
cumulativeInterestForDays[164] = 6157;
cumulativeInterestForDays[165] = 6241;
cumulativeInterestForDays[166] = 6325;
cumulativeInterestForDays[167] = 6410;
cumulativeInterestForDays[168] = 6496;
cumulativeInterestForDays[169] = 6582;
cumulativeInterestForDays[170] = 6669;
cumulativeInterestForDays[171] = 6757;
cumulativeInterestForDays[172] = 6845;
cumulativeInterestForDays[173] = 6934;
cumulativeInterestForDays[174] = 7024;
cumulativeInterestForDays[175] = 7114;
cumulativeInterestForDays[176] = 7205;
cumulativeInterestForDays[177] = 7297;
cumulativeInterestForDays[178] = 7390;
cumulativeInterestForDays[179] = 7483;
cumulativeInterestForDays[180] = 7577;
cumulativeInterestForDays[181] = 7672;
cumulativeInterestForDays[182] = 7767;
cumulativeInterestForDays[183] = 7863;
cumulativeInterestForDays[184] = 7960;
cumulativeInterestForDays[185] = 8058;
cumulativeInterestForDays[186] = 8156;
cumulativeInterestForDays[187] = 8255;
cumulativeInterestForDays[188] = 8355;
cumulativeInterestForDays[189] = 8455;
cumulativeInterestForDays[190] = 8556;
cumulativeInterestForDays[191] = 8658;
cumulativeInterestForDays[192] = 8761;
cumulativeInterestForDays[193] = 8864;
cumulativeInterestForDays[194] = 8968;
cumulativeInterestForDays[195] = 9073;
cumulativeInterestForDays[196] = 9179;
cumulativeInterestForDays[197] = 9285;
cumulativeInterestForDays[198] = 9392;
cumulativeInterestForDays[199] = 9500;
cumulativeInterestForDays[200] = 9609;
cumulativeInterestForDays[201] = 9719;
cumulativeInterestForDays[202] = 9829;
cumulativeInterestForDays[203] = 9940;
cumulativeInterestForDays[204] = 10052;
cumulativeInterestForDays[205] = 10165;
cumulativeInterestForDays[206] = 10278;
cumulativeInterestForDays[207] = 10392;
cumulativeInterestForDays[208] = 10507;
cumulativeInterestForDays[209] = 10623;
cumulativeInterestForDays[210] = 10740;
cumulativeInterestForDays[211] = 10857;
cumulativeInterestForDays[212] = 10975;
cumulativeInterestForDays[213] = 11094;
cumulativeInterestForDays[214] = 11214;
cumulativeInterestForDays[215] = 11335;
cumulativeInterestForDays[216] = 11456;
cumulativeInterestForDays[217] = 11578;
cumulativeInterestForDays[218] = 11701;
cumulativeInterestForDays[219] = 11825;
cumulativeInterestForDays[220] = 11950;
cumulativeInterestForDays[221] = 12076;
cumulativeInterestForDays[222] = 12202;
cumulativeInterestForDays[223] = 12329;
cumulativeInterestForDays[224] = 12457;
cumulativeInterestForDays[225] = 12586;
cumulativeInterestForDays[226] = 12716;
cumulativeInterestForDays[227] = 12847;
cumulativeInterestForDays[228] = 12978;
cumulativeInterestForDays[229] = 13110;
cumulativeInterestForDays[230] = 13243;
cumulativeInterestForDays[231] = 13377;
cumulativeInterestForDays[232] = 13512;
cumulativeInterestForDays[233] = 13648;
cumulativeInterestForDays[234] = 13785;
cumulativeInterestForDays[235] = 13922;
cumulativeInterestForDays[236] = 14060;
cumulativeInterestForDays[237] = 14199;
cumulativeInterestForDays[238] = 14339;
cumulativeInterestForDays[239] = 14480;
cumulativeInterestForDays[240] = 14622;
cumulativeInterestForDays[241] = 14765;
cumulativeInterestForDays[242] = 14909;
cumulativeInterestForDays[243] = 15054;
cumulativeInterestForDays[244] = 15199;
cumulativeInterestForDays[245] = 15345;
cumulativeInterestForDays[246] = 15492;
cumulativeInterestForDays[247] = 15640;
cumulativeInterestForDays[248] = 15789;
cumulativeInterestForDays[249] = 15939;
cumulativeInterestForDays[250] = 16090;
cumulativeInterestForDays[251] = 16242;
cumulativeInterestForDays[252] = 16395;
cumulativeInterestForDays[253] = 16549;
cumulativeInterestForDays[254] = 16704;
cumulativeInterestForDays[255] = 16860;
cumulativeInterestForDays[256] = 17017;
cumulativeInterestForDays[257] = 17174;
cumulativeInterestForDays[258] = 17332;
cumulativeInterestForDays[259] = 17491;
cumulativeInterestForDays[260] = 17651;
cumulativeInterestForDays[261] = 17812;
cumulativeInterestForDays[262] = 17974;
cumulativeInterestForDays[263] = 18137;
cumulativeInterestForDays[264] = 18301;
cumulativeInterestForDays[265] = 18466;
cumulativeInterestForDays[266] = 18632;
cumulativeInterestForDays[267] = 18799;
cumulativeInterestForDays[268] = 18967;
cumulativeInterestForDays[269] = 19136;
cumulativeInterestForDays[270] = 19306;
cumulativeInterestForDays[271] = 19477;
cumulativeInterestForDays[272] = 19649;
cumulativeInterestForDays[273] = 19822;
cumulativeInterestForDays[274] = 19996;
cumulativeInterestForDays[275] = 20171;
cumulativeInterestForDays[276] = 20347;
cumulativeInterestForDays[277] = 20524;
cumulativeInterestForDays[278] = 20702;
cumulativeInterestForDays[279] = 20881;
cumulativeInterestForDays[280] = 21061;
cumulativeInterestForDays[281] = 21242;
cumulativeInterestForDays[282] = 21424;
cumulativeInterestForDays[283] = 21607;
cumulativeInterestForDays[284] = 21791;
cumulativeInterestForDays[285] = 21976;
cumulativeInterestForDays[286] = 22162;
cumulativeInterestForDays[287] = 22350;
cumulativeInterestForDays[288] = 22539;
cumulativeInterestForDays[289] = 22729;
cumulativeInterestForDays[290] = 22920;
cumulativeInterestForDays[291] = 23112;
cumulativeInterestForDays[292] = 23305;
cumulativeInterestForDays[293] = 23499;
cumulativeInterestForDays[294] = 23694;
cumulativeInterestForDays[295] = 23890;
cumulativeInterestForDays[296] = 24087;
cumulativeInterestForDays[297] = 24285;
cumulativeInterestForDays[298] = 24484;
cumulativeInterestForDays[299] = 24685;
cumulativeInterestForDays[300] = 24887;
cumulativeInterestForDays[301] = 25090;
cumulativeInterestForDays[302] = 25294;
cumulativeInterestForDays[303] = 25499;
cumulativeInterestForDays[304] = 25705;
cumulativeInterestForDays[305] = 25912;
cumulativeInterestForDays[306] = 26120;
cumulativeInterestForDays[307] = 26330;
cumulativeInterestForDays[308] = 26541;
cumulativeInterestForDays[309] = 26753;
cumulativeInterestForDays[310] = 26966;
cumulativeInterestForDays[311] = 27180;
cumulativeInterestForDays[312] = 27395;
cumulativeInterestForDays[313] = 27611;
cumulativeInterestForDays[314] = 27829;
cumulativeInterestForDays[315] = 28048;
cumulativeInterestForDays[316] = 28268;
cumulativeInterestForDays[317] = 28489;
cumulativeInterestForDays[318] = 28711;
cumulativeInterestForDays[319] = 28934;
cumulativeInterestForDays[320] = 29159;
cumulativeInterestForDays[321] = 29385;
cumulativeInterestForDays[322] = 29612;
cumulativeInterestForDays[323] = 29840;
cumulativeInterestForDays[324] = 30069;
cumulativeInterestForDays[325] = 30300;
cumulativeInterestForDays[326] = 30532;
cumulativeInterestForDays[327] = 30765;
cumulativeInterestForDays[328] = 30999;
cumulativeInterestForDays[329] = 31235;
cumulativeInterestForDays[330] = 31472;
cumulativeInterestForDays[331] = 31710;
cumulativeInterestForDays[332] = 31949;
cumulativeInterestForDays[333] = 32190;
cumulativeInterestForDays[334] = 32432;
cumulativeInterestForDays[335] = 32675;
cumulativeInterestForDays[336] = 32919;
cumulativeInterestForDays[337] = 33165;
cumulativeInterestForDays[338] = 33412;
cumulativeInterestForDays[339] = 33660;
cumulativeInterestForDays[340] = 33909;
cumulativeInterestForDays[341] = 34160;
cumulativeInterestForDays[342] = 34412;
cumulativeInterestForDays[343] = 34665;
cumulativeInterestForDays[344] = 34920;
cumulativeInterestForDays[345] = 35176;
cumulativeInterestForDays[346] = 35433;
cumulativeInterestForDays[347] = 35692;
cumulativeInterestForDays[348] = 35952;
cumulativeInterestForDays[349] = 36213;
cumulativeInterestForDays[350] = 36476;
cumulativeInterestForDays[351] = 36740;
cumulativeInterestForDays[352] = 37005;
cumulativeInterestForDays[353] = 37272;
cumulativeInterestForDays[354] = 37540;
cumulativeInterestForDays[355] = 37809;
cumulativeInterestForDays[356] = 38080;
cumulativeInterestForDays[357] = 38352;
cumulativeInterestForDays[358] = 38625;
cumulativeInterestForDays[359] = 38900;
cumulativeInterestForDays[360] = 39176;
cumulativeInterestForDays[361] = 39454;
cumulativeInterestForDays[362] = 39733;
cumulativeInterestForDays[363] = 40013;
cumulativeInterestForDays[364] = 40295;
cumulativeInterestForDays[365] = 40578;
return cumulativeInterestForDays;
}
function _getInterestTillDays(uint _day) internal pure returns(uint) {
require(_day <= MAX_DAYS);
return _initCumulativeInterestForDays()[_day];
}
}
// File: contracts/Events.sol
pragma solidity ^0.6.12;
contract Events {
event Deposit(address user, uint amount, uint8 stakeId, address uplinkAddress, uint uplinkStakeId);
event Withdrawn(address user, uint amount);
event ReInvest(address user, uint amount);
event Exited(address user, uint stakeId, uint amount);
event PoolDrawn(uint refPoolAmount, uint sponsorPoolAmount);
}
// File: contracts/PercentageCalculator.sol
pragma solidity ^0.6.12;
contract PercentageCalculator {
using SafeMath for uint;
uint public constant PERCENT_MULTIPLIER = 10000;
function _calcPercentage(uint amount, uint basisPoints) internal pure returns (uint) {
require(basisPoints >= 0);
return amount.mul(basisPoints).div(PERCENT_MULTIPLIER);
}
function _calcBasisPoints(uint base, uint interest) internal pure returns (uint) {
return interest.mul(PERCENT_MULTIPLIER).div(base);
}
}
// File: contracts/utils/Utils.sol
pragma solidity ^0.6.12;
contract Utils {
using SafeMath for uint;
uint public constant DAY = 86400; // Seconds in a day
function _calcDays(uint start, uint end) internal pure returns (uint) {
return end.sub(start).div(DAY);
}
}
// File: contracts/Constants.sol
pragma solidity ^0.6.12;
contract Constants {
uint public constant MAX_CONTRACT_REWARD_BP = 37455; // 374.55%
uint public constant LP_FEE_BP = 500; // 5%
uint public constant REF_COMMISSION_BP = 800; // 8%
// Ref and sponsor pools
uint public constant REF_POOL_FEE_BP = 50; // 0.5%, goes to ref pool from each deposit
uint public constant SPONSOR_POOL_FEE_BP = 50; // 0.5%, goes to sponsor pool from each deposit
uint public constant EXIT_PENALTY_BP = 5000; // 50%, deduct from user's initial deposit on exit
// Contract bonus
uint public constant MAX_CONTRACT_BONUS_BP = 300; // maximum bonus a user can get 3%
uint public constant CONTRACT_BONUS_UNIT = 250; // For each 250 token balance of contract, gives
uint public constant CONTRACT_BONUS_PER_UNIT_BP = 1; // 0.01% extra interest
// Hold bonus
uint public constant MAX_HOLD_BONUS_BP = 100; // Maximum 1% hold bonus
uint public constant HOLD_BONUS_UNIT = 43200; // 12 hours
uint public constant HOLD_BONUS_PER_UNIT_BP = 2; // 0.02% hold bonus for each 12 hours of hold
uint public constant REWARD_THRESHOLD_BP = 300; // User will only get hold bonus if his rewards are more then 3% of his deposit
uint public constant MAX_WITHDRAWAL_OVER_REWARD_THRESHOLD_BP = 300; // Max daily withdrawal limit if user is above REWARD_THRESHOLD_BP
uint public constant DEV_FEE_BP = 500; // 5%
}
// File: contracts/StatsVars.sol
pragma solidity ^0.6.12;
contract StatsVars {
// Stats
uint public totalDepositRewards;
uint public totalExited;
}
// File: contracts/SharedVariables.sol
pragma solidity ^0.6.12;
contract SharedVariables is Constants, StatsVars, Events, PercentageCalculator, InterestCalculator, Utils {
uint public constant fourRXTokenDecimals = 8;
IERC20 public fourRXToken;
address public devAddress;
struct Stake {
uint8 id;
bool active;
bool optInInsured; // Is insured ???
uint32 holdFrom; // Timestamp from which hold should be counted
uint32 interestCountFrom; // TimeStamp from which interest should be counted, from the beginning
uint32 lastWithdrawalAt; // date time of last withdrawals so we don't allow more then 3% a day
uint origDeposit;
uint deposit; // Initial Deposit
uint withdrawn; // Total withdrawn from this stake
uint penalty; // Total penalty on this stale
uint rewards;
}
struct User {
address wallet; // Wallet Address
Stake[] stakes;
}
mapping (address => User) public users;
uint[] public refPoolBonuses;
uint[] public sponsorPoolBonuses;
uint public maxContractBalance;
uint16 public poolCycle;
uint32 public poolDrewAt;
uint public refPoolBalance;
uint public sponsorPoolBalance;
uint public devBalance;
}
// File: contracts/libs/SortedLinkedList.sol
pragma solidity ^0.6.12;
library SortedLinkedList {
using SafeMath for uint;
struct Item {
address user;
uint16 next;
uint8 id;
uint score;
}
uint16 internal constant GUARD = 0;
function addNode(Item[] storage items, address user, uint score, uint8 id) internal {
uint16 prev = findSortedIndex(items, score);
require(_verifyIndex(items, score, prev));
items.push(Item(user, items[prev].next, id, score));
items[prev].next = uint16(items.length.sub(1));
}
function updateNode(Item[] storage items, address user, uint score, uint8 id) internal {
(uint16 current, uint16 oldPrev) = findCurrentAndPrevIndex(items, user, id);
require(items[oldPrev].next == current);
require(items[current].user == user);
require(items[current].id == id);
score = score.add(items[current].score);
items[oldPrev].next = items[current].next;
addNode(items, user, score, id);
}
function initNodes(Item[] storage items) internal {
items.push(Item(address(0), 0, 0, 0));
}
function _verifyIndex(Item[] storage items, uint score, uint16 prev) internal view returns (bool) {
return prev == GUARD || (score <= items[prev].score && score > items[items[prev].next].score);
}
function findSortedIndex(Item[] storage items, uint score) internal view returns(uint16) {
Item memory current = items[GUARD];
uint16 index = GUARD;
while(current.next != GUARD && items[current.next].score >= score) {
index = current.next;
current = items[current.next];
}
return index;
}
function findCurrentAndPrevIndex(Item[] storage items, address user, uint8 id) internal view returns (uint16, uint16) {
Item memory current = items[GUARD];
uint16 currentIndex = GUARD;
uint16 prevIndex = GUARD;
while(current.next != GUARD && !(current.user == user && current.id == id)) {
prevIndex = currentIndex;
currentIndex = current.next;
current = items[current.next];
}
return (currentIndex, prevIndex);
}
function isInList(Item[] storage items, address user, uint8 id) internal view returns (bool) {
Item memory current = items[GUARD];
bool exists = false;
while(current.next != GUARD ) {
if (current.user == user && current.id == id) {
exists = true;
break;
}
current = items[current.next];
}
return exists;
}
}
// File: contracts/Pools/SponsorPool.sol
pragma solidity ^0.6.12;
contract SponsorPool {
SortedLinkedList.Item[] public sponsorPoolUsers;
function _addSponsorPoolRecord(address user, uint amount, uint8 stakeId) internal {
SortedLinkedList.addNode(sponsorPoolUsers, user, amount, stakeId);
}
function _cleanSponsorPoolUsers() internal {
delete sponsorPoolUsers;
SortedLinkedList.initNodes(sponsorPoolUsers);
}
}
// File: contracts/Pools/ReferralPool.sol
pragma solidity ^0.6.12;
contract ReferralPool {
SortedLinkedList.Item[] public refPoolUsers;
function _addReferralPoolRecord(address user, uint amount, uint8 stakeId) internal {
if (!SortedLinkedList.isInList(refPoolUsers, user, stakeId)) {
SortedLinkedList.addNode(refPoolUsers, user, amount, stakeId);
} else {
SortedLinkedList.updateNode(refPoolUsers, user, amount, stakeId);
}
}
function _cleanReferralPoolUsers() internal {
delete refPoolUsers;
SortedLinkedList.initNodes(refPoolUsers);
}
}
// File: contracts/Pools.sol
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
contract Pools is SponsorPool, ReferralPool, SharedVariables {
uint8 public constant MAX_REF_POOL_USERS = 12;
uint8 public constant MAX_SPONSOR_POOL_USERS = 10;
function _resetPools() internal {
_cleanSponsorPoolUsers();
_cleanReferralPoolUsers();
delete refPoolBalance;
delete sponsorPoolBalance;
poolDrewAt = uint32(block.timestamp);
poolCycle++;
}
function _updateSponsorPoolUsers(User memory user, Stake memory stake) internal {
_addSponsorPoolRecord(user.wallet, stake.deposit, stake.id);
}
// Reorganise top ref-pool users to draw pool for
function _updateRefPoolUsers(User memory uplinkUser , Stake memory stake, uint8 uplinkUserStakeId) internal {
_addReferralPoolRecord(uplinkUser.wallet, stake.deposit, uplinkUserStakeId);
}
function drawPool() public {
if (block.timestamp > poolDrewAt + 1 days) {
SortedLinkedList.Item memory current = refPoolUsers[0];
uint16 i = 0;
while (i < MAX_REF_POOL_USERS && current.next != SortedLinkedList.GUARD) {
current = refPoolUsers[current.next];
users[current.user].stakes[current.id].rewards = users[current.user].stakes[current.id].rewards.add(_calcPercentage(refPoolBalance, refPoolBonuses[i]));
i++;
}
current = sponsorPoolUsers[0];
i = 0;
while (i < MAX_SPONSOR_POOL_USERS && current.next != SortedLinkedList.GUARD) {
current = sponsorPoolUsers[current.next];
users[current.user].stakes[current.id].rewards = users[current.user].stakes[current.id].rewards.add(_calcPercentage(sponsorPoolBalance, sponsorPoolBonuses[i]));
i++;
}
emit PoolDrawn(refPoolBalance, sponsorPoolBalance);
_resetPools();
}
}
// pool info getters
function getPoolInfo() external view returns (uint32, uint16, uint, uint) {
return (poolDrewAt, poolCycle, sponsorPoolBalance, refPoolBalance);
}
function getPoolParticipants() external view returns (address[] memory, uint8[] memory, uint[] memory, address[] memory, uint8[] memory, uint[] memory) {
address[] memory sponsorPoolUsersAddresses = new address[](MAX_SPONSOR_POOL_USERS);
uint8[] memory sponsorPoolUsersStakeIds = new uint8[](MAX_SPONSOR_POOL_USERS);
uint[] memory sponsorPoolUsersAmounts = new uint[](MAX_SPONSOR_POOL_USERS);
address[] memory refPoolUsersAddresses = new address[](MAX_REF_POOL_USERS);
uint8[] memory refPoolUsersStakeIds = new uint8[](MAX_REF_POOL_USERS);
uint[] memory refPoolUsersAmounts = new uint[](MAX_REF_POOL_USERS);
uint16 i = 0;
SortedLinkedList.Item memory current = sponsorPoolUsers[i];
while (i < MAX_SPONSOR_POOL_USERS && current.next != SortedLinkedList.GUARD) {
current = sponsorPoolUsers[current.next];
sponsorPoolUsersAddresses[i] = current.user;
sponsorPoolUsersStakeIds[i] = current.id;
sponsorPoolUsersAmounts[i] = current.score;
i++;
}
i = 0;
current = refPoolUsers[i];
while (i < MAX_REF_POOL_USERS && current.next != SortedLinkedList.GUARD) {
current = refPoolUsers[current.next];
refPoolUsersAddresses[i] = current.user;
refPoolUsersStakeIds[i] = current.id;
refPoolUsersAmounts[i] = current.score;
i++;
}
return (sponsorPoolUsersAddresses, sponsorPoolUsersStakeIds, sponsorPoolUsersAmounts, refPoolUsersAddresses, refPoolUsersStakeIds, refPoolUsersAmounts);
}
}
// File: contracts/RewardsAndPenalties.sol
pragma solidity ^0.6.12;
contract RewardsAndPenalties is Pools {
using SafeMath for uint;
function _distributeReferralReward(uint amount, Stake memory stake, address uplinkAddress, uint8 uplinkStakeId) internal {
User storage uplinkUser = users[uplinkAddress];
uint commission = _calcPercentage(amount, REF_COMMISSION_BP);
uplinkUser.stakes[uplinkStakeId].rewards = uplinkUser.stakes[uplinkStakeId].rewards.add(commission);
_updateRefPoolUsers(uplinkUser, stake, uplinkStakeId);
}
function _calcDepositRewards(uint amount) internal pure returns (uint) {
uint rewardPercent = 0;
if (amount > 175 * (10**fourRXTokenDecimals)) {
rewardPercent = 50; // 0.5%
} else if (amount > 150 * (10**fourRXTokenDecimals)) {
rewardPercent = 40; // 0.4%
} else if (amount > 135 * (10**fourRXTokenDecimals)) {
rewardPercent = 35; // 0.35%
} else if (amount > 119 * (10**fourRXTokenDecimals)) {
rewardPercent = 30; // 0.3%
} else if (amount > 100 * (10**fourRXTokenDecimals)) {
rewardPercent = 25; // 0.25%
} else if (amount > 89 * (10**fourRXTokenDecimals)) {
rewardPercent = 20; // 0.2%
} else if (amount > 75 * (10**fourRXTokenDecimals)) {
rewardPercent = 15; // 0.15%
} else if (amount > 59 * (10**fourRXTokenDecimals)) {
rewardPercent = 10; // 0.1%
} else if (amount > 45 * (10**fourRXTokenDecimals)) {
rewardPercent = 5; // 0.05%
} else if (amount > 20 * (10**fourRXTokenDecimals)) {
rewardPercent = 2; // 0.02%
} else if (amount > 9 * (10**fourRXTokenDecimals)) {
rewardPercent = 1; // 0.01%
}
return _calcPercentage(amount, rewardPercent);
}
function _calcContractBonus(Stake memory stake) internal view returns (uint) {
uint contractBonusPercent = fourRXToken.balanceOf(address(this)).mul(CONTRACT_BONUS_PER_UNIT_BP).div(CONTRACT_BONUS_UNIT).div(10**fourRXTokenDecimals);
if (contractBonusPercent > MAX_CONTRACT_BONUS_BP) {
contractBonusPercent = MAX_CONTRACT_BONUS_BP;
}
return _calcPercentage(stake.deposit, contractBonusPercent);
}
function _calcHoldRewards(Stake memory stake) internal view returns (uint) {
uint holdBonusPercent = (block.timestamp).sub(stake.holdFrom).div(HOLD_BONUS_UNIT).mul(HOLD_BONUS_PER_UNIT_BP);
if (holdBonusPercent > MAX_HOLD_BONUS_BP) {
holdBonusPercent = MAX_HOLD_BONUS_BP;
}
return _calcPercentage(stake.deposit, holdBonusPercent);
}
function _calcRewardsWithoutHoldBonus(Stake memory stake) internal view returns (uint) {
uint interest = _calcPercentage(stake.deposit, _getInterestTillDays(_calcDays(stake.interestCountFrom, block.timestamp)));
uint contractBonus = _calcContractBonus(stake);
uint totalRewardsWithoutHoldBonus = stake.rewards.add(interest).add(contractBonus);
return totalRewardsWithoutHoldBonus;
}
function _calcRewards(Stake memory stake) internal view returns (uint) {
uint rewards = _calcRewardsWithoutHoldBonus(stake);
if (_calcBasisPoints(stake.deposit, rewards) >= REWARD_THRESHOLD_BP) {
rewards = rewards.add(_calcHoldRewards(stake));
}
uint maxRewards = _calcPercentage(stake.deposit, MAX_CONTRACT_REWARD_BP);
if (rewards > maxRewards) {
rewards = maxRewards;
}
return rewards;
}
function _calcPenalty(Stake memory stake, uint withdrawalAmount) internal pure returns (uint) {
uint basisPoints = _calcBasisPoints(stake.deposit, withdrawalAmount);
// If user's rewards are more then REWARD_THRESHOLD_BP -- No penalty
if (basisPoints >= REWARD_THRESHOLD_BP) {
return 0;
}
return _calcPercentage(withdrawalAmount, PERCENT_MULTIPLIER.sub(basisPoints.mul(PERCENT_MULTIPLIER).div(REWARD_THRESHOLD_BP)));
}
}
// File: contracts/Insurance.sol
pragma solidity ^0.6.12;
contract Insurance is RewardsAndPenalties {
uint private constant BASE_INSURANCE_FOR_BP = 3500; // trigger insurance with contract balance fall below 35%
uint private constant OPT_IN_INSURANCE_FEE_BP = 1000; // 10%
uint private constant OPT_IN_INSURANCE_FOR_BP = 10000; // 100%
bool public isInInsuranceState = false; // if contract is only allowing insured money this becomes true;
function _checkForBaseInsuranceTrigger() internal {
if (fourRXToken.balanceOf(address(this)) <= _calcPercentage(maxContractBalance, BASE_INSURANCE_FOR_BP)) {
isInInsuranceState = true;
} else {
isInInsuranceState = false;
}
}
function _getInsuredAvailableAmount(Stake memory stake, uint withdrawalAmount) internal pure returns (uint)
{
uint availableAmount = withdrawalAmount;
// Calc correct insured value by checking which insurance should be applied
uint insuredFor = BASE_INSURANCE_FOR_BP;
if (stake.optInInsured) {
insuredFor = OPT_IN_INSURANCE_FOR_BP;
}
uint maxWithdrawalAllowed = _calcPercentage(stake.deposit, insuredFor);
require(maxWithdrawalAllowed >= stake.withdrawn.add(stake.penalty)); // if contract is in insurance trigger, do not allow withdrawals for the users who already have withdrawn more then 35%
if (stake.withdrawn.add(availableAmount).add(stake.penalty) > maxWithdrawalAllowed) {
availableAmount = maxWithdrawalAllowed.sub(stake.withdrawn).sub(stake.penalty);
}
return availableAmount;
}
function _insureStake(address user, Stake storage stake) internal {
require(!stake.optInInsured && stake.active);
require(fourRXToken.transferFrom(user, address(this), _calcPercentage(stake.deposit, OPT_IN_INSURANCE_FEE_BP)));
stake.optInInsured = true;
}
}
// File: contracts/FourRXFinance.sol
pragma solidity ^0.6.12;
/// @title 4RX Finance Staking DAPP Contract
/// @notice Available functionality: Deposit, Withdraw, ExitProgram, Insure Stake
contract FourRXFinance is Insurance {
constructor(address _devAddress, address fourRXTokenAddress) public {
devAddress = _devAddress;
fourRXToken = IERC20(fourRXTokenAddress);
// Ref Bonus // 12 Max Participants
refPoolBonuses.push(2000); // 20%
refPoolBonuses.push(1700); // 17%
refPoolBonuses.push(1400); // 14%
refPoolBonuses.push(1100); // 11%
refPoolBonuses.push(1000); // 10%
refPoolBonuses.push(700); // 7%
refPoolBonuses.push(600); // 6%
refPoolBonuses.push(500); // 5%
refPoolBonuses.push(400); // 4%
refPoolBonuses.push(300); // 3%
refPoolBonuses.push(200); // 2%
refPoolBonuses.push(100); // 1%
// Sponsor Pool // 10 Max Participants
sponsorPoolBonuses.push(3000); // 30%
sponsorPoolBonuses.push(2000); // 20%
sponsorPoolBonuses.push(1200); // 12%
sponsorPoolBonuses.push(1000); // 10%
sponsorPoolBonuses.push(800); // 8%
sponsorPoolBonuses.push(700); // 7%
sponsorPoolBonuses.push(600); // 6%
sponsorPoolBonuses.push(400); // 4%
sponsorPoolBonuses.push(200); // 2%
sponsorPoolBonuses.push(100); // 1%
_resetPools();
poolCycle = 0;
}
function deposit(uint amount, address uplinkAddress, uint8 uplinkStakeId) external {
require(
uplinkAddress == address(0) ||
(users[uplinkAddress].wallet != address(0) && users[uplinkAddress].stakes[uplinkStakeId].active)
); // Either uplink must be registered and be a active deposit or 0 address
User storage user = users[msg.sender];
if (users[msg.sender].stakes.length > 0) {
require(amount >= users[msg.sender].stakes[user.stakes.length - 1].deposit.mul(2)); // deposit amount must be greater 2x then last deposit
}
require(fourRXToken.transferFrom(msg.sender, address(this), amount));
drawPool(); // Draw old pool if qualified, and we're pretty sure that this stake is going to be created
uint depositReward = _calcDepositRewards(amount);
Stake memory stake;
user.wallet = msg.sender;
stake.id = uint8(user.stakes.length);
stake.active = true;
stake.interestCountFrom = uint32(block.timestamp);
stake.holdFrom = uint32(block.timestamp);
stake.origDeposit = amount;
stake.deposit = amount.sub(_calcPercentage(amount, LP_FEE_BP)); // Deduct LP Commission
stake.rewards = depositReward;
_updateSponsorPoolUsers(user, stake);
if (uplinkAddress != address(0)) {
_distributeReferralReward(amount, stake, uplinkAddress, uplinkStakeId);
}
user.stakes.push(stake);
refPoolBalance = refPoolBalance.add(_calcPercentage(amount, REF_POOL_FEE_BP));
sponsorPoolBalance = sponsorPoolBalance.add(_calcPercentage(amount, SPONSOR_POOL_FEE_BP));
devBalance = devBalance.add(_calcPercentage(amount, DEV_FEE_BP));
uint currentContractBalance = fourRXToken.balanceOf(address(this));
if (currentContractBalance > maxContractBalance) {
maxContractBalance = currentContractBalance;
}
totalDepositRewards = totalDepositRewards.add(depositReward);
emit Deposit(msg.sender, amount, stake.id, uplinkAddress, uplinkStakeId);
}
function balanceOf(address _userAddress, uint stakeId) public view returns (uint) {
require(users[_userAddress].wallet == _userAddress);
User memory user = users[_userAddress];
return _calcRewards(user.stakes[stakeId]).sub(user.stakes[stakeId].withdrawn);
}
function withdraw(uint stakeId) external {
User storage user = users[msg.sender];
Stake storage stake = user.stakes[stakeId];
require(user.wallet == msg.sender && stake.active); // stake should be active
require(stake.lastWithdrawalAt + 1 days < block.timestamp); // we only allow one withdrawal each day
uint availableAmount = _calcRewards(stake).sub(stake.withdrawn).sub(stake.penalty);
require(availableAmount > 0);
uint penalty = _calcPenalty(stake, availableAmount);
if (penalty == 0) {
availableAmount = availableAmount.sub(_calcPercentage(stake.deposit, REWARD_THRESHOLD_BP)); // Only allow withdrawal if available is more then 10% of base
uint maxAllowedWithdrawal = _calcPercentage(stake.deposit, MAX_WITHDRAWAL_OVER_REWARD_THRESHOLD_BP);
if (availableAmount > maxAllowedWithdrawal) {
availableAmount = maxAllowedWithdrawal;
}
}
if (isInInsuranceState) {
availableAmount = _getInsuredAvailableAmount(stake, availableAmount);
}
availableAmount = availableAmount.sub(penalty);
stake.withdrawn = stake.withdrawn.add(availableAmount);
stake.lastWithdrawalAt = uint32(block.timestamp);
stake.holdFrom = uint32(block.timestamp);
stake.penalty = stake.penalty.add(penalty);
if (stake.withdrawn >= _calcPercentage(stake.deposit, MAX_CONTRACT_REWARD_BP)) {
stake.active = false; // if stake has withdrawn equals to or more then the max amount, then mark stake in-active
}
_checkForBaseInsuranceTrigger();
fourRXToken.transfer(user.wallet, availableAmount);
emit Withdrawn(user.wallet, availableAmount);
}
function exitProgram(uint stakeId) external {
User storage user = users[msg.sender];
require(user.wallet == msg.sender);
Stake storage stake = user.stakes[stakeId];
require(stake.active);
uint penaltyAmount = _calcPercentage(stake.origDeposit, EXIT_PENALTY_BP);
uint balance = balanceOf(msg.sender, stakeId);
uint availableAmount = stake.origDeposit + balance - penaltyAmount; // (deposit + (rewards - withdrawn) - penalty)
if (availableAmount > 0) {
fourRXToken.transfer(user.wallet, availableAmount);
stake.withdrawn = stake.withdrawn.add(availableAmount);
}
stake.active = false;
stake.penalty = stake.penalty.add(penaltyAmount);
totalExited = totalExited.add(1);
emit Exited(user.wallet, stakeId, availableAmount > 0 ? availableAmount : 0);
}
function insureStake(uint stakeId) external {
User storage user = users[msg.sender];
require(user.wallet == msg.sender);
Stake storage stake = user.stakes[stakeId];
_insureStake(user.wallet, stake);
}
// Getters
function getUser(address userAddress) external view returns (User memory) {
return users[userAddress];
}
function getContractInfo() external view returns (uint, bool, uint, uint) {
return (maxContractBalance, isInInsuranceState, totalDepositRewards, totalExited);
}
function withdrawDevFee(address withdrawingAddress, uint amount) external {
require(msg.sender == devAddress);
require(amount <= devBalance);
devBalance = devBalance.sub(amount);
fourRXToken.transfer(withdrawingAddress, amount);
}
function updateDevAddress(address newDevAddress) external {
require(msg.sender == devAddress);
devAddress = newDevAddress;
}
} | Ref and sponsor pools Contract bonus Hold bonus | contract Constants {
}
| 10,644,379 | [
1,
1957,
471,
272,
500,
2467,
16000,
13456,
324,
22889,
670,
1673,
324,
22889,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
5245,
288,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.6.0;
import "./SafeMath.sol";
import "./SafeBEP20.sol";
import "./Ownable.sol";
// SPDX-License-Identifier: MIT
// This smart contract was designed by the Rubix project and is not intended to be copied or manipulated without Rubix's dev's written permission.
// Website: https://rubix.onl
// Twitter: https://twitter.com/rubix0x
// The purpose of this contract is to provide Rubix token holders an opportunity to stake their tokens for a reward in return.
// This contract is also able to receive and distribute wBNB to RBX stakeholders.
// Warning! This contract has not been audited. Use at your own risk.
// We trust our code is good.
contract FelxibleStaking is Ownable {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
event Received(address, uint256);
receive() external payable {
emit Received(msg.sender, msg.value);
}
// RBX Tokens
IBEP20 private RBX;
// BNB Token
IBEP20 private wBNB;
address private jackpotPool;
// Current Pool ID
uint256 public _poolId;
// Base reward APY
uint256 private yield;
// Investors index ID
uint256 private _investorID;
// Total RBX staked on this contract
uint256 private _RbxStaked;
// Returns total BNB raised
uint256 private _bnbFunded;
// Sets pool Limit
uint256 private _poolLimit;
// Returns boolion value of pool status
bool private _paused;
// Sets time before first reward claim
uint256 constant rPeriod = 60;
uint256 constant secondsinYear = 31536000;
event funding(address indexed depositer, uint256 RBX, uint256 _wBNB2);
event staked(
address indexed account,
uint256 amount,
uint256 ID,
uint256 pID,
uint256 depositTimeStamp,
uint256 releaseTimeStamp
);
event withdrew(
address indexed account,
uint256 RBX,
uint256 wBNB,
uint256 ID,
uint256 pID,
uint256 now
);
event claimed(
address indexed account,
uint256 RBX,
uint256 wBNB,
uint256 ID,
uint256 now
);
event stakingPaused();
event poolUpdated();
event updatedJackpotAddress(address indexed newJackpotAddress);
event newRBXAPY(uint256 newAPY2);
event AddedToWhitelist(address indexed whitelistedAddr);
mapping(address => bool) private whitelist;
// @Dev checks if a user is an active Stakeholder
mapping(address => bool) private _isStakeholder;
// @Dev Mapping for storing pool data
mapping(uint256 => pool) private poolData;
struct pool {
uint256 startTS;
uint256 endTS;
uint256 shIndex;
uint256 bnbFunded;
uint256 rbxFunded;
uint256 poolWeight;
bool updated;
}
// @Dev Stores stakeholders data
mapping(uint256 => investors) private Investors;
struct investors {
address payable user;
uint256 sWeight;
uint256 depositTS;
uint256 joinedTS;
uint256 releaseTS;
uint256 rewardTS2;
uint256 pid;
uint256 accBNB;
uint256 accRBX;
uint256 accRBX2; // RBX Earned from yield staking
bool rClaimed;
bool claimed;
}
constructor(
IBEP20 _RBX,
IBEP20 _wBNB,
uint256 _yield
) public {
RBX = _RBX;
wBNB = _wBNB;
yield = _yield;
}
modifier restricted() {
require(isWhitelisted(msg.sender));
_;
}
function isWhitelisted(address _address) public view returns (bool) {
return whitelist[_address];
}
function addToWhitelist(address _address) public onlyOwner {
whitelist[_address] = true;
emit AddedToWhitelist(_address);
}
function addJackpotAddress(address _jackpotAddress) public onlyOwner {
jackpotPool = _jackpotAddress;
emit updatedJackpotAddress(_jackpotAddress);
}
function updateAPY(uint256 newAPY) public onlyOwner {
yield = newAPY;
emit newRBXAPY(newAPY);
}
// Checks if the user is an active stakeholder
function eligible(address userAddress) public view returns (bool) {
return _isStakeholder[userAddress];
}
function topUp(uint256 value1, uint256 value2) external restricted {
updatePool();
poolData[_poolId].bnbFunded = poolData[_poolId].bnbFunded.add(value1);
poolData[_poolId].rbxFunded = poolData[_poolId].rbxFunded.add(value2);
emit funding(msg.sender, value1, value2);
}
function deposit(uint256 amount, uint256 time) public returns (bool) {
require(_paused == false, "Staking is paused");
require(
amount <= 1500000000000000000000,
"Total amount should be less or equal 1,500 RBX!"
);
require(time <= 4233600, "Time must be less than 49 days");
updatePool();
SafeRbxTransfer(msg.sender, amount);
_investorID++;
poolData[_poolId].shIndex++;
poolData[_poolId].poolWeight = poolData[_poolId].poolWeight.add(amount);
_RbxStaked = _RbxStaked.add(amount);
Investors[_investorID] = investors(
msg.sender,
amount,
now,
now,
now.add(time),
poolData[_poolId].endTS,
_poolId,
0,
0,
0,
false,
false
);
emit staked(
msg.sender,
amount,
_poolId,
_investorID,
now,
now.add(time)
);
return true;
}
//Allows owner to pause staking in case of emergency
function pauseStaking(bool pause) public onlyOwner {
_paused = pause;
}
//Transfers funds
function SafeRbxTransfer(address sender, uint256 amount)
private
returns (bool)
{
RBX.safeTransferFrom(address(sender), address(this), amount);
return true;
}
function SafeBNBTransfer(address sender, uint256 amount)
private
returns (bool)
{
wBNB.safeTransferFrom(address(sender), address(this), amount);
return true;
}
//Starts new pool
function updatePool() public {
if (poolData[_poolId].startTS == 0) {
poolData[_poolId].startTS = now;
poolData[_poolId].endTS = now.add(rPeriod);
poolData[_poolId].endTS = now.add(rPeriod);
}
if (now >= poolData[_poolId].endTS) {
if (poolData[_poolId].shIndex == 0) {
poolData[_poolId].startTS = now;
poolData[_poolId].endTS = now.add(rPeriod);
}
if (poolData[_poolId].shIndex > 0) {
_poolId++;
poolData[_poolId].startTS = now;
poolData[_poolId].endTS = now.add(rPeriod);
poolData[_poolId.sub(1)].updated = true;
}
}
emit poolUpdated();
}
//Returns users share of the pool based on the staking weight.
function pShare(uint256 shID) private view returns (uint256) {
if (Investors[shID].claimed == true) {
return 0;
} else {
return
Investors[shID].sWeight.mul(1e12).div(
poolData[myPoolID(shID)].poolWeight
);
}
}
function myPoolID(uint256 shID) public view returns (uint256) {
return Investors[shID].pid;
}
//Returns amount of pending BNB in real time
function uBNBa(uint256 shID) private view returns (uint256) {
uint256 A = poolData[myPoolID(shID)].bnbFunded.mul(pShare(shID)).div(
1e12
);
uint256 B = Investors[shID].rewardTS2.sub(Investors[shID].joinedTS);
uint256 C = A.div(rPeriod);
uint256 D = B.mul(C);
uint256 E = now.sub(Investors[shID].joinedTS);
if (Investors[shID].rewardTS2 > now) {
return C.mul(E);
}
if (Investors[shID].rewardTS2 < now) {
return D;
} else if (Investors[shID].rClaimed == true) {
return 0;
}
}
// @Dev Function returns unclaimable rewards that will be forwarded to Jackpot pool.
function uBNBb(uint256 shID) private view returns (uint256) {
// Returns share of the pool
uint256 A = poolData[myPoolID(shID)].bnbFunded.mul(pShare(shID)).div(
1e12
);
// Reward per second
uint256 E = A.div(rPeriod);
// Returns Actual reward
uint256 F = Investors[shID].joinedTS.sub(
poolData[myPoolID(shID)].startTS
);
uint256 G = F.mul(E);
return G;
}
// Returns staking rewards based on the annual yield.
function uRBXa(uint256 shID) private view returns (uint256) {
uint256 A = Investors[shID].sWeight.mul(yield).div(100);
uint256 B = A.div(secondsinYear);
uint256 C = now.sub(Investors[shID].depositTS);
uint256 D = Investors[shID].releaseTS.sub(Investors[shID].depositTS);
if (timeLeft(shID) == true) {
return B.mul(C).sub(Investors[shID].accRBX2);
}
if (timeLeft(shID) == false) {
return B.mul(D).sub(Investors[shID].accRBX2);
}
}
// @Dev: Function returns total owed claimable reward.
function uRBXb(uint256 shID) private view returns (uint256) {
uint256 A = poolData[myPoolID(shID)].rbxFunded.mul(pShare(shID)).div(
1e12
);
uint256 B = A.div(rPeriod);
uint256 C = Investors[shID].rewardTS2.sub(Investors[shID].joinedTS);
uint256 D = now.sub(Investors[shID].joinedTS);
uint256 E = B.mul(C);
if (Investors[shID].rewardTS2 > now) {
return B.mul(D);
}
if (Investors[shID].rewardTS2 < now) {
return E;
} else if (Investors[shID].rClaimed == true) {
return 0;
}
}
// @Dev Function returns unclaimable rewards that will be forwarded to Jackpot pool.
function uRBXe(uint256 shID) private view returns (uint256) {
// Returns share of the pool
uint256 A = poolData[myPoolID(shID)].rbxFunded.mul(pShare(shID)).div(
1e12
);
// Reward per second
uint256 B = A.div(rPeriod);
// Returns Actual reward
uint256 C = Investors[shID].joinedTS.sub(
poolData[myPoolID(shID)].startTS
);
uint256 G = C.mul(B);
return G;
}
function unclaimedRBX(uint256 shID) private view returns (uint256) {
if (Investors[shID].claimed == false) {
return uRBXb(shID);
}
if (Investors[shID].claimed == true) {
return 0;
}
}
function unclaimedBNB(uint256 shID) private view returns (uint256) {
if (Investors[shID].rClaimed == false) {
return uBNBa(shID);
}
if (Investors[shID].rClaimed == true) {
return 0;
}
}
function iData(uint256 shID)
public
view
returns (
uint256 releaseTimeStamp2,
uint256 payoutTimeStamp2,
uint256 stakingWeight,
uint256 shareOfThePool2,
uint256 poolID2,
uint256 claimedRBX,
uint256 claimedBNB
)
{
uint256 _earnedBNB = Investors[shID].accBNB;
uint256 _earnedRBX = Investors[shID].accRBX.add(
Investors[shID].accRBX2
);
uint256 _activePool = myPoolID(shID);
return (
Investors[shID].releaseTS,
Investors[shID].rewardTS2,
Investors[shID].sWeight,
pShare(shID),
_activePool,
_earnedRBX,
_earnedBNB
);
}
function pData(uint256 pid)
public
view
returns (
uint256 timeCreated,
uint256 poolExpiry,
uint256 totalSh,
uint256 apy,
uint256 bnbFunded2,
uint256 rbxFunded2,
uint256 poolWeight
)
{
return (
poolData[pid].startTS,
poolData[pid].endTS,
poolData[pid].shIndex,
yield,
poolData[pid].bnbFunded,
poolData[pid].rbxFunded,
poolData[pid].poolWeight
);
}
// Function for claiming only RBX rewards
function claimA(uint256 shID) private {
uint256 A = uRBXa(shID);
if (timeLeft(shID) == true) {
RBX.safeTransfer(msg.sender, A);
Investors[shID].accRBX2 = Investors[shID].accRBX2.add(A);
} else {
RBX.safeTransfer(msg.sender, A.add(Investors[shID].sWeight));
Investors[shID].accRBX2 = Investors[shID].accRBX2.add(A);
Investors[shID].rClaimed = true;
Investors[shID].claimed = true;
}
}
// Function for claiming both assets
function claimB(uint256 shID) private returns (bool) {
uint256 A = uRBXb(shID);
uint256 B = uRBXa(shID);
uint256 C = uBNBa(shID);
uint256 E = uBNBb(shID);
uint256 D = uRBXe(shID);
Investors[shID].accRBX = Investors[shID].accRBX.add(A);
Investors[shID].accRBX2 = Investors[shID].accRBX2.add(B);
Investors[shID].accBNB = Investors[shID].accBNB.add(C);
if (uBNBb(shID) > 0) {
wBNB.safeTransfer(jackpotPool, E);
RBX.safeTransfer(jackpotPool, D);
}
if (timeLeft(shID) == false) {
RBX.safeTransfer(msg.sender, A.add(B).add(Investors[shID].sWeight));
wBNB.safeTransfer(msg.sender, C);
Investors[shID].claimed = true;
Investors[shID].rClaimed = true;
} else {
RBX.safeTransfer(msg.sender, A.add(B));
wBNB.safeTransfer(msg.sender, C);
subscribeToNewPool(shID);
}
}
// Function for claiming both assets and initial investment
function claimC(uint256 shID) private {
uint256 A = uRBXb(shID);
uint256 B = uRBXa(shID);
uint256 C = uBNBa(shID);
uint256 E = uBNBb(shID);
uint256 D = uRBXe(shID);
if (uBNBb(shID) > 0) {
wBNB.safeTransfer(jackpotPool, E);
RBX.safeTransfer(jackpotPool, D);
}
RBX.safeTransfer(msg.sender, A.add(B).add(Investors[shID].sWeight));
wBNB.safeTransfer(msg.sender, C);
Investors[shID].accRBX = Investors[shID].accRBX.add(A);
Investors[shID].accRBX2 = Investors[shID].accRBX2.add(B);
Investors[shID].accBNB = Investors[shID].accBNB.add(C);
Investors[shID].claimed = true;
Investors[shID].rClaimed = true;
}
// Function for claiming RBX if no BNB or RBX was funded
function claimE(uint256 shID) private {
uint256 A = uRBXa(shID);
RBX.safeTransfer(msg.sender, A);
Investors[shID].accRBX2 = Investors[shID].accRBX2.add(A);
subscribeToNewPool(shID);
}
function subscribeToNewPool(uint256 shID) private {
if (Investors[shID].releaseTS > poolData[_poolId].endTS) {
poolData[_poolId].poolWeight = poolData[_poolId].poolWeight.add(
Investors[shID].sWeight
);
Investors[shID].pid = _poolId;
Investors[shID].joinedTS = poolData[_poolId].startTS;
Investors[shID].rewardTS2 = poolData[_poolId].endTS;
poolData[_poolId].shIndex = poolData[_poolId].shIndex.add(1);
}
if (Investors[shID].releaseTS < poolData[_poolId].endTS) {
Investors[shID].rClaimed = true;
}
}
function timeLeft(uint256 shID) private view returns (bool) {
if (now >= Investors[shID].releaseTS) {
return false;
}
if (now <= Investors[shID].releaseTS) {
return true;
}
}
function rewardClaimable(uint256 shID) private view returns (bool) {
if (now <= Investors[shID].rewardTS2) {
return false;
}
if (now >= Investors[shID].rewardTS2) {
return true;
}
}
function withdraw(uint256 shID) public returns (bool) {
require(Investors[shID].claimed == false, "Reward already claimed");
require(Investors[shID].user == msg.sender, "Not Investor");
uint256 accRBX = uRBXa(shID);
uint256 accBNB = uBNBa(shID);
updatePool();
if (accBNB > 0) {
if (timeLeft(shID) == true) {
if (rewardClaimable(shID) == false) {
claimA(shID);
}
if (rewardClaimable(shID) == true) {
if (Investors[shID].rClaimed == true) {
claimA(shID);
}
if (Investors[shID].rClaimed == false) {
claimB(shID);
}
}
emit claimed(msg.sender, accRBX, accBNB, shID, now);
}
if (timeLeft(shID) == false) {
if (Investors[shID].rClaimed == true) {
claimA(shID);
}
if (Investors[shID].rClaimed == false) {
claimC(shID);
}
}
}
if (accBNB == 0) {
if (timeLeft(shID) == true) {
if (rewardClaimable(shID) == false) {
claimA(shID);
}
if (rewardClaimable(shID) == true) {
claimE(shID);
}
}
if (timeLeft(shID) == false) {
claimA(shID);
}
emit withdrew(
msg.sender,
accRBX,
accBNB,
shID,
myPoolID(shID),
now
);
}
return true;
}
}
| @Dev Mapping for storing pool data | mapping(uint256 => pool) private poolData;
| 2,514,160 | [
1,
36,
8870,
9408,
364,
15729,
2845,
501,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
12,
11890,
5034,
516,
2845,
13,
3238,
2845,
751,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.7.0;
pragma experimental ABIEncoderV2;
// File: witnet-ethereum-block-relay/contracts/BlockRelayInterface.sol
/**
* @title Block Relay Interface
* @notice Interface of a Block Relay to a Witnet network
* It defines how to interact with the Block Relay in order to support:
* - Retrieve last beacon information
* - Verify proof of inclusions (PoIs) of data request and tally transactions
* @author Witnet Foundation
*/
interface BlockRelayInterface {
/// @notice Returns the beacon from the last inserted block.
/// The last beacon (in bytes) will be used by Witnet Bridge nodes to compute their eligibility.
/// @return last beacon in bytes
function getLastBeacon() external view returns(bytes memory);
/// @notice Returns the lastest epoch reported to the block relay.
/// @return epoch
function getLastEpoch() external view returns(uint256);
/// @notice Returns the latest hash reported to the block relay
/// @return blockhash
function getLastHash() external view returns(uint256);
/// @notice Verifies the validity of a data request PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid data request PoI
function verifyDrPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element) external view returns(bool);
/// @notice Verifies the validity of a tally PoI against the Tally merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid tally PoI
function verifyTallyPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element) external view returns(bool);
/// @notice Verifies if the block relay can be upgraded
/// @return true if contract is upgradable
function isUpgradable(address _address) external view returns(bool);
}
// File: witnet-ethereum-block-relay/contracts/CentralizedBlockRelay.sol
/**
* @title Block relay contract
* @notice Contract to store/read block headers from the Witnet network
* @author Witnet Foundation
*/
contract CentralizedBlockRelay is BlockRelayInterface {
struct MerkleRoots {
// hash of the merkle root of the DRs in Witnet
uint256 drHashMerkleRoot;
// hash of the merkle root of the tallies in Witnet
uint256 tallyHashMerkleRoot;
}
struct Beacon {
// hash of the last block
uint256 blockHash;
// epoch of the last block
uint256 epoch;
}
// Address of the block pusher
address public witnet;
// Last block reported
Beacon public lastBlock;
mapping (uint256 => MerkleRoots) public blocks;
// Event emitted when a new block is posted to the contract
event NewBlock(address indexed _from, uint256 _id);
// Only the owner should be able to push blocks
modifier isOwner() {
require(msg.sender == witnet, "Sender not authorized"); // If it is incorrect here, it reverts.
_; // Otherwise, it continues.
}
// Ensures block exists
modifier blockExists(uint256 _id){
require(blocks[_id].drHashMerkleRoot!=0, "Non-existing block");
_;
}
// Ensures block does not exist
modifier blockDoesNotExist(uint256 _id){
require(blocks[_id].drHashMerkleRoot==0, "The block already existed");
_;
}
constructor() public{
// Only the contract deployer is able to push blocks
witnet = msg.sender;
}
/// @dev Read the beacon of the last block inserted
/// @return bytes to be signed by bridge nodes
function getLastBeacon()
external
view
override
returns(bytes memory)
{
return abi.encodePacked(lastBlock.blockHash, lastBlock.epoch);
}
/// @notice Returns the lastest epoch reported to the block relay.
/// @return epoch
function getLastEpoch() external view override returns(uint256) {
return lastBlock.epoch;
}
/// @notice Returns the latest hash reported to the block relay
/// @return blockhash
function getLastHash() external view override returns(uint256) {
return lastBlock.blockHash;
}
/// @dev Verifies the validity of a PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true or false depending the validity
function verifyDrPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element)
external
view
override
blockExists(_blockHash)
returns(bool)
{
uint256 drMerkleRoot = blocks[_blockHash].drHashMerkleRoot;
return(verifyPoi(
_poi,
drMerkleRoot,
_index,
_element));
}
/// @dev Verifies the validity of a PoI against the tally merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the element
/// @return true or false depending the validity
function verifyTallyPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element)
external
view
override
blockExists(_blockHash)
returns(bool)
{
uint256 tallyMerkleRoot = blocks[_blockHash].tallyHashMerkleRoot;
return(verifyPoi(
_poi,
tallyMerkleRoot,
_index,
_element));
}
/// @dev Verifies if the contract is upgradable
/// @return true if the contract upgradable
function isUpgradable(address _address) external view override returns(bool) {
if (_address == witnet) {
return true;
}
return false;
}
/// @dev Post new block into the block relay
/// @param _blockHash Hash of the block header
/// @param _epoch Witnet epoch to which the block belongs to
/// @param _drMerkleRoot Merkle root belonging to the data requests
/// @param _tallyMerkleRoot Merkle root belonging to the tallies
function postNewBlock(
uint256 _blockHash,
uint256 _epoch,
uint256 _drMerkleRoot,
uint256 _tallyMerkleRoot)
external
isOwner
blockDoesNotExist(_blockHash)
{
lastBlock.blockHash = _blockHash;
lastBlock.epoch = _epoch;
blocks[_blockHash].drHashMerkleRoot = _drMerkleRoot;
blocks[_blockHash].tallyHashMerkleRoot = _tallyMerkleRoot;
emit NewBlock(witnet, _blockHash);
}
/// @dev Retrieve the requests-only merkle root hash that was reported for a specific block header.
/// @param _blockHash Hash of the block header
/// @return Requests-only merkle root hash in the block header.
function readDrMerkleRoot(uint256 _blockHash)
external
view
blockExists(_blockHash)
returns(uint256)
{
return blocks[_blockHash].drHashMerkleRoot;
}
/// @dev Retrieve the tallies-only merkle root hash that was reported for a specific block header.
/// @param _blockHash Hash of the block header.
/// @return tallies-only merkle root hash in the block header.
function readTallyMerkleRoot(uint256 _blockHash)
external
view
blockExists(_blockHash)
returns(uint256)
{
return blocks[_blockHash].tallyHashMerkleRoot;
}
/// @dev Verifies the validity of a PoI
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _root the merkle root
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true or false depending the validity
function verifyPoi(
uint256[] memory _poi,
uint256 _root,
uint256 _index,
uint256 _element)
private pure returns(bool)
{
uint256 tree = _element;
uint256 index = _index;
// We want to prove that the hash of the _poi and the _element is equal to _root
// For knowing if concatenate to the left or the right we check the parity of the the index
for (uint i = 0; i < _poi.length; i++) {
if (index%2 == 0) {
tree = uint256(sha256(abi.encodePacked(tree, _poi[i])));
} else {
tree = uint256(sha256(abi.encodePacked(_poi[i], tree)));
}
index = index >> 1;
}
return _root == tree;
}
}
// File: witnet-ethereum-block-relay/contracts/BlockRelayProxy.sol
/**
* @title Block Relay Proxy
* @notice Contract to act as a proxy between the Witnet Bridge Interface and the block relay
* @dev More information can be found here
* DISCLAIMER: this is a work in progress, meaning the contract could be voulnerable to attacks
* @author Witnet Foundation
*/
contract BlockRelayProxy {
// Address of the current controller
address internal blockRelayAddress;
// Current interface to the controller
BlockRelayInterface internal blockRelayInstance;
struct ControllerInfo {
// last epoch seen by a controller
uint256 lastEpoch;
// address of the controller
address blockRelayController;
}
// array containing the information about controllers
ControllerInfo[] internal controllers;
modifier notIdentical(address _newAddress) {
require(_newAddress != blockRelayAddress, "The provided Block Relay instance address is already in use");
_;
}
constructor(address _blockRelayAddress) public {
// Initialize the first epoch pointing to the first controller
controllers.push(ControllerInfo({lastEpoch: 0, blockRelayController: _blockRelayAddress}));
blockRelayAddress = _blockRelayAddress;
blockRelayInstance = BlockRelayInterface(_blockRelayAddress);
}
/// @notice Returns the beacon from the last inserted block.
/// The last beacon (in bytes) will be used by Witnet Bridge nodes to compute their eligibility.
/// @return last beacon in bytes
function getLastBeacon() external view returns(bytes memory) {
return blockRelayInstance.getLastBeacon();
}
/// @notice Returns the last Wtinet epoch known to the block relay instance.
/// @return The last epoch is used in the WRB to avoid reusage of PoI in a data request.
function getLastEpoch() external view returns(uint256) {
return blockRelayInstance.getLastEpoch();
}
/// @notice Verifies the validity of a data request PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _epoch the epoch of the blockchash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid data request PoI
function verifyDrPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _epoch,
uint256 _index,
uint256 _element) external view returns(bool)
{
address controller = getController(_epoch);
return BlockRelayInterface(controller).verifyDrPoi(
_poi,
_blockHash,
_index,
_element);
}
/// @notice Verifies the validity of a tally PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _epoch the epoch of the blockchash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid data request PoI
function verifyTallyPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _epoch,
uint256 _index,
uint256 _element) external view returns(bool)
{
address controller = getController(_epoch);
return BlockRelayInterface(controller).verifyTallyPoi(
_poi,
_blockHash,
_index,
_element);
}
/// @notice Upgrades the block relay if the current one is upgradeable
/// @param _newAddress address of the new block relay to upgrade
function upgradeBlockRelay(address _newAddress) external notIdentical(_newAddress) {
// Check if the controller is upgradeable
require(blockRelayInstance.isUpgradable(msg.sender), "The upgrade has been rejected by the current implementation");
// Get last epoch seen by the replaced controller
uint256 epoch = blockRelayInstance.getLastEpoch();
// Get the length of last epochs seen by the different controllers
uint256 n = controllers.length;
// If the the last epoch seen by the replaced controller is lower than the one already anotated e.g. 0
// just update the already anotated epoch with the new address, ignoring the previously inserted controller
// Else, anotate the epoch from which the new controller should start receiving blocks
if (epoch < controllers[n-1].lastEpoch) {
controllers[n-1].blockRelayController = _newAddress;
} else {
controllers.push(ControllerInfo({lastEpoch: epoch+1, blockRelayController: _newAddress}));
}
// Update instance
blockRelayAddress = _newAddress;
blockRelayInstance = BlockRelayInterface(_newAddress);
}
/// @notice Gets the controller associated with the BR controller corresponding to the epoch provided
/// @param _epoch the epoch to work with
function getController(uint256 _epoch) public view returns(address _controller) {
// Get length of all last epochs seen by controllers
uint256 n = controllers.length;
// Go backwards until we find the controller having that blockhash
for (uint i = n; i > 0; i--) {
if (_epoch >= controllers[i-1].lastEpoch) {
return (controllers[i-1].blockRelayController);
}
}
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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;
}
}
// File: elliptic-curve-solidity/contracts/EllipticCurve.sol
/**
* @title Elliptic Curve Library
* @dev Library providing arithmetic operations over elliptic curves.
* @author Witnet Foundation
*/
library EllipticCurve {
/// @dev Modular euclidean inverse of a number (mod p).
/// @param _x The number
/// @param _pp The modulus
/// @return q such that x*q = 1 (mod _pp)
function invMod(uint256 _x, uint256 _pp) internal pure returns (uint256) {
require(_x != 0 && _x != _pp && _pp != 0, "Invalid number");
uint256 q = 0;
uint256 newT = 1;
uint256 r = _pp;
uint256 newR = _x;
uint256 t;
while (newR != 0) {
t = r / newR;
(q, newT) = (newT, addmod(q, (_pp - mulmod(t, newT, _pp)), _pp));
(r, newR) = (newR, r - t * newR );
}
return q;
}
/// @dev Modular exponentiation, b^e % _pp.
/// Source: https://github.com/androlo/standard-contracts/blob/master/contracts/src/crypto/ECCMath.sol
/// @param _base base
/// @param _exp exponent
/// @param _pp modulus
/// @return r such that r = b**e (mod _pp)
function expMod(uint256 _base, uint256 _exp, uint256 _pp) internal pure returns (uint256) {
require(_pp!=0, "Modulus is zero");
if (_base == 0)
return 0;
if (_exp == 0)
return 1;
uint256 r = 1;
uint256 bit = 2 ** 255;
assembly {
for { } gt(bit, 0) { }{
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, bit)))), _pp)
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 2))))), _pp)
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 4))))), _pp)
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 8))))), _pp)
bit := div(bit, 16)
}
}
return r;
}
/// @dev Converts a point (x, y, z) expressed in Jacobian coordinates to affine coordinates (x', y', 1).
/// @param _x coordinate x
/// @param _y coordinate y
/// @param _z coordinate z
/// @param _pp the modulus
/// @return (x', y') affine coordinates
function toAffine(
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _pp)
internal pure returns (uint256, uint256)
{
uint256 zInv = invMod(_z, _pp);
uint256 zInv2 = mulmod(zInv, zInv, _pp);
uint256 x2 = mulmod(_x, zInv2, _pp);
uint256 y2 = mulmod(_y, mulmod(zInv, zInv2, _pp), _pp);
return (x2, y2);
}
/// @dev Derives the y coordinate from a compressed-format point x [[SEC-1]](https://www.secg.org/SEC1-Ver-1.0.pdf).
/// @param _prefix parity byte (0x02 even, 0x03 odd)
/// @param _x coordinate x
/// @param _aa constant of curve
/// @param _bb constant of curve
/// @param _pp the modulus
/// @return y coordinate y
function deriveY(
uint8 _prefix,
uint256 _x,
uint256 _aa,
uint256 _bb,
uint256 _pp)
internal pure returns (uint256)
{
require(_prefix == 0x02 || _prefix == 0x03, "Invalid compressed EC point prefix");
// x^3 + ax + b
uint256 y2 = addmod(mulmod(_x, mulmod(_x, _x, _pp), _pp), addmod(mulmod(_x, _aa, _pp), _bb, _pp), _pp);
y2 = expMod(y2, (_pp + 1) / 4, _pp);
// uint256 cmp = yBit ^ y_ & 1;
uint256 y = (y2 + _prefix) % 2 == 0 ? y2 : _pp - y2;
return y;
}
/// @dev Check whether point (x,y) is on curve defined by a, b, and _pp.
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _aa constant of curve
/// @param _bb constant of curve
/// @param _pp the modulus
/// @return true if x,y in the curve, false else
function isOnCurve(
uint _x,
uint _y,
uint _aa,
uint _bb,
uint _pp)
internal pure returns (bool)
{
if (0 == _x || _x == _pp || 0 == _y || _y == _pp) {
return false;
}
// y^2
uint lhs = mulmod(_y, _y, _pp);
// x^3
uint rhs = mulmod(mulmod(_x, _x, _pp), _x, _pp);
if (_aa != 0) {
// x^3 + a*x
rhs = addmod(rhs, mulmod(_x, _aa, _pp), _pp);
}
if (_bb != 0) {
// x^3 + a*x + b
rhs = addmod(rhs, _bb, _pp);
}
return lhs == rhs;
}
/// @dev Calculate inverse (x, -y) of point (x, y).
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _pp the modulus
/// @return (x, -y)
function ecInv(
uint256 _x,
uint256 _y,
uint256 _pp)
internal pure returns (uint256, uint256)
{
return (_x, (_pp - _y) % _pp);
}
/// @dev Add two points (x1, y1) and (x2, y2) in affine coordinates.
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _x2 coordinate x of P2
/// @param _y2 coordinate y of P2
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = P1+P2 in affine coordinates
function ecAdd(
uint256 _x1,
uint256 _y1,
uint256 _x2,
uint256 _y2,
uint256 _aa,
uint256 _pp)
internal pure returns(uint256, uint256)
{
uint x = 0;
uint y = 0;
uint z = 0;
// Double if x1==x2 else add
if (_x1==_x2) {
(x, y, z) = jacDouble(
_x1,
_y1,
1,
_aa,
_pp);
} else {
(x, y, z) = jacAdd(
_x1,
_y1,
1,
_x2,
_y2,
1,
_pp);
}
// Get back to affine
return toAffine(
x,
y,
z,
_pp);
}
/// @dev Substract two points (x1, y1) and (x2, y2) in affine coordinates.
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _x2 coordinate x of P2
/// @param _y2 coordinate y of P2
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = P1-P2 in affine coordinates
function ecSub(
uint256 _x1,
uint256 _y1,
uint256 _x2,
uint256 _y2,
uint256 _aa,
uint256 _pp)
internal pure returns(uint256, uint256)
{
// invert square
(uint256 x, uint256 y) = ecInv(_x2, _y2, _pp);
// P1-square
return ecAdd(
_x1,
_y1,
x,
y,
_aa,
_pp);
}
/// @dev Multiply point (x1, y1, z1) times d in affine coordinates.
/// @param _k scalar to multiply
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = d*P in affine coordinates
function ecMul(
uint256 _k,
uint256 _x,
uint256 _y,
uint256 _aa,
uint256 _pp)
internal pure returns(uint256, uint256)
{
// Jacobian multiplication
(uint256 x1, uint256 y1, uint256 z1) = jacMul(
_k,
_x,
_y,
1,
_aa,
_pp);
// Get back to affine
return toAffine(
x1,
y1,
z1,
_pp);
}
/// @dev Adds two points (x1, y1, z1) and (x2 y2, z2).
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _z1 coordinate z of P1
/// @param _x2 coordinate x of square
/// @param _y2 coordinate y of square
/// @param _z2 coordinate z of square
/// @param _pp the modulus
/// @return (qx, qy, qz) P1+square in Jacobian
function jacAdd(
uint256 _x1,
uint256 _y1,
uint256 _z1,
uint256 _x2,
uint256 _y2,
uint256 _z2,
uint256 _pp)
internal pure returns (uint256, uint256, uint256)
{
if ((_x1==0)&&(_y1==0))
return (_x2, _y2, _z2);
if ((_x2==0)&&(_y2==0))
return (_x1, _y1, _z1);
// We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5
uint[4] memory zs; // z1^2, z1^3, z2^2, z2^3
zs[0] = mulmod(_z1, _z1, _pp);
zs[1] = mulmod(_z1, zs[0], _pp);
zs[2] = mulmod(_z2, _z2, _pp);
zs[3] = mulmod(_z2, zs[2], _pp);
// u1, s1, u2, s2
zs = [
mulmod(_x1, zs[2], _pp),
mulmod(_y1, zs[3], _pp),
mulmod(_x2, zs[0], _pp),
mulmod(_y2, zs[1], _pp)
];
// In case of zs[0] == zs[2] && zs[1] == zs[3], double function should be used
require(zs[0] != zs[2], "Invalid data");
uint[4] memory hr;
//h
hr[0] = addmod(zs[2], _pp - zs[0], _pp);
//r
hr[1] = addmod(zs[3], _pp - zs[1], _pp);
//h^2
hr[2] = mulmod(hr[0], hr[0], _pp);
// h^3
hr[3] = mulmod(hr[2], hr[0], _pp);
// qx = -h^3 -2u1h^2+r^2
uint256 qx = addmod(mulmod(hr[1], hr[1], _pp), _pp - hr[3], _pp);
qx = addmod(qx, _pp - mulmod(2, mulmod(zs[0], hr[2], _pp), _pp), _pp);
// qy = -s1*z1*h^3+r(u1*h^2 -x^3)
uint256 qy = mulmod(hr[1], addmod(mulmod(zs[0], hr[2], _pp), _pp - qx, _pp), _pp);
qy = addmod(qy, _pp - mulmod(zs[1], hr[3], _pp), _pp);
// qz = h*z1*z2
uint256 qz = mulmod(hr[0], mulmod(_z1, _z2, _pp), _pp);
return(qx, qy, qz);
}
/// @dev Doubles a points (x, y, z).
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _z coordinate z of P1
/// @param _pp the modulus
/// @param _aa the a scalar in the curve equation
/// @return (qx, qy, qz) 2P in Jacobian
function jacDouble(
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _aa,
uint256 _pp)
internal pure returns (uint256, uint256, uint256)
{
if (_z == 0)
return (_x, _y, _z);
uint256[3] memory square;
// We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5
// Note: there is a bug in the paper regarding the m parameter, M=3*(x1^2)+a*(z1^4)
square[0] = mulmod(_x, _x, _pp); //x1^2
square[1] = mulmod(_y, _y, _pp); //y1^2
square[2] = mulmod(_z, _z, _pp); //z1^2
// s
uint s = mulmod(4, mulmod(_x, square[1], _pp), _pp);
// m
uint m = addmod(mulmod(3, square[0], _pp), mulmod(_aa, mulmod(square[2], square[2], _pp), _pp), _pp);
// qx
uint256 qx = addmod(mulmod(m, m, _pp), _pp - addmod(s, s, _pp), _pp);
// qy = -8*y1^4 + M(S-T)
uint256 qy = addmod(mulmod(m, addmod(s, _pp - qx, _pp), _pp), _pp - mulmod(8, mulmod(square[1], square[1], _pp), _pp), _pp);
// qz = 2*y1*z1
uint256 qz = mulmod(2, mulmod(_y, _z, _pp), _pp);
return (qx, qy, qz);
}
/// @dev Multiply point (x, y, z) times d.
/// @param _d scalar to multiply
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _z coordinate z of P1
/// @param _aa constant of curve
/// @param _pp the modulus
/// @return (qx, qy, qz) d*P1 in Jacobian
function jacMul(
uint256 _d,
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _aa,
uint256 _pp)
internal pure returns (uint256, uint256, uint256)
{
uint256 remaining = _d;
uint256[3] memory point;
point[0] = _x;
point[1] = _y;
point[2] = _z;
uint256 qx = 0;
uint256 qy = 0;
uint256 qz = 1;
if (_d == 0) {
return (qx, qy, qz);
}
// Double and add algorithm
while (remaining != 0) {
if ((remaining & 1) != 0) {
(qx, qy, qz) = jacAdd(
qx,
qy,
qz,
point[0],
point[1],
point[2],
_pp);
}
remaining = remaining / 2;
(point[0], point[1], point[2]) = jacDouble(
point[0],
point[1],
point[2],
_aa,
_pp);
}
return (qx, qy, qz);
}
}
// File: vrf-solidity/contracts/VRF.sol
/**
* @title Verifiable Random Functions (VRF)
* @notice Library verifying VRF proofs using the `Secp256k1` curve and the `SHA256` hash function.
* @dev This library follows the algorithms described in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04) and [RFC6979](https://tools.ietf.org/html/rfc6979).
* It supports the _SECP256K1_SHA256_TAI_ cipher suite, i.e. the aforementioned algorithms using `SHA256` and the `Secp256k1` curve.
* @author Witnet Foundation
*/
library VRF {
/**
* Secp256k1 parameters
*/
// Generator coordinate `x` of the EC curve
uint256 public constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
// Generator coordinate `y` of the EC curve
uint256 public constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
// Constant `a` of EC equation
uint256 public constant AA = 0;
// Constant `b` of EC equation
uint256 public constant BB = 7;
// Prime number of the curve
uint256 public constant PP = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
// Order of the curve
uint256 public constant NN = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
/// @dev Public key derivation from private key.
/// @param _d The scalar
/// @param _x The coordinate x
/// @param _y The coordinate y
/// @return (qx, qy) The derived point
function derivePoint(uint256 _d, uint256 _x, uint256 _y) internal pure returns (uint256, uint256) {
return EllipticCurve.ecMul(
_d,
_x,
_y,
AA,
PP
);
}
/// @dev Function to derive the `y` coordinate given the `x` coordinate and the parity byte (`0x03` for odd `y` and `0x04` for even `y`).
/// @param _yByte The parity byte following the ec point compressed format
/// @param _x The coordinate `x` of the point
/// @return The coordinate `y` of the point
function deriveY(uint8 _yByte, uint256 _x) internal pure returns (uint256) {
return EllipticCurve.deriveY(
_yByte,
_x,
AA,
BB,
PP);
}
/// @dev Computes the VRF hash output as result of the digest of a ciphersuite-dependent prefix
/// concatenated with the gamma point
/// @param _gammaX The x-coordinate of the gamma EC point
/// @param _gammaY The y-coordinate of the gamma EC point
/// @return The VRF hash ouput as shas256 digest
function gammaToHash(uint256 _gammaX, uint256 _gammaY) internal pure returns (bytes32) {
bytes memory c = abi.encodePacked(
// Cipher suite code (SECP256K1-SHA256-TAI is 0xFE)
uint8(0xFE),
// 0x01
uint8(0x03),
// Compressed Gamma Point
encodePoint(_gammaX, _gammaY));
return sha256(c);
}
/// @dev VRF verification by providing the public key, the message and the VRF proof.
/// This function computes several elliptic curve operations which may lead to extensive gas consumption.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @param _message The message (in bytes) used for computing the VRF
/// @return true, if VRF proof is valid
function verify(uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message) internal pure returns (bool) {
// Step 2: Hash to try and increment (outputs a hashed value, a finite EC point in G)
uint256[2] memory hPoint;
(hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message);
// Step 3: U = s*B - c*Y (where B is the generator)
(uint256 uPointX, uint256 uPointY) = ecMulSubMul(
_proof[3],
GX,
GY,
_proof[2],
_publicKey[0],
_publicKey[1]);
// Step 4: V = s*H - c*Gamma
(uint256 vPointX, uint256 vPointY) = ecMulSubMul(
_proof[3],
hPoint[0],
hPoint[1],
_proof[2],
_proof[0],_proof[1]);
// Step 5: derived c from hash points(...)
bytes16 derivedC = hashPoints(
hPoint[0],
hPoint[1],
_proof[0],
_proof[1],
uPointX,
uPointY,
vPointX,
vPointY);
// Step 6: Check validity c == c'
return uint128(derivedC) == _proof[2];
}
/// @dev VRF fast verification by providing the public key, the message, the VRF proof and several intermediate elliptic curve points that enable the verification shortcut.
/// This function leverages the EVM's `ecrecover` precompile to verify elliptic curve multiplications by decreasing the security from 32 to 20 bytes.
/// Based on the original idea of Vitalik Buterin: https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @param _message The message (in bytes) used for computing the VRF
/// @param _uPoint The `u` EC point defined as `U = s*B - c*Y`
/// @param _vComponents The components required to compute `v` as `V = s*H - c*Gamma`
/// @return true, if VRF proof is valid
function fastVerify(
uint256[2] memory _publicKey,
uint256[4] memory _proof,
bytes memory _message,
uint256[2] memory _uPoint,
uint256[4] memory _vComponents)
internal pure returns (bool)
{
// Step 2: Hash to try and increment -> hashed value, a finite EC point in G
uint256[2] memory hPoint;
(hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message);
// Step 3 & Step 4:
// U = s*B - c*Y (where B is the generator)
// V = s*H - c*Gamma
if (!ecMulSubMulVerify(
_proof[3],
_proof[2],
_publicKey[0],
_publicKey[1],
_uPoint[0],
_uPoint[1]) ||
!ecMulVerify(
_proof[3],
hPoint[0],
hPoint[1],
_vComponents[0],
_vComponents[1]) ||
!ecMulVerify(
_proof[2],
_proof[0],
_proof[1],
_vComponents[2],
_vComponents[3])
)
{
return false;
}
(uint256 vPointX, uint256 vPointY) = EllipticCurve.ecSub(
_vComponents[0],
_vComponents[1],
_vComponents[2],
_vComponents[3],
AA,
PP);
// Step 5: derived c from hash points(...)
bytes16 derivedC = hashPoints(
hPoint[0],
hPoint[1],
_proof[0],
_proof[1],
_uPoint[0],
_uPoint[1],
vPointX,
vPointY);
// Step 6: Check validity c == c'
return uint128(derivedC) == _proof[2];
}
/// @dev Decode VRF proof from bytes
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
function decodeProof(bytes memory _proof) internal pure returns (uint[4] memory) {
require(_proof.length == 81, "Malformed VRF proof");
uint8 gammaSign;
uint256 gammaX;
uint128 c;
uint256 s;
assembly {
gammaSign := mload(add(_proof, 1))
gammaX := mload(add(_proof, 33))
c := mload(add(_proof, 49))
s := mload(add(_proof, 81))
}
uint256 gammaY = deriveY(gammaSign, gammaX);
return [
gammaX,
gammaY,
c,
s];
}
/// @dev Decode EC point from bytes
/// @param _point The EC point as bytes
/// @return The point as `[point-x, point-y]`
function decodePoint(bytes memory _point) internal pure returns (uint[2] memory) {
require(_point.length == 33, "Malformed compressed EC point");
uint8 sign;
uint256 x;
assembly {
sign := mload(add(_point, 1))
x := mload(add(_point, 33))
}
uint256 y = deriveY(sign, x);
return [x, y];
}
/// @dev Compute the parameters (EC points) required for the VRF fast verification function.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @param _message The message (in bytes) used for computing the VRF
/// @return The fast verify required parameters as the tuple `([uPointX, uPointY], [sHX, sHY, cGammaX, cGammaY])`
function computeFastVerifyParams(uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message)
internal pure returns (uint256[2] memory, uint256[4] memory)
{
// Requirements for Step 3: U = s*B - c*Y (where B is the generator)
uint256[2] memory hPoint;
(hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message);
(uint256 uPointX, uint256 uPointY) = ecMulSubMul(
_proof[3],
GX,
GY,
_proof[2],
_publicKey[0],
_publicKey[1]);
// Requirements for Step 4: V = s*H - c*Gamma
(uint256 sHX, uint256 sHY) = derivePoint(_proof[3], hPoint[0], hPoint[1]);
(uint256 cGammaX, uint256 cGammaY) = derivePoint(_proof[2], _proof[0], _proof[1]);
return (
[uPointX, uPointY],
[
sHX,
sHY,
cGammaX,
cGammaY
]);
}
/// @dev Function to convert a `Hash(PK|DATA)` to a point in the curve as defined in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04).
/// Used in Step 2 of VRF verification function.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _message The message used for computing the VRF
/// @return The hash point in affine cooridnates
function hashToTryAndIncrement(uint256[2] memory _publicKey, bytes memory _message) internal pure returns (uint, uint) {
// Step 1: public key to bytes
// Step 2: V = cipher_suite | 0x01 | public_key_bytes | message | ctr
bytes memory c = abi.encodePacked(
// Cipher suite code (SECP256K1-SHA256-TAI is 0xFE)
uint8(254),
// 0x01
uint8(1),
// Public Key
encodePoint(_publicKey[0], _publicKey[1]),
// Message
_message);
// Step 3: find a valid EC point
// Loop over counter ctr starting at 0x00 and do hash
for (uint8 ctr = 0; ctr < 256; ctr++) {
// Counter update
// c[cLength-1] = byte(ctr);
bytes32 sha = sha256(abi.encodePacked(c, ctr));
// Step 4: arbitraty string to point and check if it is on curve
uint hPointX = uint256(sha);
uint hPointY = deriveY(2, hPointX);
if (EllipticCurve.isOnCurve(
hPointX,
hPointY,
AA,
BB,
PP))
{
// Step 5 (omitted): calculate H (cofactor is 1 on secp256k1)
// If H is not "INVALID" and cofactor > 1, set H = cofactor * H
return (hPointX, hPointY);
}
}
revert("No valid point was found");
}
/// @dev Function to hash a certain set of points as specified in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04).
/// Used in Step 5 of VRF verification function.
/// @param _hPointX The coordinate `x` of point `H`
/// @param _hPointY The coordinate `y` of point `H`
/// @param _gammaX The coordinate `x` of the point `Gamma`
/// @param _gammaX The coordinate `y` of the point `Gamma`
/// @param _uPointX The coordinate `x` of point `U`
/// @param _uPointY The coordinate `y` of point `U`
/// @param _vPointX The coordinate `x` of point `V`
/// @param _vPointY The coordinate `y` of point `V`
/// @return The first half of the digest of the points using SHA256
function hashPoints(
uint256 _hPointX,
uint256 _hPointY,
uint256 _gammaX,
uint256 _gammaY,
uint256 _uPointX,
uint256 _uPointY,
uint256 _vPointX,
uint256 _vPointY)
internal pure returns (bytes16)
{
bytes memory c = abi.encodePacked(
// Ciphersuite 0xFE
uint8(254),
// Prefix 0x02
uint8(2),
// Points to Bytes
encodePoint(_hPointX, _hPointY),
encodePoint(_gammaX, _gammaY),
encodePoint(_uPointX, _uPointY),
encodePoint(_vPointX, _vPointY)
);
// Hash bytes and truncate
bytes32 sha = sha256(c);
bytes16 half1;
assembly {
let freemem_pointer := mload(0x40)
mstore(add(freemem_pointer,0x00), sha)
half1 := mload(add(freemem_pointer,0x00))
}
return half1;
}
/// @dev Encode an EC point to bytes
/// @param _x The coordinate `x` of the point
/// @param _y The coordinate `y` of the point
/// @return The point coordinates as bytes
function encodePoint(uint256 _x, uint256 _y) internal pure returns (bytes memory) {
uint8 prefix = uint8(2 + (_y % 2));
return abi.encodePacked(prefix, _x);
}
/// @dev Substracts two key derivation functionsas `s1*A - s2*B`.
/// @param _scalar1 The scalar `s1`
/// @param _a1 The `x` coordinate of point `A`
/// @param _a2 The `y` coordinate of point `A`
/// @param _scalar2 The scalar `s2`
/// @param _b1 The `x` coordinate of point `B`
/// @param _b2 The `y` coordinate of point `B`
/// @return The derived point in affine cooridnates
function ecMulSubMul(
uint256 _scalar1,
uint256 _a1,
uint256 _a2,
uint256 _scalar2,
uint256 _b1,
uint256 _b2)
internal pure returns (uint256, uint256)
{
(uint256 m1, uint256 m2) = derivePoint(_scalar1, _a1, _a2);
(uint256 n1, uint256 n2) = derivePoint(_scalar2, _b1, _b2);
(uint256 r1, uint256 r2) = EllipticCurve.ecSub(
m1,
m2,
n1,
n2,
AA,
PP);
return (r1, r2);
}
/// @dev Verify an Elliptic Curve multiplication of the form `(qx,qy) = scalar*(x,y)` by using the precompiled `ecrecover` function.
/// The usage of the precompiled `ecrecover` function decreases the security from 32 to 20 bytes.
/// Based on the original idea of Vitalik Buterin: https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9
/// @param _scalar The scalar of the point multiplication
/// @param _x The coordinate `x` of the point
/// @param _y The coordinate `y` of the point
/// @param _qx The coordinate `x` of the multiplication result
/// @param _qy The coordinate `y` of the multiplication result
/// @return true, if first 20 bytes match
function ecMulVerify(
uint256 _scalar,
uint256 _x,
uint256 _y,
uint256 _qx,
uint256 _qy)
internal pure returns(bool)
{
address result = ecrecover(
0,
_y % 2 != 0 ? 28 : 27,
bytes32(_x),
bytes32(mulmod(_scalar, _x, NN)));
return pointToAddress(_qx, _qy) == result;
}
/// @dev Verify an Elliptic Curve operation of the form `Q = scalar1*(gx,gy) - scalar2*(x,y)` by using the precompiled `ecrecover` function, where `(gx,gy)` is the generator of the EC.
/// The usage of the precompiled `ecrecover` function decreases the security from 32 to 20 bytes.
/// Based on SolCrypto library: https://github.com/HarryR/solcrypto
/// @param _scalar1 The scalar of the multiplication of `(gx,gy)`
/// @param _scalar2 The scalar of the multiplication of `(x,y)`
/// @param _x The coordinate `x` of the point to be mutiply by `scalar2`
/// @param _y The coordinate `y` of the point to be mutiply by `scalar2`
/// @param _qx The coordinate `x` of the equation result
/// @param _qy The coordinate `y` of the equation result
/// @return true, if first 20 bytes match
function ecMulSubMulVerify(
uint256 _scalar1,
uint256 _scalar2,
uint256 _x,
uint256 _y,
uint256 _qx,
uint256 _qy)
internal pure returns(bool)
{
uint256 scalar1 = (NN - _scalar1) % NN;
scalar1 = mulmod(scalar1, _x, NN);
uint256 scalar2 = (NN - _scalar2) % NN;
address result = ecrecover(
bytes32(scalar1),
_y % 2 != 0 ? 28 : 27,
bytes32(_x),
bytes32(mulmod(scalar2, _x, NN)));
return pointToAddress(_qx, _qy) == result;
}
/// @dev Gets the address corresponding to the EC point digest (keccak256), i.e. the first 20 bytes of the digest.
/// This function is used for performing a fast EC multiplication verification.
/// @param _x The coordinate `x` of the point
/// @param _y The coordinate `y` of the point
/// @return The address of the EC point digest (keccak256)
function pointToAddress(uint256 _x, uint256 _y)
internal pure returns(address)
{
return address(uint256(keccak256(abi.encodePacked(_x, _y))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
}
}
// File: witnet-ethereum-bridge/contracts/ActiveBridgeSetLib.sol
/**
* @title Active Bridge Set (ABS) library
* @notice This library counts the number of bridges that were active recently.
*/
library ActiveBridgeSetLib {
// Number of Ethereum blocks during which identities can be pushed into a single activity slot
uint8 public constant CLAIM_BLOCK_PERIOD = 8;
// Number of activity slots in the ABS
uint8 public constant ACTIVITY_LENGTH = 100;
struct ActiveBridgeSet {
// Mapping of activity slots with participating identities
mapping (uint16 => address[]) epochIdentities;
// Mapping of identities with their participation count
mapping (address => uint16) identityCount;
// Number of identities in the Active Bridge Set (consolidated during `ACTIVITY_LENGTH`)
uint32 activeIdentities;
// Number of identities for the next activity slot (to be updated in the next activity slot)
uint32 nextActiveIdentities;
// Last used block number during an activity update
uint256 lastBlockNumber;
}
modifier validBlockNumber(uint256 _blockFromArguments, uint256 _blockFromContractState) {
require (_blockFromArguments >= _blockFromContractState, "The provided block is older than the last updated block");
_;
}
/// @dev Updates activity in Witnet without requiring protocol participation.
/// @param _abs The Active Bridge Set structure to be updated.
/// @param _blockNumber The block number up to which the activity should be updated.
function updateActivity(ActiveBridgeSet storage _abs, uint256 _blockNumber)
internal
validBlockNumber(_blockNumber, _abs.lastBlockNumber)
{
(uint16 currentSlot, uint16 lastSlot, bool overflow) = getSlots(_abs, _blockNumber);
// Avoid gas cost if ABS is up to date
require(
updateABS(
_abs,
currentSlot,
lastSlot,
overflow
), "The ABS was already up to date");
_abs.lastBlockNumber = _blockNumber;
}
/// @dev Pushes activity updates through protocol activities (implying insertion of identity).
/// @param _abs The Active Bridge Set structure to be updated.
/// @param _address The address pushing the activity.
/// @param _blockNumber The block number up to which the activity should be updated.
function pushActivity(ActiveBridgeSet storage _abs, address _address, uint256 _blockNumber)
internal
validBlockNumber(_blockNumber, _abs.lastBlockNumber)
returns (bool success)
{
(uint16 currentSlot, uint16 lastSlot, bool overflow) = getSlots(_abs, _blockNumber);
// Update ABS and if it was already up to date, check if identities already counted
if (
updateABS(
_abs,
currentSlot,
lastSlot,
overflow
))
{
_abs.lastBlockNumber = _blockNumber;
} else {
// Check if address was already counted as active identity in this current activity slot
uint256 epochIdsLength = _abs.epochIdentities[currentSlot].length;
for (uint256 i; i < epochIdsLength; i++) {
if (_abs.epochIdentities[currentSlot][i] == _address) {
return false;
}
}
}
// Update current activity slot with identity:
// 1. Add currentSlot to `epochIdentities` with address
// 2. If count = 0, increment by 1 `nextActiveIdentities`
// 3. Increment by 1 the count of the identity
_abs.epochIdentities[currentSlot].push(_address);
if (_abs.identityCount[_address] == 0) {
_abs.nextActiveIdentities++;
}
_abs.identityCount[_address]++;
return true;
}
/// @dev Checks if an address is a member of the ABS.
/// @param _abs The Active Bridge Set structure from the Witnet Requests Board.
/// @param _address The address to check.
/// @return true if address is member of ABS.
function absMembership(ActiveBridgeSet storage _abs, address _address) internal view returns (bool) {
return _abs.identityCount[_address] > 0;
}
/// @dev Gets the slots of the last block seen by the ABS provided and the block number provided.
/// @param _abs The Active Bridge Set structure containing the last block.
/// @param _blockNumber The block number from which to get the current slot.
/// @return (currentSlot, lastSlot, overflow), where overflow implies the block difference > CLAIM_BLOCK_PERIOD* ACTIVITY_LENGTH.
function getSlots(ActiveBridgeSet storage _abs, uint256 _blockNumber) private view returns (uint8, uint8, bool) {
// Get current activity slot number
uint8 currentSlot = uint8((_blockNumber / CLAIM_BLOCK_PERIOD) % ACTIVITY_LENGTH);
// Get last actitivy slot number
uint8 lastSlot = uint8((_abs.lastBlockNumber / CLAIM_BLOCK_PERIOD) % ACTIVITY_LENGTH);
// Check if there was an activity slot overflow
// `ACTIVITY_LENGTH` is changed to `uint16` here to ensure the multiplication doesn't overflow silently
bool overflow = (_blockNumber - _abs.lastBlockNumber) >= CLAIM_BLOCK_PERIOD * uint16(ACTIVITY_LENGTH);
return (currentSlot, lastSlot, overflow);
}
/// @dev Updates the provided ABS according to the slots provided.
/// @param _abs The Active Bridge Set to be updated.
/// @param _currentSlot The current slot.
/// @param _lastSlot The last slot seen by the ABS.
/// @param _overflow Whether the current slot has overflown the last slot.
/// @return True if update occurred.
function updateABS(
ActiveBridgeSet storage _abs,
uint16 _currentSlot,
uint16 _lastSlot,
bool _overflow)
private
returns (bool)
{
// If there are more than `ACTIVITY_LENGTH` slots empty => remove entirely the ABS
if (_overflow) {
flushABS(_abs, _lastSlot, _lastSlot);
// If ABS are not up to date => fill previous activity slots with empty activities
} else if (_currentSlot != _lastSlot) {
flushABS(_abs, _currentSlot, _lastSlot);
} else {
return false;
}
return true;
}
/// @dev Flushes the provided ABS record between lastSlot and currentSlot.
/// @param _abs The Active Bridge Set to be flushed.
/// @param _currentSlot The current slot.
function flushABS(ActiveBridgeSet storage _abs, uint16 _currentSlot, uint16 _lastSlot) private {
// For each slot elapsed, remove identities and update `nextActiveIdentities` count
for (uint16 slot = (_lastSlot + 1) % ACTIVITY_LENGTH ; slot != _currentSlot ; slot = (slot + 1) % ACTIVITY_LENGTH) {
flushSlot(_abs, slot);
}
// Update current activity slot
flushSlot(_abs, _currentSlot);
_abs.activeIdentities = _abs.nextActiveIdentities;
}
/// @dev Flushes a slot of the provided ABS.
/// @param _abs The Active Bridge Set to be flushed.
/// @param _slot The slot to be flushed.
function flushSlot(ActiveBridgeSet storage _abs, uint16 _slot) private {
// For a given slot, go through all identities to flush them
uint256 epochIdsLength = _abs.epochIdentities[_slot].length;
for (uint256 id = 0; id < epochIdsLength; id++) {
flushIdentity(_abs, _abs.epochIdentities[_slot][id]);
}
delete _abs.epochIdentities[_slot];
}
/// @dev Decrements the appearance counter of an identity from the provided ABS. If the counter reaches 0, the identity is flushed.
/// @param _abs The Active Bridge Set to be flushed.
/// @param _address The address to be flushed.
function flushIdentity(ActiveBridgeSet storage _abs, address _address) private {
require(absMembership(_abs, _address), "The identity address is already out of the ARS");
// Decrement the count of an identity, and if it reaches 0, delete it and update `nextActiveIdentities`count
_abs.identityCount[_address]--;
if (_abs.identityCount[_address] == 0) {
delete _abs.identityCount[_address];
_abs.nextActiveIdentities--;
}
}
}
// File: witnet-ethereum-bridge/contracts/WitnetRequestsBoardInterface.sol
/**
* @title Witnet Requests Board Interface
* @notice Interface of a Witnet Request Board (WRB)
* It defines how to interact with the WRB in order to support:
* - Post and upgrade a data request
* - Read the result of a dr
* @author Witnet Foundation
*/
interface WitnetRequestsBoardInterface {
/// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value.
/// @param _dr The bytes corresponding to the Protocol Buffers serialization of the data request output.
/// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request.
/// @return The unique identifier of the data request.
function postDataRequest(bytes calldata _dr, uint256 _tallyReward) external payable returns(uint256);
/// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward.
/// @param _id The unique identifier of the data request.
/// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward.
function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable;
/// @dev Retrieves the DR hash of the id from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The hash of the DR
function readDrHash (uint256 _id) external view returns(uint256);
/// @dev Retrieves the result (if already available) of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the DR
function readResult (uint256 _id) external view returns(bytes memory);
/// @notice Verifies if the block relay can be upgraded.
/// @return true if contract is upgradable.
function isUpgradable(address _address) external view returns(bool);
}
// File: witnet-ethereum-bridge/contracts/WitnetRequestsBoard.sol
/**
* @title Witnet Requests Board
* @notice Contract to bridge requests to Witnet.
* @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network.
* The result of the requests will be posted back to this contract by the bridge nodes too.
* @author Witnet Foundation
*/
contract WitnetRequestsBoard is WitnetRequestsBoardInterface {
using ActiveBridgeSetLib for ActiveBridgeSetLib.ActiveBridgeSet;
// Expiration period after which a Witnet Request can be claimed again
uint256 public constant CLAIM_EXPIRATION = 13;
struct DataRequest {
bytes dr;
uint256 inclusionReward;
uint256 tallyReward;
bytes result;
// Block number at which the DR was claimed for the last time
uint256 blockNumber;
uint256 drHash;
address payable pkhClaim;
}
// Owner of the Witnet Request Board
address public witnet;
// Block Relay proxy prividing verification functions
BlockRelayProxy public blockRelay;
// Witnet Requests within the board
DataRequest[] public requests;
// Set of recently active bridges
ActiveBridgeSetLib.ActiveBridgeSet public abs;
// Replication factor for Active Bridge Set identities
uint8 public repFactor;
// Event emitted when a new DR is posted
event PostedRequest(address indexed _from, uint256 _id);
// Event emitted when a DR inclusion proof is posted
event IncludedRequest(address indexed _from, uint256 _id);
// Event emitted when a result proof is posted
event PostedResult(address indexed _from, uint256 _id);
// Ensures the reward is not greater than the value
modifier payingEnough(uint256 _value, uint256 _tally) {
require(_value >= _tally, "Transaction value needs to be equal or greater than tally reward");
_;
}
// Ensures the poe is valid
modifier poeValid(
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers) {
require(
verifyPoe(
_poe,
_publicKey,
_uPoint,
_vPointHelpers),
"Not a valid PoE");
_;
}
// Ensures signature (sign(msg.sender)) is valid
modifier validSignature(
uint256[2] memory _publicKey,
bytes memory addrSignature) {
require(verifySig(abi.encodePacked(msg.sender), _publicKey, addrSignature), "Not a valid signature");
_;
}
// Ensures the DR inclusion proof has not been reported yet
modifier drNotIncluded(uint256 _id) {
require(requests[_id].drHash == 0, "DR already included");
_;
}
// Ensures the DR inclusion has been already reported
modifier drIncluded(uint256 _id) {
require(requests[_id].drHash != 0, "DR not yet included");
_;
}
// Ensures the result has not been reported yet
modifier resultNotIncluded(uint256 _id) {
require(requests[_id].result.length == 0, "Result already included");
_;
}
// Ensures the VRF is valid
modifier vrfValid(
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers) virtual {
require(
VRF.fastVerify(
_publicKey,
_poe,
getLastBeacon(),
_uPoint,
_vPointHelpers),
"Not a valid VRF");
_;
}
// Ensures the address belongs to the active bridge set
modifier absMember(address _address) {
require(abs.absMembership(_address), "Not a member of the ABS");
_;
}
/**
* @notice Include an address to specify the Witnet Block Relay and a replication factor.
* @param _blockRelayAddress BlockRelayProxy address.
* @param _repFactor replication factor.
*/
constructor(address _blockRelayAddress, uint8 _repFactor) public {
blockRelay = BlockRelayProxy(_blockRelayAddress);
witnet = msg.sender;
// Insert an empty request so as to initialize the requests array with length > 0
DataRequest memory request;
requests.push(request);
repFactor = _repFactor;
}
/// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value.
/// @param _serialized The bytes corresponding to the Protocol Buffers serialization of the data request output.
/// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request.
/// @return The unique identifier of the data request.
function postDataRequest(bytes calldata _serialized, uint256 _tallyReward)
external
payable
payingEnough(msg.value, _tallyReward)
override
returns(uint256)
{
// The initial length of the `requests` array will become the ID of the request for everything related to the WRB
uint256 id = requests.length;
// Create a new `DataRequest` object and initialize all the non-default fields
DataRequest memory request;
request.dr = _serialized;
request.inclusionReward = SafeMath.sub(msg.value, _tallyReward);
request.tallyReward = _tallyReward;
// Push the new request into the contract state
requests.push(request);
// Let observers know that a new request has been posted
emit PostedRequest(msg.sender, id);
return id;
}
/// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward.
/// @param _id The unique identifier of the data request.
/// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward.
function upgradeDataRequest(uint256 _id, uint256 _tallyReward)
external
payable
payingEnough(msg.value, _tallyReward)
resultNotIncluded(_id)
override
{
if (requests[_id].drHash != 0) {
require(
msg.value == _tallyReward,
"Txn value should equal result reward argument (request reward already paid)"
);
requests[_id].tallyReward = SafeMath.add(requests[_id].tallyReward, _tallyReward);
} else {
requests[_id].inclusionReward = SafeMath.add(requests[_id].inclusionReward, msg.value - _tallyReward);
requests[_id].tallyReward = SafeMath.add(requests[_id].tallyReward, _tallyReward);
}
}
/// @dev Checks if the data requests from a list are claimable or not.
/// @param _ids The list of data request identifiers to be checked.
/// @return An array of booleans indicating if data requests are claimable or not.
function checkDataRequestsClaimability(uint256[] calldata _ids) external view returns (bool[] memory) {
uint256 idsLength = _ids.length;
bool[] memory validIds = new bool[](idsLength);
for (uint i = 0; i < idsLength; i++) {
uint256 index = _ids[i];
validIds[i] = (dataRequestCanBeClaimed(requests[index])) &&
requests[index].drHash == 0 &&
index < requests.length &&
requests[index].result.length == 0;
}
return validIds;
}
/// @dev Presents a proof of inclusion to prove that the request was posted into Witnet so as to unlock the inclusion reward that was put aside for the claiming identity (public key hash).
/// @param _id The unique identifier of the data request.
/// @param _poi A proof of inclusion proving that the data request appears listed in one recent block in Witnet.
/// @param _index The index in the merkle tree.
/// @param _blockHash The hash of the block in which the data request was inserted.
/// @param _epoch The epoch in which the blockHash was created.
function reportDataRequestInclusion(
uint256 _id,
uint256[] calldata _poi,
uint256 _index,
uint256 _blockHash,
uint256 _epoch)
external
drNotIncluded(_id)
{
// Check the data request has been claimed
require(dataRequestCanBeClaimed(requests[_id]) == false, "Data Request has not yet been claimed");
uint256 drOutputHash = uint256(sha256(requests[_id].dr));
uint256 drHash = uint256(sha256(abi.encodePacked(drOutputHash, _poi[0])));
// Update the state upon which this function depends before the external call
requests[_id].drHash = drHash;
require(
blockRelay.verifyDrPoi(
_poi,
_blockHash,
_epoch,
_index,
drOutputHash), "Invalid PoI");
requests[_id].pkhClaim.transfer(requests[_id].inclusionReward);
// Push requests[_id].pkhClaim to abs
abs.pushActivity(requests[_id].pkhClaim, block.number);
emit IncludedRequest(msg.sender, _id);
}
/// @dev Reports the result of a data request in Witnet.
/// @param _id The unique identifier of the data request.
/// @param _poi A proof of inclusion proving that the data in _result has been acknowledged by the Witnet network as being the final result for the data request by putting in a tally transaction inside a Witnet block.
/// @param _index The position of the tally transaction in the tallies-only merkle tree in the Witnet block.
/// @param _blockHash The hash of the block in which the result (tally) was inserted.
/// @param _epoch The epoch in which the blockHash was created.
/// @param _result The result itself as bytes.
function reportResult(
uint256 _id,
uint256[] calldata _poi,
uint256 _index,
uint256 _blockHash,
uint256 _epoch,
bytes calldata _result)
external
drIncluded(_id)
resultNotIncluded(_id)
absMember(msg.sender)
{
// Ensures the result byes do not have zero length
// This would not be a valid encoding with CBOR and could trigger a reentrancy attack
require(_result.length != 0, "Result has zero length");
// Update the state upon which this function depends before the external call
requests[_id].result = _result;
uint256 resHash = uint256(sha256(abi.encodePacked(requests[_id].drHash, _result)));
require(
blockRelay.verifyTallyPoi(
_poi,
_blockHash,
_epoch,
_index,
resHash), "Invalid PoI");
msg.sender.transfer(requests[_id].tallyReward);
emit PostedResult(msg.sender, _id);
}
/// @dev Retrieves the bytes of the serialization of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the data request as bytes.
function readDataRequest(uint256 _id) external view returns(bytes memory) {
require(requests.length > _id, "Id not found");
return requests[_id].dr;
}
/// @dev Retrieves the result (if already available) of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the DR
function readResult(uint256 _id) external view override returns(bytes memory) {
require(requests.length > _id, "Id not found");
return requests[_id].result;
}
/// @dev Retrieves hash of the data request transaction in Witnet.
/// @param _id The unique identifier of the data request.
/// @return The hash of the DataRequest transaction in Witnet.
function readDrHash(uint256 _id) external view override returns(uint256) {
require(requests.length > _id, "Id not found");
return requests[_id].drHash;
}
/// @dev Returns the number of data requests in the WRB.
/// @return the number of data requests in the WRB.
function requestsCount() external view returns(uint256) {
return requests.length;
}
/// @notice Wrapper around the decodeProof from VRF library.
/// @dev Decode VRF proof from bytes.
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`.
/// @return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`.
function decodeProof(bytes calldata _proof) external pure returns (uint[4] memory) {
return VRF.decodeProof(_proof);
}
/// @notice Wrapper around the decodePoint from VRF library.
/// @dev Decode EC point from bytes.
/// @param _point The EC point as bytes.
/// @return The point as `[point-x, point-y]`.
function decodePoint(bytes calldata _point) external pure returns (uint[2] memory) {
return VRF.decodePoint(_point);
}
/// @dev Wrapper around the computeFastVerifyParams from VRF library.
/// @dev Compute the parameters (EC points) required for the VRF fast verification function..
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`.
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`.
/// @param _message The message (in bytes) used for computing the VRF.
/// @return The fast verify required parameters as the tuple `([uPointX, uPointY], [sHX, sHY, cGammaX, cGammaY])`.
function computeFastVerifyParams(uint256[2] calldata _publicKey, uint256[4] calldata _proof, bytes calldata _message)
external pure returns (uint256[2] memory, uint256[4] memory)
{
return VRF.computeFastVerifyParams(_publicKey, _proof, _message);
}
/// @dev Updates the ABS activity with the block number provided.
/// @param _blockNumber update the ABS until this block number.
function updateAbsActivity(uint256 _blockNumber) external {
require (_blockNumber <= block.number, "The provided block number has not been reached");
abs.updateActivity(_blockNumber);
}
/// @dev Verifies if the contract is upgradable.
/// @return true if the contract upgradable.
function isUpgradable(address _address) external view override returns(bool) {
if (_address == witnet) {
return true;
}
return false;
}
/// @dev Claim drs to be posted to Witnet by the node.
/// @param _ids Data request ids to be claimed.
/// @param _poe PoE claiming eligibility.
/// @param _uPoint uPoint coordinates as [uPointX, uPointY] corresponding to U = s*B - c*Y.
/// @param _vPointHelpers helpers for calculating the V point as [(s*H)X, (s*H)Y, cGammaX, cGammaY]. V = s*H + cGamma.
function claimDataRequests(
uint256[] memory _ids,
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers,
bytes memory addrSignature)
public
validSignature(_publicKey, addrSignature)
poeValid(_poe,_publicKey, _uPoint,_vPointHelpers)
returns(bool)
{
for (uint i = 0; i < _ids.length; i++) {
require(
dataRequestCanBeClaimed(requests[_ids[i]]),
"One of the listed data requests was already claimed"
);
requests[_ids[i]].pkhClaim = msg.sender;
requests[_ids[i]].blockNumber = block.number;
}
return true;
}
/// @dev Read the beacon of the last block inserted.
/// @return bytes to be signed by the node as PoE.
function getLastBeacon() public view virtual returns(bytes memory) {
return blockRelay.getLastBeacon();
}
/// @dev Claim drs to be posted to Witnet by the node.
/// @param _poe PoE claiming eligibility.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`.
/// @param _uPoint uPoint coordinates as [uPointX, uPointY] corresponding to U = s*B - c*Y.
/// @param _vPointHelpers helpers for calculating the V point as [(s*H)X, (s*H)Y, cGammaX, cGammaY]. V = s*H + cGamma.
function verifyPoe(
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers)
internal
view
vrfValid(_poe,_publicKey, _uPoint,_vPointHelpers)
returns(bool)
{
uint256 vrf = uint256(VRF.gammaToHash(_poe[0], _poe[1]));
// True if vrf/(2^{256} -1) <= repFactor/abs.activeIdentities
if (abs.activeIdentities < repFactor) {
return true;
}
// We rewrote it as vrf <= ((2^{256} -1)/abs.activeIdentities)*repFactor to gain efficiency
if (vrf <= ((~uint256(0)/abs.activeIdentities)*repFactor)) {
return true;
}
return false;
}
/// @dev Verifies the validity of a signature.
/// @param _message message to be verified.
/// @param _publicKey public key of the signer as `[pubKey-x, pubKey-y]`.
/// @param _addrSignature the signature to verify asas r||s||v.
/// @return true or false depending the validity.
function verifySig(
bytes memory _message,
uint256[2] memory _publicKey,
bytes memory _addrSignature)
internal
pure
returns(bool)
{
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(_addrSignature, 0x20))
s := mload(add(_addrSignature, 0x40))
v := byte(0, mload(add(_addrSignature, 0x60)))
}
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return false;
}
if (v != 0 && v != 1) {
return false;
}
v = 28 - v;
bytes32 msgHash = sha256(_message);
address hashedKey = VRF.pointToAddress(_publicKey[0], _publicKey[1]);
return ecrecover(
msgHash,
v,
r,
s) == hashedKey;
}
function dataRequestCanBeClaimed(DataRequest memory _request) private view returns (bool) {
return
(_request.blockNumber == 0 || block.number - _request.blockNumber > CLAIM_EXPIRATION) &&
_request.drHash == 0 &&
_request.result.length == 0;
}
}
// File: witnet-ethereum-bridge/contracts/WitnetRequestsBoardProxy.sol
/**
* @title Block Relay Proxy
* @notice Contract to act as a proxy between the Witnet Bridge Interface and the Block Relay.
* @author Witnet Foundation
*/
contract WitnetRequestsBoardProxy {
// Address of the Witnet Request Board contract that is currently being used
address public witnetRequestsBoardAddress;
// Struct if the information of each controller
struct ControllerInfo {
// Address of the Controller
address controllerAddress;
// The lastId of the previous Controller
uint256 lastId;
}
// Last id of the WRB controller
uint256 internal currentLastId;
// Instance of the current WitnetRequestBoard
WitnetRequestsBoardInterface internal witnetRequestsBoardInstance;
// Array with the controllers that have been used in the Proxy
ControllerInfo[] internal controllers;
modifier notIdentical(address _newAddress) {
require(_newAddress != witnetRequestsBoardAddress, "The provided Witnet Requests Board instance address is already in use");
_;
}
/**
* @notice Include an address to specify the Witnet Request Board.
* @param _witnetRequestsBoardAddress WitnetRequestBoard address.
*/
constructor(address _witnetRequestsBoardAddress) public {
// Initialize the first epoch pointing to the first controller
controllers.push(ControllerInfo({controllerAddress: _witnetRequestsBoardAddress, lastId: 0}));
witnetRequestsBoardAddress = _witnetRequestsBoardAddress;
witnetRequestsBoardInstance = WitnetRequestsBoardInterface(_witnetRequestsBoardAddress);
}
/// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value.
/// @param _dr The bytes corresponding to the Protocol Buffers serialization of the data request output.
/// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request.
/// @return The unique identifier of the data request.
function postDataRequest(bytes calldata _dr, uint256 _tallyReward) external payable returns(uint256) {
uint256 n = controllers.length;
uint256 offset = controllers[n - 1].lastId;
// Update the currentLastId with the id in the controller plus the offSet
currentLastId = witnetRequestsBoardInstance.postDataRequest{value: msg.value}(_dr, _tallyReward) + offset;
return currentLastId;
}
/// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward.
/// @param _id The unique identifier of the data request.
/// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward.
function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable {
address wrbAddress;
uint256 wrbOffset;
(wrbAddress, wrbOffset) = getController(_id);
return witnetRequestsBoardInstance.upgradeDataRequest{value: msg.value}(_id - wrbOffset, _tallyReward);
}
/// @dev Retrieves the DR hash of the id from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The hash of the DR.
function readDrHash (uint256 _id)
external
view
returns(uint256)
{
// Get the address and the offset of the corresponding to id
address wrbAddress;
uint256 offsetWrb;
(wrbAddress, offsetWrb) = getController(_id);
// Return the result of the DR readed in the corresponding Controller with its own id
WitnetRequestsBoardInterface wrbWithDrHash;
wrbWithDrHash = WitnetRequestsBoardInterface(wrbAddress);
uint256 drHash = wrbWithDrHash.readDrHash(_id - offsetWrb);
return drHash;
}
/// @dev Retrieves the result (if already available) of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the DR.
function readResult(uint256 _id) external view returns(bytes memory) {
// Get the address and the offset of the corresponding to id
address wrbAddress;
uint256 offSetWrb;
(wrbAddress, offSetWrb) = getController(_id);
// Return the result of the DR in the corresponding Controller with its own id
WitnetRequestsBoardInterface wrbWithResult;
wrbWithResult = WitnetRequestsBoardInterface(wrbAddress);
return wrbWithResult.readResult(_id - offSetWrb);
}
/// @notice Upgrades the Witnet Requests Board if the current one is upgradeable.
/// @param _newAddress address of the new block relay to upgrade.
function upgradeWitnetRequestsBoard(address _newAddress) public notIdentical(_newAddress) {
// Require the WRB is upgradable
require(witnetRequestsBoardInstance.isUpgradable(msg.sender), "The upgrade has been rejected by the current implementation");
// Map the currentLastId to the corresponding witnetRequestsBoardAddress and add it to controllers
controllers.push(ControllerInfo({controllerAddress: _newAddress, lastId: currentLastId}));
// Upgrade the WRB
witnetRequestsBoardAddress = _newAddress;
witnetRequestsBoardInstance = WitnetRequestsBoardInterface(_newAddress);
}
/// @notice Gets the controller from an Id.
/// @param _id id of a Data Request from which we get the controller.
function getController(uint256 _id) internal view returns(address _controllerAddress, uint256 _offset) {
// Check id is bigger than 0
require(_id > 0, "Non-existent controller for id 0");
uint256 n = controllers.length;
// If the id is bigger than the lastId of a Controller, read the result in that Controller
for (uint i = n; i > 0; i--) {
if (_id > controllers[i - 1].lastId) {
return (controllers[i - 1].controllerAddress, controllers[i - 1].lastId);
}
}
}
}
// File: witnet-ethereum-bridge/contracts/BufferLib.sol
/**
* @title A convenient wrapper around the `bytes memory` type that exposes a buffer-like interface
* @notice The buffer has an inner cursor that tracks the final offset of every read, i.e. any subsequent read will
* start with the byte that goes right after the last one in the previous read.
* @dev `uint32` is used here for `cursor` because `uint16` would only enable seeking up to 8KB, which could in some
* theoretical use cases be exceeded. Conversely, `uint32` supports up to 512MB, which cannot credibly be exceeded.
*/
library BufferLib {
struct Buffer {
bytes data;
uint32 cursor;
}
// Ensures we access an existing index in an array
modifier notOutOfBounds(uint32 index, uint256 length) {
require(index < length, "Tried to read from a consumed Buffer (must rewind it first)");
_;
}
/**
* @notice Read and consume a certain amount of bytes from the buffer.
* @param _buffer An instance of `BufferLib.Buffer`.
* @param _length How many bytes to read and consume from the buffer.
* @return A `bytes memory` containing the first `_length` bytes from the buffer, counting from the cursor position.
*/
function read(Buffer memory _buffer, uint32 _length) internal pure returns (bytes memory) {
// Make sure not to read out of the bounds of the original bytes
require(_buffer.cursor + _length <= _buffer.data.length, "Not enough bytes in buffer when reading");
// Create a new `bytes memory destination` value
bytes memory destination = new bytes(_length);
bytes memory source = _buffer.data;
uint32 offset = _buffer.cursor;
// Get raw pointers for source and destination
uint sourcePointer;
uint destinationPointer;
assembly {
sourcePointer := add(add(source, 32), offset)
destinationPointer := add(destination, 32)
}
// Copy `_length` bytes from source to destination
memcpy(destinationPointer, sourcePointer, uint(_length));
// Move the cursor forward by `_length` bytes
seek(_buffer, _length, true);
return destination;
}
/**
* @notice Read and consume the next byte from the buffer.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The next byte in the buffer counting from the cursor position.
*/
function next(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (byte) {
// Return the byte at the position marked by the cursor and advance the cursor all at once
return _buffer.data[_buffer.cursor++];
}
/**
* @notice Move the inner cursor of the buffer to a relative or absolute position.
* @param _buffer An instance of `BufferLib.Buffer`.
* @param _offset How many bytes to move the cursor forward.
* @param _relative Whether to count `_offset` from the last position of the cursor (`true`) or the beginning of the
* buffer (`true`).
* @return The final position of the cursor (will equal `_offset` if `_relative` is `false`).
*/
// solium-disable-next-line security/no-assign-params
function seek(Buffer memory _buffer, uint32 _offset, bool _relative) internal pure returns (uint32) {
// Deal with relative offsets
if (_relative) {
require(_offset + _buffer.cursor > _offset, "Integer overflow when seeking");
_offset += _buffer.cursor;
}
// Make sure not to read out of the bounds of the original bytes
require(_offset <= _buffer.data.length, "Not enough bytes in buffer when seeking");
_buffer.cursor = _offset;
return _buffer.cursor;
}
/**
* @notice Move the inner cursor a number of bytes forward.
* @dev This is a simple wrapper around the relative offset case of `seek()`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @param _relativeOffset How many bytes to move the cursor forward.
* @return The final position of the cursor.
*/
function seek(Buffer memory _buffer, uint32 _relativeOffset) internal pure returns (uint32) {
return seek(_buffer, _relativeOffset, true);
}
/**
* @notice Move the inner cursor back to the first byte in the buffer.
* @param _buffer An instance of `BufferLib.Buffer`.
*/
function rewind(Buffer memory _buffer) internal pure {
_buffer.cursor = 0;
}
/**
* @notice Read and consume the next byte from the buffer as an `uint8`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint8` value of the next byte in the buffer counting from the cursor position.
*/
function readUint8(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (uint8) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint8 value;
assembly {
value := mload(add(add(bytesValue, 1), offset))
}
_buffer.cursor++;
return value;
}
/**
* @notice Read and consume the next 2 bytes from the buffer as an `uint16`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint16` value of the next 2 bytes in the buffer counting from the cursor position.
*/
function readUint16(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 1, _buffer.data.length) returns (uint16) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint16 value;
assembly {
value := mload(add(add(bytesValue, 2), offset))
}
_buffer.cursor += 2;
return value;
}
/**
* @notice Read and consume the next 4 bytes from the buffer as an `uint32`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position.
*/
function readUint32(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 3, _buffer.data.length) returns (uint32) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint32 value;
assembly {
value := mload(add(add(bytesValue, 4), offset))
}
_buffer.cursor += 4;
return value;
}
/**
* @notice Read and consume the next 8 bytes from the buffer as an `uint64`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint64` value of the next 8 bytes in the buffer counting from the cursor position.
*/
function readUint64(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 7, _buffer.data.length) returns (uint64) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint64 value;
assembly {
value := mload(add(add(bytesValue, 8), offset))
}
_buffer.cursor += 8;
return value;
}
/**
* @notice Read and consume the next 16 bytes from the buffer as an `uint128`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint128` value of the next 16 bytes in the buffer counting from the cursor position.
*/
function readUint128(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint128 value;
assembly {
value := mload(add(add(bytesValue, 16), offset))
}
_buffer.cursor += 16;
return value;
}
/**
* @notice Read and consume the next 32 bytes from the buffer as an `uint256`.
* @return The `uint256` value of the next 32 bytes in the buffer counting from the cursor position.
* @param _buffer An instance of `BufferLib.Buffer`.
*/
function readUint256(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 31, _buffer.data.length) returns (uint256) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint256 value;
assembly {
value := mload(add(add(bytesValue, 32), offset))
}
_buffer.cursor += 32;
return value;
}
/**
* @notice Read and consume the next 2 bytes from the buffer as an IEEE 754-2008 floating point number enclosed in an
* `int32`.
* @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values
* by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `float16`
* use cases. In other words, the integer output of this method is 10,000 times the actual value. The input bytes are
* expected to follow the 16-bit base-2 format (a.k.a. `binary16`) in the IEEE 754-2008 standard.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position.
*/
function readFloat16(Buffer memory _buffer) internal pure returns (int32) {
uint32 bytesValue = readUint16(_buffer);
// Get bit at position 0
uint32 sign = bytesValue & 0x8000;
// Get bits 1 to 5, then normalize to the [-14, 15] range so as to counterweight the IEEE 754 exponent bias
int32 exponent = (int32(bytesValue & 0x7c00) >> 10) - 15;
// Get bits 6 to 15
int32 significand = int32(bytesValue & 0x03ff);
// Add 1024 to the fraction if the exponent is 0
if (exponent == 15) {
significand |= 0x400;
}
// Compute `2 ^ exponent · (1 + fraction / 1024)`
int32 result = 0;
if (exponent >= 0) {
result = int32(((1 << uint256(exponent)) * 10000 * (uint256(significand) | 0x400)) >> 10);
} else {
result = int32((((uint256(significand) | 0x400) * 10000) / (1 << uint256(- exponent))) >> 10);
}
// Make the result negative if the sign bit is not 0
if (sign != 0) {
result *= - 1;
}
return result;
}
/**
* @notice Copy bytes from one memory address into another.
* @dev This function was borrowed from Nick Johnson's `solidity-stringutils` lib, and reproduced here under the terms
* of [Apache License 2.0](https://github.com/Arachnid/solidity-stringutils/blob/master/LICENSE).
* @param _dest Address of the destination memory.
* @param _src Address to the source memory.
* @param _len How many bytes to copy.
*/
// solium-disable-next-line security/no-assign-params
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))
}
}
}
// File: witnet-ethereum-bridge/contracts/CBOR.sol
/**
* @title A minimalistic implementation of “RFC 7049 Concise Binary Object Representation”
* @notice This library leverages a buffer-like structure for step-by-step decoding of bytes so as to minimize
* the gas cost of decoding them into a useful native type.
* @dev Most of the logic has been borrowed from Patrick Gansterer’s cbor.js library: https://github.com/paroga/cbor-js
* TODO: add support for Array (majorType = 4)
* TODO: add support for Map (majorType = 5)
* TODO: add support for Float32 (majorType = 7, additionalInformation = 26)
* TODO: add support for Float64 (majorType = 7, additionalInformation = 27)
*/
library CBOR {
using BufferLib for BufferLib.Buffer;
uint64 constant internal UINT64_MAX = ~uint64(0);
struct Value {
BufferLib.Buffer buffer;
uint8 initialByte;
uint8 majorType;
uint8 additionalInformation;
uint64 len;
uint64 tag;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `bytes` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as a `bytes` value.
*/
function decodeBytes(Value memory _cborValue) public pure returns(bytes memory) {
_cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation);
if (_cborValue.len == UINT64_MAX) {
bytes memory bytesData;
// These checks look repetitive but the equivalent loop would be more expensive.
uint32 itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType));
if (itemLength < UINT64_MAX) {
bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength));
itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType));
if (itemLength < UINT64_MAX) {
bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength));
}
}
return bytesData;
} else {
return _cborValue.buffer.read(uint32(_cborValue.len));
}
}
/**
* @notice Decode a `CBOR.Value` structure into a `fixed16` value.
* @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values
* by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`
* use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128` value.
*/
function decodeFixed16(Value memory _cborValue) public pure returns(int32) {
require(_cborValue.majorType == 7, "Tried to read a `fixed` value from a `CBOR.Value` with majorType != 7");
require(_cborValue.additionalInformation == 25, "Tried to read `fixed16` from a `CBOR.Value` with additionalInformation != 25");
return _cborValue.buffer.readFloat16();
}
/**
* @notice Decode a `CBOR.Value` structure into a native `int128[]` value whose inner values follow the same convention.
* as explained in `decodeFixed16`.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128[]` value.
*/
function decodeFixed16Array(Value memory _cborValue) public pure returns(int128[] memory) {
require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
int128[] memory array = new int128[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeFixed16(item);
}
return array;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `int128` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128` value.
*/
function decodeInt128(Value memory _cborValue) public pure returns(int128) {
if (_cborValue.majorType == 1) {
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
return int128(-1) - int128(length);
} else if (_cborValue.majorType == 0) {
// Any `uint64` can be safely casted to `int128`, so this method supports majorType 1 as well so as to have offer
// a uniform API for positive and negative numbers
return int128(decodeUint64(_cborValue));
}
revert("Tried to read `int128` from a `CBOR.Value` with majorType not 0 or 1");
}
/**
* @notice Decode a `CBOR.Value` structure into a native `int128[]` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128[]` value.
*/
function decodeInt128Array(Value memory _cborValue) public pure returns(int128[] memory) {
require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
int128[] memory array = new int128[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeInt128(item);
}
return array;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `string` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as a `string` value.
*/
function decodeString(Value memory _cborValue) public pure returns(string memory) {
_cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation);
if (_cborValue.len == UINT64_MAX) {
bytes memory textData;
bool done;
while (!done) {
uint64 itemLength = readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType);
if (itemLength < UINT64_MAX) {
textData = abi.encodePacked(textData, readText(_cborValue.buffer, itemLength / 4));
} else {
done = true;
}
}
return string(textData);
} else {
return string(readText(_cborValue.buffer, _cborValue.len));
}
}
/**
* @notice Decode a `CBOR.Value` structure into a native `string[]` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `string[]` value.
*/
function decodeStringArray(Value memory _cborValue) public pure returns(string[] memory) {
require(_cborValue.majorType == 4, "Tried to read `string[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
string[] memory array = new string[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeString(item);
}
return array;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `uint64` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `uint64` value.
*/
function decodeUint64(Value memory _cborValue) public pure returns(uint64) {
require(_cborValue.majorType == 0, "Tried to read `uint64` from a `CBOR.Value` with majorType != 0");
return readLength(_cborValue.buffer, _cborValue.additionalInformation);
}
/**
* @notice Decode a `CBOR.Value` structure into a native `uint64[]` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `uint64[]` value.
*/
function decodeUint64Array(Value memory _cborValue) public pure returns(uint64[] memory) {
require(_cborValue.majorType == 4, "Tried to read `uint64[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
uint64[] memory array = new uint64[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeUint64(item);
}
return array;
}
/**
* @notice Decode a CBOR.Value structure from raw bytes.
* @dev This is the main factory for CBOR.Value instances, which can be later decoded into native EVM types.
* @param _cborBytes Raw bytes representing a CBOR-encoded value.
* @return A `CBOR.Value` instance containing a partially decoded value.
*/
function valueFromBytes(bytes memory _cborBytes) public pure returns(Value memory) {
BufferLib.Buffer memory buffer = BufferLib.Buffer(_cborBytes, 0);
return valueFromBuffer(buffer);
}
/**
* @notice Decode a CBOR.Value structure from raw bytes.
* @dev This is an alternate factory for CBOR.Value instances, which can be later decoded into native EVM types.
* @param _buffer A Buffer structure representing a CBOR-encoded value.
* @return A `CBOR.Value` instance containing a partially decoded value.
*/
function valueFromBuffer(BufferLib.Buffer memory _buffer) public pure returns(Value memory) {
require(_buffer.data.length > 0, "Found empty buffer when parsing CBOR value");
uint8 initialByte;
uint8 majorType = 255;
uint8 additionalInformation;
uint64 length;
uint64 tag = UINT64_MAX;
bool isTagged = true;
while (isTagged) {
// Extract basic CBOR properties from input bytes
initialByte = _buffer.readUint8();
majorType = initialByte >> 5;
additionalInformation = initialByte & 0x1f;
// Early CBOR tag parsing.
if (majorType == 6) {
tag = readLength(_buffer, additionalInformation);
} else {
isTagged = false;
}
}
require(majorType <= 7, "Invalid CBOR major type");
return CBOR.Value(
_buffer,
initialByte,
majorType,
additionalInformation,
length,
tag);
}
// Reads the length of the next CBOR item from a buffer, consuming a different number of bytes depending on the
// value of the `additionalInformation` argument.
function readLength(BufferLib.Buffer memory _buffer, uint8 additionalInformation) private pure returns(uint64) {
if (additionalInformation < 24) {
return additionalInformation;
}
if (additionalInformation == 24) {
return _buffer.readUint8();
}
if (additionalInformation == 25) {
return _buffer.readUint16();
}
if (additionalInformation == 26) {
return _buffer.readUint32();
}
if (additionalInformation == 27) {
return _buffer.readUint64();
}
if (additionalInformation == 31) {
return UINT64_MAX;
}
revert("Invalid length encoding (non-existent additionalInformation value)");
}
// Read the length of a CBOR indifinite-length item (arrays, maps, byte strings and text) from a buffer, consuming
// as many bytes as specified by the first byte.
function readIndefiniteStringLength(BufferLib.Buffer memory _buffer, uint8 majorType) private pure returns(uint64) {
uint8 initialByte = _buffer.readUint8();
if (initialByte == 0xff) {
return UINT64_MAX;
}
uint64 length = readLength(_buffer, initialByte & 0x1f);
require(length < UINT64_MAX && (initialByte >> 5) == majorType, "Invalid indefinite length");
return length;
}
// Read a text string of a given length from a buffer. Returns a `bytes memory` value for the sake of genericness,
// but it can be easily casted into a string with `string(result)`.
// solium-disable-next-line security/no-assign-params
function readText(BufferLib.Buffer memory _buffer, uint64 _length) private pure returns(bytes memory) {
bytes memory result;
for (uint64 index = 0; index < _length; index++) {
uint8 value = _buffer.readUint8();
if (value & 0x80 != 0) {
if (value < 0xe0) {
value = (value & 0x1f) << 6 |
(_buffer.readUint8() & 0x3f);
_length -= 1;
} else if (value < 0xf0) {
value = (value & 0x0f) << 12 |
(_buffer.readUint8() & 0x3f) << 6 |
(_buffer.readUint8() & 0x3f);
_length -= 2;
} else {
value = (value & 0x0f) << 18 |
(_buffer.readUint8() & 0x3f) << 12 |
(_buffer.readUint8() & 0x3f) << 6 |
(_buffer.readUint8() & 0x3f);
_length -= 3;
}
}
result = abi.encodePacked(result, value);
}
return result;
}
}
// File: witnet-ethereum-bridge/contracts/Witnet.sol
/**
* @title A library for decoding Witnet request results
* @notice The library exposes functions to check the Witnet request success.
* and retrieve Witnet results from CBOR values into solidity types.
*/
library Witnet {
using CBOR for CBOR.Value;
/*
STRUCTS
*/
struct Result {
bool success;
CBOR.Value cborValue;
}
/*
ENUMS
*/
enum ErrorCodes {
// 0x00: Unknown error. Something went really bad!
Unknown,
// Script format errors
/// 0x01: At least one of the source scripts is not a valid CBOR-encoded value.
SourceScriptNotCBOR,
/// 0x02: The CBOR value decoded from a source script is not an Array.
SourceScriptNotArray,
/// 0x03: The Array value decoded form a source script is not a valid RADON script.
SourceScriptNotRADON,
/// Unallocated
ScriptFormat0x04,
ScriptFormat0x05,
ScriptFormat0x06,
ScriptFormat0x07,
ScriptFormat0x08,
ScriptFormat0x09,
ScriptFormat0x0A,
ScriptFormat0x0B,
ScriptFormat0x0C,
ScriptFormat0x0D,
ScriptFormat0x0E,
ScriptFormat0x0F,
// Complexity errors
/// 0x10: The request contains too many sources.
RequestTooManySources,
/// 0x11: The script contains too many calls.
ScriptTooManyCalls,
/// Unallocated
Complexity0x12,
Complexity0x13,
Complexity0x14,
Complexity0x15,
Complexity0x16,
Complexity0x17,
Complexity0x18,
Complexity0x19,
Complexity0x1A,
Complexity0x1B,
Complexity0x1C,
Complexity0x1D,
Complexity0x1E,
Complexity0x1F,
// Operator errors
/// 0x20: The operator does not exist.
UnsupportedOperator,
/// Unallocated
Operator0x21,
Operator0x22,
Operator0x23,
Operator0x24,
Operator0x25,
Operator0x26,
Operator0x27,
Operator0x28,
Operator0x29,
Operator0x2A,
Operator0x2B,
Operator0x2C,
Operator0x2D,
Operator0x2E,
Operator0x2F,
// Retrieval-specific errors
/// 0x30: At least one of the sources could not be retrieved, but returned HTTP error.
HTTP,
/// 0x31: Retrieval of at least one of the sources timed out.
RetrievalTimeout,
/// Unallocated
Retrieval0x32,
Retrieval0x33,
Retrieval0x34,
Retrieval0x35,
Retrieval0x36,
Retrieval0x37,
Retrieval0x38,
Retrieval0x39,
Retrieval0x3A,
Retrieval0x3B,
Retrieval0x3C,
Retrieval0x3D,
Retrieval0x3E,
Retrieval0x3F,
// Math errors
/// 0x40: Math operator caused an underflow.
Underflow,
/// 0x41: Math operator caused an overflow.
Overflow,
/// 0x42: Tried to divide by zero.
DivisionByZero,
Size
}
/*
Result impl's
*/
/**
* @notice Decode raw CBOR bytes into a Result instance.
* @param _cborBytes Raw bytes representing a CBOR-encoded value.
* @return A `Result` instance.
*/
function resultFromCborBytes(bytes calldata _cborBytes) external pure returns(Result memory) {
CBOR.Value memory cborValue = CBOR.valueFromBytes(_cborBytes);
return resultFromCborValue(cborValue);
}
/**
* @notice Decode a CBOR value into a Result instance.
* @param _cborValue An instance of `CBOR.Value`.
* @return A `Result` instance.
*/
function resultFromCborValue(CBOR.Value memory _cborValue) public pure returns(Result memory) {
// Witnet uses CBOR tag 39 to represent RADON error code identifiers.
// [CBOR tag 39] Identifiers for CBOR: https://github.com/lucas-clemente/cbor-specs/blob/master/id.md
bool success = _cborValue.tag != 39;
return Result(success, _cborValue);
}
/**
* @notice Tell if a Result is successful.
* @param _result An instance of Result.
* @return `true` if successful, `false` if errored.
*/
function isOk(Result memory _result) public pure returns(bool) {
return _result.success;
}
/**
* @notice Tell if a Result is errored.
* @param _result An instance of Result.
* @return `true` if errored, `false` if successful.
*/
function isError(Result memory _result) public pure returns(bool) {
return !_result.success;
}
/**
* @notice Decode a bytes value from a Result as a `bytes` value.
* @param _result An instance of Result.
* @return The `bytes` decoded from the Result.
*/
function asBytes(Result memory _result) public pure returns(bytes memory) {
require(_result.success, "Tried to read bytes value from errored Result");
return _result.cborValue.decodeBytes();
}
/**
* @notice Decode an error code from a Result as a member of `ErrorCodes`.
* @param _result An instance of `Result`.
* @return The `CBORValue.Error memory` decoded from the Result.
*/
function asErrorCode(Result memory _result) public pure returns(ErrorCodes) {
uint64[] memory error = asRawError(_result);
return supportedErrorOrElseUnknown(error[0]);
}
/**
* @notice Generate a suitable error message for a member of `ErrorCodes` and its corresponding arguments.
* @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function
* @param _result An instance of `Result`.
* @return A tuple containing the `CBORValue.Error memory` decoded from the `Result`, plus a loggable error message.
*/
function asErrorMessage(Result memory _result) public pure returns(ErrorCodes, string memory) {
uint64[] memory error = asRawError(_result);
ErrorCodes errorCode = supportedErrorOrElseUnknown(error[0]);
bytes memory errorMessage;
if (errorCode == ErrorCodes.SourceScriptNotCBOR) {
errorMessage = abi.encodePacked("Source script #", utoa(error[1]), " was not a valid CBOR value");
} else if (errorCode == ErrorCodes.SourceScriptNotArray) {
errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not an Array of calls");
} else if (errorCode == ErrorCodes.SourceScriptNotRADON) {
errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not a valid RADON script");
} else if (errorCode == ErrorCodes.RequestTooManySources) {
errorMessage = abi.encodePacked("The request contained too many sources (", utoa(error[1]), ")");
} else if (errorCode == ErrorCodes.ScriptTooManyCalls) {
errorMessage = abi.encodePacked(
"Script #",
utoa(error[2]),
" from the ",
stageName(error[1]),
" stage contained too many calls (",
utoa(error[3]),
")"
);
} else if (errorCode == ErrorCodes.UnsupportedOperator) {
errorMessage = abi.encodePacked(
"Operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage is not supported"
);
} else if (errorCode == ErrorCodes.HTTP) {
errorMessage = abi.encodePacked(
"Source #",
utoa(error[1]),
" could not be retrieved. Failed with HTTP error code: ",
utoa(error[2] / 100),
utoa(error[2] % 100 / 10),
utoa(error[2] % 10)
);
} else if (errorCode == ErrorCodes.RetrievalTimeout) {
errorMessage = abi.encodePacked(
"Source #",
utoa(error[1]),
" could not be retrieved because of a timeout."
);
} else if (errorCode == ErrorCodes.Underflow) {
errorMessage = abi.encodePacked(
"Underflow at operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage"
);
} else if (errorCode == ErrorCodes.Overflow) {
errorMessage = abi.encodePacked(
"Overflow at operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage"
);
} else if (errorCode == ErrorCodes.DivisionByZero) {
errorMessage = abi.encodePacked(
"Division by zero at operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage"
);
} else {
errorMessage = abi.encodePacked("Unknown error (0x", utohex(error[0]), ")");
}
return (errorCode, string(errorMessage));
}
/**
* @notice Decode a raw error from a `Result` as a `uint64[]`.
* @param _result An instance of `Result`.
* @return The `uint64[]` raw error as decoded from the `Result`.
*/
function asRawError(Result memory _result) public pure returns(uint64[] memory) {
require(!_result.success, "Tried to read error code from successful Result");
return _result.cborValue.decodeUint64Array();
}
/**
* @notice Decode a fixed16 (half-precision) numeric value from a Result as an `int32` value.
* @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values.
* by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`.
* use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`.
* @param _result An instance of Result.
* @return The `int128` decoded from the Result.
*/
function asFixed16(Result memory _result) public pure returns(int32) {
require(_result.success, "Tried to read `fixed16` value from errored Result");
return _result.cborValue.decodeFixed16();
}
/**
* @notice Decode an array of fixed16 values from a Result as an `int128[]` value.
* @param _result An instance of Result.
* @return The `int128[]` decoded from the Result.
*/
function asFixed16Array(Result memory _result) public pure returns(int128[] memory) {
require(_result.success, "Tried to read `fixed16[]` value from errored Result");
return _result.cborValue.decodeFixed16Array();
}
/**
* @notice Decode a integer numeric value from a Result as an `int128` value.
* @param _result An instance of Result.
* @return The `int128` decoded from the Result.
*/
function asInt128(Result memory _result) public pure returns(int128) {
require(_result.success, "Tried to read `int128` value from errored Result");
return _result.cborValue.decodeInt128();
}
/**
* @notice Decode an array of integer numeric values from a Result as an `int128[]` value.
* @param _result An instance of Result.
* @return The `int128[]` decoded from the Result.
*/
function asInt128Array(Result memory _result) public pure returns(int128[] memory) {
require(_result.success, "Tried to read `int128[]` value from errored Result");
return _result.cborValue.decodeInt128Array();
}
/**
* @notice Decode a string value from a Result as a `string` value.
* @param _result An instance of Result.
* @return The `string` decoded from the Result.
*/
function asString(Result memory _result) public pure returns(string memory) {
require(_result.success, "Tried to read `string` value from errored Result");
return _result.cborValue.decodeString();
}
/**
* @notice Decode an array of string values from a Result as a `string[]` value.
* @param _result An instance of Result.
* @return The `string[]` decoded from the Result.
*/
function asStringArray(Result memory _result) public pure returns(string[] memory) {
require(_result.success, "Tried to read `string[]` value from errored Result");
return _result.cborValue.decodeStringArray();
}
/**
* @notice Decode a natural numeric value from a Result as a `uint64` value.
* @param _result An instance of Result.
* @return The `uint64` decoded from the Result.
*/
function asUint64(Result memory _result) public pure returns(uint64) {
require(_result.success, "Tried to read `uint64` value from errored Result");
return _result.cborValue.decodeUint64();
}
/**
* @notice Decode an array of natural numeric values from a Result as a `uint64[]` value.
* @param _result An instance of Result.
* @return The `uint64[]` decoded from the Result.
*/
function asUint64Array(Result memory _result) public pure returns(uint64[] memory) {
require(_result.success, "Tried to read `uint64[]` value from errored Result");
return _result.cborValue.decodeUint64Array();
}
/**
* @notice Convert a stage index number into the name of the matching Witnet request stage.
* @param _stageIndex A `uint64` identifying the index of one of the Witnet request stages.
* @return The name of the matching stage.
*/
function stageName(uint64 _stageIndex) public pure returns(string memory) {
if (_stageIndex == 0) {
return "retrieval";
} else if (_stageIndex == 1) {
return "aggregation";
} else if (_stageIndex == 2) {
return "tally";
} else {
return "unknown";
}
}
/**
* @notice Get an `ErrorCodes` item from its `uint64` discriminant, or default to `ErrorCodes.Unknown` if it doesn't
* exist.
* @param _discriminant The numeric identifier of an error.
* @return A member of `ErrorCodes`.
*/
function supportedErrorOrElseUnknown(uint64 _discriminant) private pure returns(ErrorCodes) {
if (_discriminant < uint8(ErrorCodes.Size)) {
return ErrorCodes(_discriminant);
} else {
return ErrorCodes.Unknown;
}
}
/**
* @notice Convert a `uint64` into a 1, 2 or 3 characters long `string` representing its.
* three less significant decimal values.
* @param _u A `uint64` value.
* @return The `string` representing its decimal value.
*/
function utoa(uint64 _u) private pure returns(string memory) {
if (_u < 10) {
bytes memory b1 = new bytes(1);
b1[0] = byte(uint8(_u) + 48);
return string(b1);
} else if (_u < 100) {
bytes memory b2 = new bytes(2);
b2[0] = byte(uint8(_u / 10) + 48);
b2[1] = byte(uint8(_u % 10) + 48);
return string(b2);
} else {
bytes memory b3 = new bytes(3);
b3[0] = byte(uint8(_u / 100) + 48);
b3[1] = byte(uint8(_u % 100 / 10) + 48);
b3[2] = byte(uint8(_u % 10) + 48);
return string(b3);
}
}
/**
* @notice Convert a `uint64` into a 2 characters long `string` representing its two less significant hexadecimal values.
* @param _u A `uint64` value.
* @return The `string` representing its hexadecimal value.
*/
function utohex(uint64 _u) private pure returns(string memory) {
bytes memory b2 = new bytes(2);
uint8 d0 = uint8(_u / 16) + 48;
uint8 d1 = uint8(_u % 16) + 48;
if (d0 > 57)
d0 += 7;
if (d1 > 57)
d1 += 7;
b2[0] = byte(d0);
b2[1] = byte(d1);
return string(b2);
}
}
// File: witnet-ethereum-bridge/contracts/Request.sol
/**
* @title The serialized form of a Witnet data request
*/
contract Request {
bytes public bytecode;
uint256 public id;
/**
* @dev A `Request` is constructed around a `bytes memory` value containing a well-formed Witnet data request serialized
* using Protocol Buffers. However, we cannot verify its validity at this point. This implies that contracts using
* the WRB should not be considered trustless before a valid Proof-of-Inclusion has been posted for the requests.
* The hash of the request is computed in the constructor to guarantee consistency. Otherwise there could be a
* mismatch and a data request could be resolved with the result of another.
* @param _bytecode Witnet request in bytes.
*/
constructor(bytes memory _bytecode) public {
bytecode = _bytecode;
id = uint256(sha256(_bytecode));
}
}
// File: witnet-ethereum-bridge/contracts/UsingWitnet.sol
/**
* @title The UsingWitnet contract
* @notice Contract writers can inherit this contract in order to create requests for the
* Witnet network.
*/
contract UsingWitnet {
using Witnet for Witnet.Result;
WitnetRequestsBoardProxy internal wrb;
/**
* @notice Include an address to specify the WitnetRequestsBoard.
* @param _wrb WitnetRequestsBoard address.
*/
constructor(address _wrb) public {
wrb = WitnetRequestsBoardProxy(_wrb);
}
// Provides a convenient way for client contracts extending this to block the execution of the main logic of the
// contract until a particular request has been successfully accepted into Witnet
modifier witnetRequestAccepted(uint256 _id) {
require(witnetCheckRequestAccepted(_id), "Witnet request is not yet accepted into the Witnet network");
_;
}
// Ensures that user-specified rewards are equal to the total transaction value to prevent users from burning any excess value
modifier validRewards(uint256 _requestReward, uint256 _resultReward) {
require(_requestReward + _resultReward >= _requestReward, "The sum of rewards overflows");
require(msg.value == _requestReward + _resultReward, "Transaction value should equal the sum of rewards");
_;
}
/**
* @notice Send a new request to the Witnet network
* @dev Call to `post_dr` function in the WitnetRequestsBoard contract
* @param _request An instance of the `Request` contract
* @param _requestReward Reward specified for the user which posts the request into Witnet
* @param _resultReward Reward specified for the user which posts back the request result
* @return Sequencial identifier for the request included in the WitnetRequestsBoard
*/
function witnetPostRequest(Request _request, uint256 _requestReward, uint256 _resultReward)
internal
validRewards(_requestReward, _resultReward)
returns (uint256)
{
return wrb.postDataRequest.value(_requestReward + _resultReward)(_request.bytecode(), _resultReward);
}
/**
* @notice Check if a request has been accepted into Witnet.
* @dev Contracts depending on Witnet should not start their main business logic (e.g. receiving value from third.
* parties) before this method returns `true`.
* @param _id The sequential identifier of a request that has been previously sent to the WitnetRequestsBoard.
* @return A boolean telling if the request has been already accepted or not. `false` do not mean rejection, though.
*/
function witnetCheckRequestAccepted(uint256 _id) internal view returns (bool) {
// Find the request in the
uint256 drHash = wrb.readDrHash(_id);
// If the hash of the data request transaction in Witnet is not the default, then it means that inclusion of the
// request has been proven to the WRB.
return drHash != 0;
}
/**
* @notice Upgrade the rewards for a Data Request previously included.
* @dev Call to `upgrade_dr` function in the WitnetRequestsBoard contract.
* @param _id The sequential identifier of a request that has been previously sent to the WitnetRequestsBoard.
* @param _requestReward Reward specified for the user which posts the request into Witnet
* @param _resultReward Reward specified for the user which post the Data Request result.
*/
function witnetUpgradeRequest(uint256 _id, uint256 _requestReward, uint256 _resultReward)
internal
validRewards(_requestReward, _resultReward)
{
wrb.upgradeDataRequest.value(msg.value)(_id, _resultReward);
}
/**
* @notice Read the result of a resolved request.
* @dev Call to `read_result` function in the WitnetRequestsBoard contract.
* @param _id The sequential identifier of a request that was posted to Witnet.
* @return The result of the request as an instance of `Result`.
*/
function witnetReadResult(uint256 _id) internal view returns (Witnet.Result memory) {
return Witnet.resultFromCborBytes(wrb.readResult(_id));
}
}
// File: adomedianizer/contracts/IERC2362.sol
/**
* @dev EIP2362 Interface for pull oracles
* https://github.com/tellor-io/EIP-2362
*/
interface IERC2362
{
/**
* @dev Exposed function pertaining to EIP standards
* @param _id bytes32 ID of the query
* @return int,uint,uint returns the value, timestamp, and status code of query
*/
function valueFor(bytes32 _id) external view returns(int256,uint256,uint256);
}
// File: witnet-price-feeds-examples/contracts/requests/BitcoinPrice.sol
// The bytecode of the BitcoinPrice request that will be sent to Witnet
contract BitcoinPriceRequest is Request {
constructor () Request(hex"0abb0108c3aafbf405123b122468747470733a2f2f7777772e6269747374616d702e6e65742f6170692f7469636b65722f1a13841877821864646c6173748218571903e8185b125c123168747470733a2f2f6170692e636f696e6465736b2e636f6d2f76312f6270692f63757272656e7470726963652e6a736f6e1a2786187782186663627069821866635553448218646a726174655f666c6f61748218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { }
}
// File: witnet-price-feeds-examples/contracts/bitcoin_price_feed/BtcUsdPriceFeed.sol
// Import the UsingWitnet library that enables interacting with Witnet
// Import the ERC2362 interface
// Import the BitcoinPrice request that you created before
// Your contract needs to inherit from UsingWitnet
contract BtcUsdPriceFeed is UsingWitnet, IERC2362 {
// The public Bitcoin price point
uint64 public lastPrice;
// Stores the ID of the last Witnet request
uint256 public lastRequestId;
// Stores the timestamp of the last time the public price point was updated
uint256 public timestamp;
// Tells if an update has been requested but not yet completed
bool public pending;
// The Witnet request object, is set in the constructor
Request public request;
// Emits when the price is updated
event priceUpdated(uint64);
// Emits when found an error decoding request result
event resultError(string);
// This is `keccak256("Price-BTC/USD-3")`
bytes32 constant public BTCUSD3ID = bytes32(hex"637b7efb6b620736c247aaa282f3898914c0bef6c12faff0d3fe9d4bea783020");
// This constructor does a nifty trick to tell the `UsingWitnet` library where
// to find the Witnet contracts on whatever Ethereum network you use.
constructor (address _wrb) UsingWitnet(_wrb) public {
// Instantiate the Witnet request
request = new BitcoinPriceRequest();
}
/**
* @notice Sends `request` to the WitnetRequestsBoard.
* @dev This method will only succeed if `pending` is 0.
**/
function requestUpdate() public payable {
require(!pending, "An update is already pending. Complete it first before requesting another update.");
// Amount to pay to the bridge node relaying this request from Ethereum to Witnet
uint256 _witnetRequestReward = 100 szabo;
// Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum
uint256 _witnetResultReward = 100 szabo;
// Send the request to Witnet and store the ID for later retrieval of the result
// The `witnetPostRequest` method comes with `UsingWitnet`
lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward);
// Signal that there is already a pending request
pending = true;
}
/**
* @notice Reads the result, if ready, from the WitnetRequestsBoard.
* @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to
* protect your methods from being called before the request has been successfully
* relayed into Witnet.
**/
function completeUpdate() public witnetRequestAccepted(lastRequestId) {
require(pending, "There is no pending update.");
// Read the result of the Witnet request
// The `witnetReadResult` method comes with `UsingWitnet`
Witnet.Result memory result = witnetReadResult(lastRequestId);
// If the Witnet request succeeded, decode the result and update the price point
// If it failed, revert the transaction with a pretty-printed error message
if (result.isOk()) {
lastPrice = result.asUint64();
timestamp = block.timestamp;
emit priceUpdated(lastPrice);
} else {
string memory errorMessage;
// Try to read the value as an error message, catch error bytes if read fails
try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) {
errorMessage = e;
}
catch (bytes memory errorBytes){
errorMessage = string(errorBytes);
}
emit resultError(errorMessage);
}
// In any case, set `pending` to false so a new update can be requested
pending = false;
}
/**
* @notice Exposes the public data point in an ERC2362 compliant way.
* @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called
* successfully before.
**/
function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) {
// Unsupported data point ID
if(_id != BTCUSD3ID) return(0, 0, 400);
// No value is yet available for the queried data point ID
if (timestamp == 0) return(0, 0, 404);
int256 value = int256(lastPrice);
return(value, timestamp, 200);
}
}
// File: witnet-price-feeds-examples/contracts/requests/EthPrice.sol
// The bytecode of the EthPrice request that will be sent to Witnet
contract EthPriceRequest is Request {
constructor () Request(hex"0a850208d7affbf4051245122e68747470733a2f2f7777772e6269747374616d702e6e65742f6170692f76322f7469636b65722f6574687573642f1a13841877821864646c6173748218571903e8185b1247122068747470733a2f2f6170692e636f696e6361702e696f2f76322f6173736574731a238618778218616464617461821818018218646870726963655573648218571903e8185b1253122668747470733a2f2f6170692e636f696e70617072696b612e636f6d2f76312f7469636b6572731a29871876821818038218666671756f746573821866635553448218646570726963658218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { }
}
// File: witnet-price-feeds-examples/contracts/eth_price_feed/EthUsdPriceFeed.sol
// Import the UsingWitnet library that enables interacting with Witnet
// Import the ERC2362 interface
// Import the ethPrice request that you created before
// Your contract needs to inherit from UsingWitnet
contract EthUsdPriceFeed is UsingWitnet, IERC2362 {
// The public eth price point
uint64 public lastPrice;
// Stores the ID of the last Witnet request
uint256 public lastRequestId;
// Stores the timestamp of the last time the public price point was updated
uint256 public timestamp;
// Tells if an update has been requested but not yet completed
bool public pending;
// The Witnet request object, is set in the constructor
Request public request;
// Emits when the price is updated
event priceUpdated(uint64);
// Emits when found an error decoding request result
event resultError(string);
// This is the ERC2362 identifier for a eth price feed, computed as `keccak256("Price-ETH/USD-3")`
bytes32 constant public ETHUSD3ID = bytes32(hex"dfaa6f747f0f012e8f2069d6ecacff25f5cdf0258702051747439949737fc0b5");
// This constructor does a nifty trick to tell the `UsingWitnet` library where
// to find the Witnet contracts on whatever Ethereum network you use.
constructor (address _wrb) UsingWitnet(_wrb) public {
// Instantiate the Witnet request
request = new EthPriceRequest();
}
/**
* @notice Sends `request` to the WitnetRequestsBoard.
* @dev This method will only succeed if `pending` is 0.
**/
function requestUpdate() public payable {
require(!pending, "An update is already pending. Complete it first before requesting another update.");
// Amount to pay to the bridge node relaying this request from Ethereum to Witnet
uint256 _witnetRequestReward = 100 szabo;
// Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum
uint256 _witnetResultReward = 100 szabo;
// Send the request to Witnet and store the ID for later retrieval of the result
// The `witnetPostRequest` method comes with `UsingWitnet`
lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward);
// Signal that there is already a pending request
pending = true;
}
/**
* @notice Reads the result, if ready, from the WitnetRequestsBoard.
* @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to
* protect your methods from being called before the request has been successfully
* relayed into Witnet.
**/
function completeUpdate() public witnetRequestAccepted(lastRequestId) {
require(pending, "There is no pending update.");
// Read the result of the Witnet request
// The `witnetReadResult` method comes with `UsingWitnet`
Witnet.Result memory result = witnetReadResult(lastRequestId);
// If the Witnet request succeeded, decode the result and update the price point
// If it failed, revert the transaction with a pretty-printed error message
if (result.isOk()) {
lastPrice = result.asUint64();
timestamp = block.timestamp;
emit priceUpdated(lastPrice);
} else {
string memory errorMessage;
// Try to read the value as an error message, catch error bytes if read fails
try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) {
errorMessage = e;
}
catch (bytes memory errorBytes){
errorMessage = string(errorBytes);
}
emit resultError(errorMessage);
}
// In any case, set `pending` to false so a new update can be requested
pending = false;
}
/**
* @notice Exposes the public data point in an ERC2362 compliant way.
* @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called
* successfully before.
**/
function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) {
// Unsupported data point ID
if(_id != ETHUSD3ID) return(0, 0, 400);
// No value is yet available for the queried data point ID
if (timestamp == 0) return(0, 0, 404);
int256 value = int256(lastPrice);
return(value, timestamp, 200);
}
}
// File: witnet-price-feeds-examples/contracts/requests/GoldPrice.sol
// The bytecode of the GoldPrice request that will be sent to Witnet
contract GoldPriceRequest is Request {
constructor () Request(hex"0ab90308c3aafbf4051257123f68747470733a2f2f636f696e7965702e636f6d2f6170692f76312f3f66726f6d3d58415526746f3d455552266c616e673d657326666f726d61743d6a736f6e1a148418778218646570726963658218571903e8185b1253122b68747470733a2f2f646174612d6173672e676f6c6470726963652e6f72672f64625852617465732f4555521a24861877821861656974656d73821818008218646878617550726963658218571903e8185b1255123668747470733a2f2f7777772e6d7963757272656e63797472616e736665722e636f6d2f6170692f63757272656e742f5841552f4555521a1b851877821866646461746182186464726174658218571903e8185b129101125d68747470733a2f2f7777772e696e766572736f726f2e65732f6461746f732f3f706572696f643d3379656172267869676e6974655f636f64653d5841552663757272656e63793d455552267765696768745f756e69743d6f756e6365731a308518778218666a7461626c655f64617461821864736d6574616c5f70726963655f63757272656e748218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { }
}
// File: witnet-price-feeds-examples/contracts/gold_price_feed/GoldEurPriceFeed.sol
// Import the UsingWitnet library that enables interacting with Witnet
// Import the ERC2362 interface
// Import the goldPrice request that you created before
// Your contract needs to inherit from UsingWitnet
contract GoldEurPriceFeed is UsingWitnet, IERC2362 {
// The public gold price point
uint64 public lastPrice;
// Stores the ID of the last Witnet request
uint256 public lastRequestId;
// Stores the timestamp of the last time the public price point was updated
uint256 public timestamp;
// Tells if an update has been requested but not yet completed
bool public pending;
// The Witnet request object, is set in the constructor
Request public request;
// Emits when the price is updated
event priceUpdated(uint64);
// Emits when found an error decoding request result
event resultError(string);
// This is the ERC2362 identifier for a gold price feed, computed as `keccak256("Price-XAU/EUR-3")`
bytes32 constant public XAUEUR3ID = bytes32(hex"68cba0705475e40c1ddbf7dc7c1ae4e7320ca094c4e118d1067c4dea5df28590");
// This constructor does a nifty trick to tell the `UsingWitnet` library where
// to find the Witnet contracts on whatever Ethereum network you use.
constructor (address _wrb) UsingWitnet(_wrb) public {
// Instantiate the Witnet request
request = new GoldPriceRequest();
}
/**
* @notice Sends `request` to the WitnetRequestsBoard.
* @dev This method will only succeed if `pending` is 0.
**/
function requestUpdate() public payable {
require(!pending, "An update is already pending. Complete it first before requesting another update.");
// Amount to pay to the bridge node relaying this request from Ethereum to Witnet
uint256 _witnetRequestReward = 100 szabo;
// Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum
uint256 _witnetResultReward = 100 szabo;
// Send the request to Witnet and store the ID for later retrieval of the result
// The `witnetPostRequest` method comes with `UsingWitnet`
lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward);
// Signal that there is already a pending request
pending = true;
}
/**
* @notice Reads the result, if ready, from the WitnetRequestsBoard.
* @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to
* protect your methods from being called before the request has been successfully
* relayed into Witnet.
**/
function completeUpdate() public witnetRequestAccepted(lastRequestId) {
require(pending, "There is no pending update.");
// Read the result of the Witnet request
// The `witnetReadResult` method comes with `UsingWitnet`
Witnet.Result memory result = witnetReadResult(lastRequestId);
// If the Witnet request succeeded, decode the result and update the price point
// If it failed, revert the transaction with a pretty-printed error message
if (result.isOk()) {
lastPrice = result.asUint64();
timestamp = block.timestamp;
emit priceUpdated(lastPrice);
} else {
string memory errorMessage;
// Try to read the value as an error message, catch error bytes if read fails
try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) {
errorMessage = e;
}
catch (bytes memory errorBytes){
errorMessage = string(errorBytes);
}
emit resultError(errorMessage);
}
// In any case, set `pending` to false so a new update can be requested
pending = false;
}
/**
* @notice Exposes the public data point in an ERC2362 compliant way.
* @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called
* successfully before.
**/
function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) {
// Unsupported data point ID
if(_id != XAUEUR3ID) return(0, 0, 400);
// No value is yet available for the queried data point ID
if (timestamp == 0) return(0, 0, 404);
int256 value = int256(lastPrice);
return(value, timestamp, 200);
}
}
// File: contracts/Deployer.sol
// Import witnet-ethereum-block-relay-contracts
// Import the UsingWitnet library that enables interacting with Witnet
// Import price feeds
contract Deployer {
}
// File: contracts/Migrations.sol
contract Migrations {
address public owner;
uint public lastCompletedMigration;
constructor() public {
owner = msg.sender;
}
modifier restricted() {
if (msg.sender == owner)
_;
}
function setCompleted(uint _completed) public restricted {
lastCompletedMigration = _completed;
}
function upgrade(address _newAddress) public restricted {
Migrations upgraded = Migrations(_newAddress);
upgraded.setCompleted(lastCompletedMigration);
}
}
| @dev Retrieves the result (if already available) of one data request from the WRB. @param _id The unique identifier of the data request. @return The result of the DR | function readResult(uint256 _id) external view override returns(bytes memory) {
require(requests.length > _id, "Id not found");
return requests[_id].result;
}
| 901,151 | [
1,
6960,
326,
563,
261,
430,
1818,
2319,
13,
434,
1245,
501,
590,
628,
326,
12984,
38,
18,
225,
389,
350,
1021,
3089,
2756,
434,
326,
501,
590,
18,
327,
1021,
563,
434,
326,
16801,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
855,
1253,
12,
11890,
5034,
389,
350,
13,
3903,
1476,
3849,
1135,
12,
3890,
3778,
13,
288,
203,
565,
2583,
12,
11420,
18,
2469,
405,
389,
350,
16,
315,
548,
486,
1392,
8863,
203,
565,
327,
3285,
63,
67,
350,
8009,
2088,
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
]
|
//Address: 0x70c1d6d067465c09f539de678af013aad2934cdd
//Contract name: Crowdsale
//Balance: 0 Ether
//Verification Date: 3/19/2018
//Transacion Count: 6
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @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 constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public 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);
}
/**
* @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 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) {
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 constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) 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 amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
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 specifing the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
owner = newOwner;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
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() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract BurnableByOwner is BasicToken, Ownable {
event Burn(address indexed burner, uint256 value);
function burn(address _address, uint256 _value) public onlyOwner{
require(_value <= balances[_address]);
// 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
address burner = _address;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(burner, _value);
emit Transfer(burner, address(0), _value);
}
}
contract Wolf is Ownable, MintableToken, BurnableByOwner {
using SafeMath for uint256;
string public constant name = "Wolf";
string public constant symbol = "Wolf";
uint32 public constant decimals = 18;
address public addressTeam;
address public addressCashwolf;
address public addressFutureInvest;
uint public summTeam = 15000000000 * 1 ether;
uint public summCashwolf = 10000000000 * 1 ether;
uint public summFutureInvest = 10000000000 * 1 ether;
function Wolf() public {
addressTeam = 0xb5AB520F01DeE8a42A2bfaEa8075398414774778;
addressCashwolf = 0x3366e9946DD375d1966c8E09f889Bc18C5E1579A;
addressFutureInvest = 0x7134121392eE0b6DC9382BBd8E392B4054CdCcEf;
//Founders and supporters initial Allocations
balances[addressTeam] = balances[addressTeam].add(summTeam);
balances[addressCashwolf] = balances[addressCashwolf].add(summCashwolf);
balances[addressFutureInvest] = balances[addressFutureInvest].add(summFutureInvest);
totalSupply = summTeam.add(summCashwolf).add(summFutureInvest);
}
function getTotalSupply() public constant returns(uint256){
return totalSupply;
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where Contributors can make
* token Contributions and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive. The contract requires a MintableToken that will be
* minted as contributions arrive, note that the crowdsale contract
* must be owner of the token in order to be able to mint it.
*/
contract Crowdsale is Ownable {
using SafeMath for uint256;
// soft cap
uint256 public softcap;
// balances for softcap
mapping(address => uint) public balancesSoftCap;
struct BuyInfo {
uint summEth;
uint summToken;
uint dateEndRefund;
}
mapping(address => mapping(uint => BuyInfo)) public payments;
mapping(address => uint) public paymentCounter;
// The token being offered
Wolf public token;
// start and end timestamps where investments are allowed (both inclusive)
// start
uint256 public startICO;
// end
uint256 public endICO;
uint256 public period;
uint256 public endICO14;
// token distribution
uint256 public hardCap;
uint256 public totalICO;
// how many token units a Contributor gets per wei
uint256 public rate;
// address where funds are collected
address public wallet;
// minimum/maximum quantity values
uint256 public minNumbPerSubscr;
uint256 public maxNumbPerSubscr;
/**
* event for token Procurement logging
* @param contributor who Pledged for the tokens
* @param beneficiary who got the tokens
* @param value weis Contributed for Procurement
* @param amount amount of tokens Procured
*/
event TokenProcurement(address indexed contributor, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale() public {
token = createTokenContract();
// soft cap
softcap = 100 * 1 ether;
// minimum quantity values
minNumbPerSubscr = 10000000000000000; //0.01 eth
maxNumbPerSubscr = 100 * 1 ether;
// start and end timestamps where investments are allowed
// start
startICO = 1521878400;// 03/24/2018 @ 8:00am (UTC)
period = 30;
// end
endICO = startICO + period * 1 days;
endICO14 = endICO + 14 * 1 days;
// restrictions on amounts during the crowdfunding event stages
hardCap = 65000000000 * 1 ether;
// rate;
rate = 1000000;
// address where funds are collected
wallet = 0x7472106A07EbAB5a202e195c0dC22776778b44E6;
}
function setStartICO(uint _startICO) public onlyOwner{
startICO = _startICO;
endICO = startICO + period * 1 days;
endICO14 = endICO + 14 * 1 days;
}
function setPeriod(uint _period) public onlyOwner{
period = _period;
endICO = startICO + period * 1 days;
endICO14 = endICO + 14 * 1 days;
}
function setRate(uint _rate) public onlyOwner{
rate = _rate;
}
function createTokenContract() internal returns (Wolf) {
return new Wolf();
}
// fallback function can be used to Procure tokens
function () external payable {
procureTokens(msg.sender);
}
// low level token Pledge function
function procureTokens(address beneficiary) public payable {
uint256 tokens;
uint256 weiAmount = msg.value;
uint256 backAmount;
require(beneficiary != address(0));
//minimum/maximum amount in ETH
require(weiAmount >= minNumbPerSubscr && weiAmount <= maxNumbPerSubscr);
if (now >= startICO && now <= endICO && totalICO < hardCap){
tokens = weiAmount.mul(rate);
if (hardCap.sub(totalICO) < tokens){
tokens = hardCap.sub(totalICO);
weiAmount = tokens.div(rate);
backAmount = msg.value.sub(weiAmount);
}
totalICO = totalICO.add(tokens);
}
require(tokens > 0);
token.mint(beneficiary, tokens);
balancesSoftCap[beneficiary] = balancesSoftCap[beneficiary].add(weiAmount);
uint256 dateEndRefund = now + 14 * 1 days;
paymentCounter[beneficiary] = paymentCounter[beneficiary] + 1;
payments[beneficiary][paymentCounter[beneficiary]] = BuyInfo(weiAmount, tokens, dateEndRefund);
if (backAmount > 0){
msg.sender.transfer(backAmount);
}
emit TokenProcurement(msg.sender, beneficiary, weiAmount, tokens);
}
function refund() public{
require(address(this).balance < softcap && now > endICO);
require(balancesSoftCap[msg.sender] > 0);
uint value = balancesSoftCap[msg.sender];
balancesSoftCap[msg.sender] = 0;
msg.sender.transfer(value);
}
function revoke(uint _id) public{
require(now <= payments[msg.sender][_id].dateEndRefund);
require(payments[msg.sender][_id].summEth > 0);
require(payments[msg.sender][_id].summToken > 0);
uint value = payments[msg.sender][_id].summEth;
uint valueToken = payments[msg.sender][_id].summToken;
balancesSoftCap[msg.sender] = balancesSoftCap[msg.sender].sub(value);
payments[msg.sender][_id].summEth = 0;
payments[msg.sender][_id].summToken = 0;
msg.sender.transfer(value);
token.burn(msg.sender, valueToken);
}
function transferToMultisig() public onlyOwner {
require(address(this).balance >= softcap && now > endICO14);
wallet.transfer(address(this).balance);
}
}
| Founders and supporters initial Allocations | function Wolf() public {
addressTeam = 0xb5AB520F01DeE8a42A2bfaEa8075398414774778;
addressCashwolf = 0x3366e9946DD375d1966c8E09f889Bc18C5E1579A;
addressFutureInvest = 0x7134121392eE0b6DC9382BBd8E392B4054CdCcEf;
balances[addressTeam] = balances[addressTeam].add(summTeam);
balances[addressCashwolf] = balances[addressCashwolf].add(summCashwolf);
balances[addressFutureInvest] = balances[addressFutureInvest].add(summFutureInvest);
totalSupply = summTeam.add(summCashwolf).add(summFutureInvest);
}
| 933,121 | [
1,
2043,
414,
471,
1169,
3831,
5432,
2172,
2262,
12352,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
678,
355,
74,
1435,
1071,
288,
203,
202,
2867,
8689,
273,
374,
6114,
25,
2090,
25,
3462,
42,
1611,
758,
41,
28,
69,
9452,
37,
22,
70,
507,
41,
69,
3672,
5877,
5520,
5193,
3461,
4700,
24,
4700,
28,
31,
203,
202,
2867,
39,
961,
91,
355,
74,
273,
374,
92,
3707,
6028,
73,
2733,
8749,
5698,
23,
5877,
72,
3657,
6028,
71,
28,
41,
5908,
74,
5482,
29,
38,
71,
2643,
39,
25,
41,
3600,
7235,
37,
31,
203,
202,
2867,
4118,
3605,
395,
273,
374,
92,
27,
25213,
2138,
3437,
9975,
73,
41,
20,
70,
26,
5528,
29,
7414,
22,
9676,
72,
28,
41,
5520,
22,
38,
24,
6260,
24,
19728,
39,
71,
41,
74,
31,
203,
202,
203,
203,
565,
324,
26488,
63,
2867,
8689,
65,
273,
324,
26488,
63,
2867,
8689,
8009,
1289,
12,
1364,
81,
8689,
1769,
203,
565,
324,
26488,
63,
2867,
39,
961,
91,
355,
74,
65,
273,
324,
26488,
63,
2867,
39,
961,
91,
355,
74,
8009,
1289,
12,
1364,
81,
39,
961,
91,
355,
74,
1769,
203,
202,
70,
26488,
63,
2867,
4118,
3605,
395,
65,
273,
324,
26488,
63,
2867,
4118,
3605,
395,
8009,
1289,
12,
1364,
81,
4118,
3605,
395,
1769,
203,
203,
565,
2078,
3088,
1283,
273,
2142,
81,
8689,
18,
1289,
12,
1364,
81,
39,
961,
91,
355,
74,
2934,
1289,
12,
1364,
81,
4118,
3605,
395,
1769,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xB690fC16279C096999264e3C049fA133024b4d69/sources/contracts/blueprints/DynamicBlueprint.sol | * @notice See {IDynamicBlueprint-updateOperatorFilterAndRegister}/ | function updateOperatorFilterAndRegister(
address newRegistry,
address coriCuratedSubscriptionAddress
) external override {
updateOperatorFilterRegistryAddress(newRegistry);
addOperatorFiltererSubscription(coriCuratedSubscriptionAddress);
}
| 3,599,366 | [
1,
9704,
288,
734,
3920,
30123,
17,
2725,
5592,
1586,
1876,
3996,
4004,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1089,
5592,
1586,
1876,
3996,
12,
203,
3639,
1758,
394,
4243,
16,
203,
3639,
1758,
1858,
77,
2408,
690,
6663,
1887,
203,
565,
262,
3903,
3849,
288,
203,
3639,
1089,
5592,
1586,
4243,
1887,
12,
2704,
4243,
1769,
203,
3639,
527,
5592,
1586,
264,
6663,
12,
3850,
77,
2408,
690,
6663,
1887,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
import "./Context.sol";
import "./IERC20.sol";
import "./SafeMath.sol";
import "./Owned.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 ERC20Farm is Context, IERC20, Owned {
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;
address public _minterContract;
address public _nftFarmingContract;
mapping (address => bool) private disabled_burn;
/**
* @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, address owner) public Owned(owner){
_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];
}
//set contract account that can mint and one that can farm
function setContracts(address minterContract, address nftFarmingContract) external onlyOwner returns (bool){
_minterContract=minterContract;
_nftFarmingContract=nftFarmingContract;
}
// to mint the YOU tokens by staking contract
function mintToFarm(uint256 amount) external payable onlyMinterContract returns (bool) {
_mint(msg.sender, amount);
return true;
}
// to burn YOU tokens by FarmingNFT contract
function burnToFarm(address account, uint256 amount) external onlynftFarmingContract returns (bool) {
require(disabled_burn[account] != true, "Account has disabled burning to be allowed by Farming contract");
_burn(account, amount);
return true;
}
// enable FarmingNFT contract to burn tokens
function enableFarmBurn() external returns (bool) {
require(disabled_burn[msg.sender] == true, "Account is already enabled burning to be allowed by Farming contract");
disabled_burn[msg.sender] = false;
return true;
}
// disable FarmingNFT contract to burn tokens:
// enabled by default
function disableFarmBurn() external returns (bool) {
require(disabled_burn[msg.sender] != true, "Account is already disabled burning to be allowed by Farming contract");
disabled_burn[msg.sender] = true;
return true;
}
/**
* @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 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 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 Throws if called by any account other than the minter.
*/
modifier onlyMinterContract() {
require(isMinterContract(), "caller is not the minting staking contract");
_;
}
/**
* @dev Returns true if the caller is the current minter.
*/
function isMinterContract() public view returns (bool) {
return _msgSender() == _minterContract;
}
/**
* @dev Throws if called by any account other than the minter.
*/
modifier onlynftFarmingContract() {
require(isnftFarmingContract(), "caller is not the nft farming contract");
_;
}
/**
* @dev Returns true if the caller is the current nft farming contract.
*/
function isnftFarmingContract() public view returns (bool) {
return _msgSender() == _nftFarmingContract;
}
} | * @dev Returns true if the caller is the current minter./ | function isMinterContract() public view returns (bool) {
return _msgSender() == _minterContract;
}
| 1,447,444 | [
1,
1356,
638,
309,
326,
4894,
353,
326,
783,
1131,
387,
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,
15707,
2761,
8924,
1435,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
389,
3576,
12021,
1435,
422,
389,
1154,
387,
8924,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/11155111/0x75B142FeaD91A708218ddCd26AcD492eB1674Eeb/sources/project_/contracts/handlers/PermissionlessGenericHandler.sol | 32 + 2 + 1 + 1 + 20 + 20
| require(data.length >= 76, "Incorrect data length"); | 3,804,027 | [
1,
1578,
397,
576,
397,
404,
397,
404,
397,
4200,
397,
4200,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2583,
12,
892,
18,
2469,
1545,
22997,
16,
315,
16268,
501,
769,
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
]
|
./full_match/314159/0x3d85c6060f1Ae7ab148E87805AFC05240965BEc7/sources/contracts/BasicFEVMDALN.sol | Add the token to the activeTokens array | activeTokens[lastActiveTokenIndex] = _tokenInfos[i];
| 16,361,663 | [
1,
986,
326,
1147,
358,
326,
2695,
5157,
526,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2695,
5157,
63,
2722,
3896,
1345,
1016,
65,
273,
389,
2316,
7655,
63,
77,
15533,
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
]
|
./partial_match/56/0xf54baA17caD136eED492856664C88CC45655F8bF/sources/UP.sol | * @dev Wrappers over Solidity's arithmetic operations with added overflow checks. Arithmetic operations in Solidity wrap on overflow. This can easily result in bugs, because programmers usually assume that an overflow raises an error, which is the standard behavior in high level programming languages. `SafeMath` restores this intuition by reverting the transaction when an operation overflows. Using this library instead of the unchecked operations eliminates an entire class of bugs, so it's recommended to use it always./ | library SafeMath {
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
| 11,052,585 | [
1,
24114,
1879,
348,
7953,
560,
1807,
30828,
5295,
598,
3096,
9391,
4271,
18,
27443,
5295,
316,
348,
7953,
560,
2193,
603,
9391,
18,
1220,
848,
17997,
563,
316,
22398,
16,
2724,
5402,
81,
414,
11234,
6750,
716,
392,
9391,
14183,
392,
555,
16,
1492,
353,
326,
4529,
6885,
316,
3551,
1801,
5402,
11987,
8191,
18,
1375,
9890,
10477,
68,
3127,
3485,
333,
509,
89,
608,
635,
15226,
310,
326,
2492,
1347,
392,
1674,
9391,
87,
18,
11637,
333,
5313,
3560,
434,
326,
22893,
5295,
19229,
4174,
392,
7278,
667,
434,
22398,
16,
1427,
518,
1807,
14553,
358,
999,
518,
3712,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
12083,
14060,
10477,
288,
203,
7010,
565,
445,
775,
986,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
6430,
16,
2254,
5034,
13,
288,
203,
3639,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
3639,
309,
261,
71,
411,
279,
13,
327,
261,
5743,
16,
374,
1769,
203,
3639,
327,
261,
3767,
16,
276,
1769,
203,
565,
289,
203,
7010,
565,
445,
775,
1676,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
6430,
16,
2254,
5034,
13,
288,
203,
3639,
309,
261,
70,
405,
279,
13,
327,
261,
5743,
16,
374,
1769,
203,
3639,
327,
261,
3767,
16,
279,
300,
324,
1769,
203,
565,
289,
203,
7010,
565,
445,
775,
27860,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
6430,
16,
2254,
5034,
13,
288,
203,
3639,
309,
261,
69,
422,
374,
13,
327,
261,
3767,
16,
374,
1769,
203,
3639,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
3639,
309,
261,
71,
342,
279,
480,
324,
13,
327,
261,
5743,
16,
374,
1769,
203,
3639,
327,
261,
3767,
16,
276,
1769,
203,
565,
289,
203,
7010,
565,
445,
775,
7244,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
6430,
16,
2254,
5034,
13,
288,
203,
3639,
309,
261,
70,
422,
374,
13,
327,
261,
5743,
16,
374,
1769,
203,
3639,
327,
261,
3767,
16,
279,
342,
324,
1769,
203,
565,
289,
203,
7010,
565,
445,
775,
1739,
12,
11890,
5034,
279,
2
]
|
./full_match/1/0x864a1CBB53b9Dea3691a6974B456088C2771DcAd/sources/browser/Bar.sol | Internal view function to get all of the extra data for a single pool Only calculate with fixed apr after the Soft Launch User pool informationpoolMetadata[14] = _pendingUni(_pid, _user);poolMetadata[16] = _userInfo.uniClaimed; | function _getPoolMetadataFor(uint256 _pid, address _user, uint256 _boogiePrice) internal view returns (uint[17] memory poolMetadata) {
PoolInfo memory pool = poolInfo[_pid];
uint256 totalSupply;
uint256 totalLPSupply;
uint256 stakedLPSupply;
uint256 tokenPrice;
uint256 lpTokenPrice;
uint256 totalLiquidityValue;
uint256 boogiePerBlock;
if (_pid != 0 || boogiePoolActive == true) {
totalSupply = pool.token.totalSupply();
totalLPSupply = pool.lpToken.totalSupply();
stakedLPSupply = _getPoolSupply(_pid);
tokenPrice = 10**uint256(pool.token.decimals()) * weth.balanceOf(address(pool.lpToken)) / pool.token.balanceOf(address(pool.lpToken));
lpTokenPrice = 10**18 * 2 * weth.balanceOf(address(pool.lpToken)) / totalLPSupply;
totalLiquidityValue = stakedLPSupply * lpTokenPrice / 1e18;
}
if (block.number >= startBlock + SOFT_LAUNCH_DURATION) {
boogiePerBlock = ((pool.apr * 1e18 * totalLiquidityValue / _boogiePrice) / APPROX_BLOCKS_PER_YEAR) / 100;
if (_pid != 0) {
boogiePerBlock = SOFT_LAUNCH_BOOGIE_PER_BLOCK;
boogiePerBlock = 25 * SOFT_LAUNCH_BOOGIE_PER_BLOCK;
}
}
poolMetadata[1] = totalLPSupply;
poolMetadata[2] = stakedLPSupply;
poolMetadata[3] = tokenPrice;
poolMetadata[4] = lpTokenPrice;
poolMetadata[5] = totalLiquidityValue;
poolMetadata[6] = boogiePerBlock;
poolMetadata[7] = pool.token.decimals();
if (_pid != 0 || boogiePoolActive == true) {
UserInfo memory _userInfo = userInfo[_pid][_user];
poolMetadata[8] = pool.token.balanceOf(_user);
poolMetadata[9] = pool.token.allowance(_user, address(this));
poolMetadata[10] = pool.lpToken.balanceOf(_user);
poolMetadata[11] = pool.lpToken.allowance(_user, address(this));
poolMetadata[12] = _userInfo.staked;
poolMetadata[13] = _pendingBoogie(_pid, _user);
poolMetadata[15] = _userInfo.claimed;
}
}
| 4,927,156 | [
1,
3061,
1476,
445,
358,
336,
777,
434,
326,
2870,
501,
364,
279,
2202,
2845,
5098,
4604,
598,
5499,
513,
86,
1839,
326,
12438,
14643,
2177,
2845,
1779,
6011,
2277,
63,
3461,
65,
273,
389,
9561,
984,
77,
24899,
6610,
16,
389,
1355,
1769,
6011,
2277,
63,
2313,
65,
273,
389,
1355,
966,
18,
318,
77,
9762,
329,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
389,
588,
2864,
2277,
1290,
12,
11890,
5034,
389,
6610,
16,
1758,
389,
1355,
16,
2254,
5034,
389,
1075,
717,
1385,
5147,
13,
2713,
1476,
1135,
261,
11890,
63,
4033,
65,
3778,
2845,
2277,
13,
288,
203,
3639,
8828,
966,
3778,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
203,
3639,
2254,
5034,
2078,
3088,
1283,
31,
203,
3639,
2254,
5034,
2078,
14461,
3088,
1283,
31,
203,
3639,
2254,
5034,
384,
9477,
14461,
3088,
1283,
31,
203,
3639,
2254,
5034,
1147,
5147,
31,
203,
3639,
2254,
5034,
12423,
1345,
5147,
31,
203,
3639,
2254,
5034,
2078,
48,
18988,
24237,
620,
31,
203,
3639,
2254,
5034,
800,
717,
1385,
2173,
1768,
31,
203,
203,
3639,
309,
261,
67,
6610,
480,
374,
747,
800,
717,
1385,
2864,
3896,
422,
638,
13,
288,
203,
5411,
2078,
3088,
1283,
273,
2845,
18,
2316,
18,
4963,
3088,
1283,
5621,
203,
5411,
2078,
14461,
3088,
1283,
273,
2845,
18,
9953,
1345,
18,
4963,
3088,
1283,
5621,
203,
5411,
384,
9477,
14461,
3088,
1283,
273,
389,
588,
2864,
3088,
1283,
24899,
6610,
1769,
203,
203,
5411,
1147,
5147,
273,
1728,
636,
11890,
5034,
12,
6011,
18,
2316,
18,
31734,
10756,
380,
341,
546,
18,
12296,
951,
12,
2867,
12,
6011,
18,
9953,
1345,
3719,
342,
2845,
18,
2316,
18,
12296,
951,
12,
2867,
12,
6011,
18,
9953,
1345,
10019,
203,
5411,
12423,
1345,
5147,
273,
1728,
636,
2643,
380,
576,
380,
341,
546,
18,
12296,
951,
12,
2867,
12,
6011,
18,
9953,
1345,
3719,
342,
2078,
14461,
3088,
2
]
|
./full_match/80001/0xf494169441E0Ef3708EFA9d2E4c01BaB184a98ea/sources/StakeManager.sol | * Modifier requiring the current block to be the first block of the epoch./ | modifier onlyFirstBlock() {
if (!environment.isFirstBlock()) revert OnlyFirstBlock();
_;
}
| 857,851 | [
1,
9829,
29468,
326,
783,
1203,
358,
506,
326,
1122,
1203,
434,
326,
7632,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
9606,
1338,
3759,
1768,
1435,
288,
203,
3639,
309,
16051,
10274,
18,
291,
3759,
1768,
10756,
15226,
5098,
3759,
1768,
5621,
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,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
// Access Control
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
// Safe Math
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/// @title Letter Contract.
/// @author Bernardo A. Rodrigues.
/// @notice This contract defines a Letter, where each Page is a NFT.
/// @dev This contract defines a Letter, where each Page is a NFT.
contract Letter is ERC721Upgradeable, OwnableUpgradeable, AccessControlUpgradeable {
/// No high severity issues found
/// Reviewed line-by-line and no vulnerabilities detected
/// Therefore, smart contract is recommended to be deployed to mainnet
/// 3rd Party Audited by @dev Francis Isberto
// Letter constants
uint private constant MAX_TITLE_LEN = 64;
uint private constant MAX_PAGE_LEN = 8192;
uint private constant MAX_AUTHOR_LEN = 64;
// Letter vars
string private _title;
string private _author;
bool private _open;
string[] private _pages; // Each page is a Token
// Letter events
event letterInit(address owner, string _titleMint, string _authorMint);
event pageMint(address owner, string page, uint256 pageNumber);
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// ---------------------------------------
/// @notice Initializer of the Letter contract.
/// @dev Initializer of the Letter contract.
/// @param _titleMint Title of the Letter.
/// @param _firstPageMint Contents of the 1st Letter Page.
/// @param _authorMint Author Signature of the Letter (as in handwritten signature; NOT as in cryptographic signature).
/// @param _owner Owner of Letter contract.
function initLetter(string memory _titleMint, string memory _firstPageMint, string memory _authorMint, address _owner)
public
initializer {
__ERC721_init("Letter", "LETT");
__Ownable_init();
// Page Title is optional, max 64 characters
if (getStringLength(_titleMint) != 0) {
require((getStringLength(_titleMint) <= MAX_TITLE_LEN), "Title exceeds MAX_TITLE_LEN");
_title = _titleMint;
}
// Page Body is optional, max 8192 characters
if (getStringLength(_firstPageMint) != 0){
require((getStringLength(_firstPageMint) <= MAX_PAGE_LEN), "Page exceed MAX_PAGE_LEN");
}
// Page Author is optional, max 64 characters
if (getStringLength(_authorMint) != 0) {
require((getStringLength(_authorMint) <= MAX_AUTHOR_LEN), "Author exceeds MAX_AUTHOR_LEN");
_author = _authorMint;
}
// Mint first Page
uint256 _pageNumber = _pages.length;
_mint(_owner, _pageNumber);
emit letterInit(_owner, _titleMint, _authorMint);
emit pageMint(_owner, _firstPageMint, _pageNumber);
// save Page
_pages.push(_firstPageMint);
// Factory Contract + Owner are Admin
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
// Owner is Reader
grantRole(READER_ROLE, _owner);
// set Letter Contract Owner
transferOwnership(_owner);
}
// ---------------------------------------
// Access Control
bytes32 private constant READER_ROLE = keccak256("READER");
modifier onlyReader() {
if (!_open){
require (hasRole(READER_ROLE, msg.sender), "Restricted to Reader Role");
}
_;
}
/// @notice Check if Account belongs to Reader Role.
/// @dev Check if Account belongs to Reader Role.
/// @param _account Address of Account to be checked against Reader Role.
/// @return bool True if Account belongs to Reader Role, False otherwise.
function isReader(address _account)
public
view
returns (bool){
if (_open){
return true;
}
return hasRole(READER_ROLE, _account);
}
/// @notice Add an account to the Reader role. Restricted to Owner.
/// @dev Add an account to the Reader role. Restricted to Owner.
/// @param _account Address of Account to be added to Reader Role.
function addReader(address _account)
public
virtual
onlyOwner {
grantRole(READER_ROLE, _account);
}
/// @notice Remove an account from the Reader role. Restricted to Owner.
/// @dev Remove an account from the Reader role. Restricted to Owner.
/// @param _account Address of Account to be removed from Reader Role.
function removeReader(address _account)
public
virtual
onlyOwner {
revokeRole(READER_ROLE, _account);
}
/// @notice Open Reader Role (every Account can Read)
/// @dev Open Reader Role (every Account can Read)
function open()
public
virtual
onlyOwner {
_open = true;
}
/// @notice
/// @dev Close Reader Role (only Reader accounts can Read)
/// @dev Close Reader Role (only Reader accounts can Read)
function close()
public
virtual
onlyOwner {
_open = false;
}
// ---------------------------------------
// View functions
/// @notice Read Letter Title. Restricted to Accounts with Reader Role.
/// @dev Read Letter Title. Restricted to Accounts with Reader Role.
/// @return string Letter Title.
function readTitle()
public
view
onlyReader
returns (string memory) {
return _title;
}
/// @notice Read Letter Author. Restricted to Accounts with Reader Role.
/// @dev Read Letter Author. Restricted to Accounts with Reader Role.
/// @return string Letter Author.
function readAuthor()
public
view
onlyReader
returns (string memory) {
return _author;
}
/// @notice Reade Page. Restricted to Accounts with Reader Role.
/// @dev Reade Page. Restricted to Accounts with Reader Role.
/// @param _pageN Number (Token Id) of Page (NFT) to be read.
/// @return string Page Contents.
function readPage(uint256 _pageN)
public
view
onlyReader
returns (string memory) {
require ((_pageN < _pages.length), "Can't read non-existent Page");
return _pages[_pageN];
}
/// @notice View Page Count. Restricted to Accounts with Reader Role.
/// @dev View Page Count. Restricted to Accounts with Reader Role.
/// @return uint256 Letter Page Count.
function viewPageCount()
public
view
onlyReader
returns (uint256) {
return _pages.length;
}
/// @notice Check whether Letter is Open.
/// @dev Check whether Letter is Open.
/// @return bool True if Letter is Open, False if Letter is Closed.
function isOpen()
public
view
returns (bool) {
return _open;
}
// ---------------------------------------
// Utility functions
/// @notice Utility for calculating String Length.
/// @dev Utility for calculating String Length.
/// @param _s String for Length to be checked.
/// @return uint Length of String.
function getStringLength(string memory _s)
private
pure
returns (uint) {
bytes memory bs = bytes(_s);
return bs.length;
}
// ---------------------------------------
// Mint new Page function
/// @notice Write new Page (NFT) and append it to Letter. Restricted to Owner.
/// @dev Write new Page (NFT) and append it to Letter. Restricted to Owner.
/// @param _pageMint String with Page contents.
function writePage(string memory _pageMint)
public
onlyOwner
{
// Page Body is mandatory, max 65536 characters
require((getStringLength(_pageMint) != 0), "Cannot mint empty page");
require((getStringLength(_pageMint) <= MAX_PAGE_LEN), "Page exceeds MAX_PAGE_LEN");
// Mint Page Token
uint256 _pageNumber = _pages.length;
_mint(msg.sender, _pageNumber);
// save Page
_pages.push(_pageMint);
}
/// @notice Override, imposed by Interfaces from AccessControlUpgradeable and ERC721Upgradeable.
/// @dev Override, imposed by Interfaces from AccessControlUpgradeable and ERC721Upgradeable.
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlUpgradeable, ERC721Upgradeable) returns (bool) {
return
interfaceId == type(IAccessControlUpgradeable).interfaceId ||
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/// @notice Override, guarantees that after Page NFT is transferred, new Owner belongs to Reader role.
/// @dev Override, guarantees that after Page NFT is transferred, new Owner belongs to Reader role.
/// @param from Address of previous Owner.
/// @param to Address of new Owner.
/// @param tokenId Page Number (NF Token Id).
/// @param _data Data.
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);
// New Page owner belongs to Reader role
_setupRole(READER_ROLE, to);
}
/// @notice Override, guarantees that after Page NFT is transferred, new Owner belongs to Reader role.
/// @dev Override, guarantees that after Page NFT is transferred, new Owner belongs to Reader role.
/// @param from Address of previous Owner.
/// @param to Address of new Owner.
/// @param tokenId Page Number (NF Token Id).
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);
// New Page owner belongs to Reader role
_setupRole(READER_ROLE, to);
}
}
| @notice Open Reader Role (every Account can Read) @dev Open Reader Role (every Account can Read) | function open()
public
virtual
onlyOwner {
_open = true;
}
| 12,659,725 | [
1,
3678,
5393,
6204,
261,
20434,
6590,
848,
2720,
13,
225,
3502,
5393,
6204,
261,
20434,
6590,
848,
2720,
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
]
| [
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,
1696,
1435,
203,
565,
1071,
203,
565,
5024,
203,
565,
1338,
5541,
288,
203,
3639,
389,
3190,
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
]
|
./partial_match/1/0xdF1d7FD22aC3aB5171E275796f123224039f3b24/sources/src/v0.8/ccip/onRamp/EVM2EVMOnRamp.sol | @notice Calculate remaining LINK balance after paying nops @return balance if nops were to be paid Since LINK caps at uint96, casting to int256 is safe | function _linkLeftAfterNopFees() private view returns (int256) {
return int256(IERC20(i_linkToken).balanceOf(address(this))) - int256(uint256(s_nopFeesJuels));
}
| 4,303,831 | [
1,
8695,
4463,
22926,
11013,
1839,
8843,
310,
290,
4473,
327,
11013,
309,
290,
4473,
4591,
358,
506,
30591,
7897,
22926,
15788,
622,
2254,
10525,
16,
27660,
358,
509,
5034,
353,
4183,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
389,
1232,
3910,
4436,
50,
556,
2954,
281,
1435,
3238,
1476,
1135,
261,
474,
5034,
13,
288,
203,
565,
327,
509,
5034,
12,
45,
654,
39,
3462,
12,
77,
67,
1232,
1345,
2934,
12296,
951,
12,
2867,
12,
2211,
20349,
300,
509,
5034,
12,
11890,
5034,
12,
87,
67,
82,
556,
2954,
281,
46,
89,
10558,
10019,
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
]
|
pragma solidity ^0.4.23;
/******* USING Registry **************************
Gives the inherting contract access to:
.addressOf(bytes32): returns current address mapped to the name.
[modifier] .fromOwner(): requires the sender is owner.
*************************************************/
// Returned by .getRegistry()
interface IRegistry {
function owner() external view returns (address _addr);
function addressOf(bytes32 _name) external view returns (address _addr);
}
contract UsingRegistry {
IRegistry private registry;
modifier fromOwner(){
require(msg.sender == getOwner());
_;
}
constructor(address _registry)
public
{
require(_registry != 0);
registry = IRegistry(_registry);
}
function addressOf(bytes32 _name)
internal
view
returns(address _addr)
{
return registry.addressOf(_name);
}
function getOwner()
public
view
returns (address _addr)
{
return registry.owner();
}
function getRegistry()
public
view
returns (IRegistry _addr)
{
return registry;
}
}
/******* USING ADMIN ***********************
Gives the inherting contract access to:
.getAdmin(): returns the current address of the admin
[modifier] .fromAdmin: requires the sender is the admin
*************************************************/
contract UsingAdmin is
UsingRegistry
{
constructor(address _registry)
UsingRegistry(_registry)
public
{}
modifier fromAdmin(){
require(msg.sender == getAdmin());
_;
}
function getAdmin()
public
constant
returns (address _addr)
{
return addressOf("ADMIN");
}
}
/**
This is a simple class that maintains a doubly linked list of
address => uint amounts. Address balances can be added to
or removed from via add() and subtract(). All balances can
be obtain by calling balances(). If an address has a 0 amount,
it is removed from the Ledger.
Note: THIS DOES NOT TEST FOR OVERFLOWS, but it's safe to
use to track Ether balances.
Public methods:
- [fromOwner] add()
- [fromOwner] subtract()
Public views:
- total()
- size()
- balanceOf()
- balances()
- entries() [to manually iterate]
*/
contract Ledger {
uint public total; // Total amount in Ledger
struct Entry { // Doubly linked list tracks amount per address
uint balance;
address next;
address prev;
}
mapping (address => Entry) public entries;
address public owner;
modifier fromOwner() { require(msg.sender==owner); _; }
// Constructor sets the owner
constructor(address _owner)
public
{
owner = _owner;
}
/******************************************************/
/*************** OWNER METHODS ************************/
/******************************************************/
function add(address _address, uint _amt)
fromOwner
public
{
if (_address == address(0) || _amt == 0) return;
Entry storage entry = entries[_address];
// If new entry, replace first entry with this one.
if (entry.balance == 0) {
entry.next = entries[0x0].next;
entries[entries[0x0].next].prev = _address;
entries[0x0].next = _address;
}
// Update stats.
total += _amt;
entry.balance += _amt;
}
function subtract(address _address, uint _amt)
fromOwner
public
returns (uint _amtRemoved)
{
if (_address == address(0) || _amt == 0) return;
Entry storage entry = entries[_address];
uint _maxAmt = entry.balance;
if (_maxAmt == 0) return;
if (_amt >= _maxAmt) {
// Subtract the max amount, and delete entry.
total -= _maxAmt;
entries[entry.prev].next = entry.next;
entries[entry.next].prev = entry.prev;
delete entries[_address];
return _maxAmt;
} else {
// Subtract the amount from entry.
total -= _amt;
entry.balance -= _amt;
return _amt;
}
}
/******************************************************/
/*************** PUBLIC VIEWS *************************/
/******************************************************/
function size()
public
view
returns (uint _size)
{
// Loop once to get the total count.
Entry memory _curEntry = entries[0x0];
while (_curEntry.next > 0) {
_curEntry = entries[_curEntry.next];
_size++;
}
return _size;
}
function balanceOf(address _address)
public
view
returns (uint _balance)
{
return entries[_address].balance;
}
function balances()
public
view
returns (address[] _addresses, uint[] _balances)
{
// Populate names and addresses
uint _size = size();
_addresses = new address[](_size);
_balances = new uint[](_size);
uint _i = 0;
Entry memory _curEntry = entries[0x0];
while (_curEntry.next > 0) {
_addresses[_i] = _curEntry.next;
_balances[_i] = entries[_curEntry.next].balance;
_curEntry = entries[_curEntry.next];
_i++;
}
return (_addresses, _balances);
}
}
/*
This is an abstract contract, inherited by Treasury, that manages
creating, cancelling, and executing admin requests that control
capital. It provides transparency, governence, and security.
In the future, the Admin account can be set to be a DAO.
A Request:
- can only be created by Admin
- can be cancelled by Admin, if not yet executed
- can be executed after WAITING_TIME (1 week)
- cannot be executed after TIMEOUT_TIME (2 weeks)
- contains a type, target, and value
- when executed, calls corresponding `execute${type}()` method
*/
contract Requestable is
UsingAdmin
{
uint32 public constant WAITING_TIME = 60*60*24*7; // 1 week
uint32 public constant TIMEOUT_TIME = 60*60*24*14; // 2 weeks
uint32 public constant MAX_PENDING_REQUESTS = 10;
// Requests.
enum RequestType {SendCapital, RecallCapital, RaiseCapital, DistributeCapital}
struct Request {
// Params to handle state and history.
uint32 id;
uint8 typeId;
uint32 dateCreated;
uint32 dateCancelled;
uint32 dateExecuted;
string createdMsg;
string cancelledMsg;
string executedMsg;
bool executedSuccessfully;
// Params for execution.
address target;
uint value;
}
mapping (uint32 => Request) public requests;
uint32 public curRequestId;
uint32[] public completedRequestIds;
uint32[] public cancelledRequestIds;
uint32[] public pendingRequestIds;
// Events.
event RequestCreated(uint time, uint indexed id, uint indexed typeId, address indexed target, uint value, string msg);
event RequestCancelled(uint time, uint indexed id, uint indexed typeId, address indexed target, string msg);
event RequestExecuted(uint time, uint indexed id, uint indexed typeId, address indexed target, bool success, string msg);
constructor(address _registry)
UsingAdmin(_registry)
public
{ }
// Creates a request, assigning it the next ID.
// Throws if there are already 8 pending requests.
function createRequest(uint _typeId, address _target, uint _value, string _msg)
public
fromAdmin
{
uint32 _id = ++curRequestId;
requests[_id].id = _id;
requests[_id].typeId = uint8(RequestType(_typeId));
requests[_id].dateCreated = uint32(now);
requests[_id].createdMsg = _msg;
requests[_id].target = _target;
requests[_id].value = _value;
_addPendingRequestId(_id);
emit RequestCreated(now, _id, _typeId, _target, _value, _msg);
}
// Cancels a request.
// Throws if already cancelled or executed.
function cancelRequest(uint32 _id, string _msg)
public
fromAdmin
{
// Require Request exists, is not cancelled, is not executed.
Request storage r = requests[_id];
require(r.id != 0 && r.dateCancelled == 0 && r.dateExecuted == 0);
r.dateCancelled = uint32(now);
r.cancelledMsg = _msg;
_removePendingRequestId(_id);
cancelledRequestIds.push(_id);
emit RequestCancelled(now, r.id, r.typeId, r.target, _msg);
}
// Executes (or times out) a request if it is not already cancelled or executed.
// Note: This may revert if the executeFn() reverts. It'll time-out eventually.
function executeRequest(uint32 _id)
public
{
// Require Request exists, is not cancelled, is not executed.
// Also require is past WAITING_TIME since creation.
Request storage r = requests[_id];
require(r.id != 0 && r.dateCancelled == 0 && r.dateExecuted == 0);
require(uint32(now) > r.dateCreated + WAITING_TIME);
// If request timed out, cancel it.
if (uint32(now) > r.dateCreated + TIMEOUT_TIME) {
cancelRequest(_id, "Request timed out.");
return;
}
// Execute concrete method after setting as executed.
r.dateExecuted = uint32(now);
string memory _msg;
bool _success;
RequestType _type = RequestType(r.typeId);
if (_type == RequestType.SendCapital) {
(_success, _msg) = executeSendCapital(r.target, r.value);
} else if (_type == RequestType.RecallCapital) {
(_success, _msg) = executeRecallCapital(r.target, r.value);
} else if (_type == RequestType.RaiseCapital) {
(_success, _msg) = executeRaiseCapital(r.value);
} else if (_type == RequestType.DistributeCapital) {
(_success, _msg) = executeDistributeCapital(r.value);
}
// Save results, and emit.
r.executedSuccessfully = _success;
r.executedMsg = _msg;
_removePendingRequestId(_id);
completedRequestIds.push(_id);
emit RequestExecuted(now, r.id, r.typeId, r.target, _success, _msg);
}
// Pushes id onto the array, throws if too many.
function _addPendingRequestId(uint32 _id)
private
{
require(pendingRequestIds.length != MAX_PENDING_REQUESTS);
pendingRequestIds.push(_id);
}
// Removes id from array, reduces array length by one.
// Throws if not found.
function _removePendingRequestId(uint32 _id)
private
{
// Find this id in the array, or throw.
uint _len = pendingRequestIds.length;
uint _foundIndex = MAX_PENDING_REQUESTS;
for (uint _i = 0; _i < _len; _i++) {
if (pendingRequestIds[_i] == _id) {
_foundIndex = _i;
break;
}
}
require(_foundIndex != MAX_PENDING_REQUESTS);
// Swap last element to this index, then delete last element.
pendingRequestIds[_foundIndex] = pendingRequestIds[_len-1];
pendingRequestIds.length--;
}
// These methods must be implemented by Treasury /////////////////
function executeSendCapital(address _target, uint _value)
internal returns (bool _success, string _msg);
function executeRecallCapital(address _target, uint _value)
internal returns (bool _success, string _msg);
function executeRaiseCapital(uint _value)
internal returns (bool _success, string _msg);
function executeDistributeCapital(uint _value)
internal returns (bool _success, string _msg);
//////////////////////////////////////////////////////////////////
// View that returns a Request as a valid tuple.
// Sorry for the formatting, but it's a waste of lines otherwise.
function getRequest(uint32 _requestId) public view returns (
uint32 _id, uint8 _typeId, address _target, uint _value,
bool _executedSuccessfully,
uint32 _dateCreated, uint32 _dateCancelled, uint32 _dateExecuted,
string _createdMsg, string _cancelledMsg, string _executedMsg
) {
Request memory r = requests[_requestId];
return (
r.id, r.typeId, r.target, r.value,
r.executedSuccessfully,
r.dateCreated, r.dateCancelled, r.dateExecuted,
r.createdMsg, r.cancelledMsg, r.executedMsg
);
}
function isRequestExecutable(uint32 _requestId)
public
view
returns (bool _isExecutable)
{
Request memory r = requests[_requestId];
_isExecutable = (r.id>0 && r.dateCancelled==0 && r.dateExecuted==0);
_isExecutable = _isExecutable && (uint32(now) > r.dateCreated + WAITING_TIME);
return _isExecutable;
}
// Return the lengths of arrays.
function numPendingRequests() public view returns (uint _num){
return pendingRequestIds.length;
}
function numCompletedRequests() public view returns (uint _num){
return completedRequestIds.length;
}
function numCancelledRequests() public view returns (uint _num){
return cancelledRequestIds.length;
}
}
/*
UI: https://www.pennyether.com/status/treasury
The Treasury manages 2 balances:
* capital: Ether that can be sent to bankrollable contracts.
- Is controlled via `Requester` governance, by the Admin (which is mutable)
- Capital received by Comptroller is considered "capitalRaised".
- A target amount can be set: "capitalRaisedTarget".
- Comptroller will sell Tokens to reach capitalRaisedTarget.
- Can be sent to Bankrollable contracts.
- Can be recalled from Bankrollable contracts.
- Allocation in-total and per-contract is available.
* profits: Ether received via fallback fn. Can be sent to Token at any time.
- Are received via fallback function, typically by bankrolled contracts.
- Can be sent to Token at any time, by anyone, via .issueDividend()
All Ether entering and leaving Treasury is allocated to one of the three balances.
Thus, the balance of Treasury will always equal: capital + profits.
Roles:
Owner: can set Comptroller and Token addresses, once.
Comptroller: can add and remove "raised" capital
Admin: can trigger requests.
Token: receives profits via .issueDividend().
Anybody: can call .issueDividend()
can call .addCapital()
*/
// Allows Treasury to add/remove capital to/from Bankrollable instances.
interface _ITrBankrollable {
function removeBankroll(uint _amount, string _callbackFn) external;
function addBankroll() external payable;
}
interface _ITrComptroller {
function treasury() external view returns (address);
function token() external view returns (address);
function wasSaleEnded() external view returns (bool);
}
contract Treasury is
Requestable
{
// Address that can initComptroller
address public owner;
// Capital sent from this address is considered "capitalRaised"
// This also contains the token that dividends will be sent to.
_ITrComptroller public comptroller;
// Balances
uint public capital; // Ether held as capital. Sendable/Recallable via Requests
uint public profits; // Ether received via fallback fn. Distributable only to Token.
// Capital Management
uint public capitalRaised; // The amount of capital raised from Comptroller.
uint public capitalRaisedTarget; // The target amount of capitalRaised.
Ledger public capitalLedger; // Tracks capital allocated per address
// Stats
uint public profitsSent; // Total profits ever sent.
uint public profitsTotal; // Total profits ever received.
// EVENTS
event Created(uint time);
// Admin triggered events
event ComptrollerSet(uint time, address comptroller, address token);
// capital-related events
event CapitalAdded(uint time, address indexed sender, uint amount);
event CapitalRemoved(uint time, address indexed recipient, uint amount);
event CapitalRaised(uint time, uint amount);
// profit-related events
event ProfitsReceived(uint time, address indexed sender, uint amount);
// request-related events
event ExecutedSendCapital(uint time, address indexed bankrollable, uint amount);
event ExecutedRecallCapital(uint time, address indexed bankrollable, uint amount);
event ExecutedRaiseCapital(uint time, uint amount);
event ExecutedDistributeCapital(uint time, uint amount);
// dividend events
event DividendSuccess(uint time, address token, uint amount);
event DividendFailure(uint time, string msg);
// `Requester` provides .fromAdmin() and requires implementation of:
// - executeSendCapital
// - executeRecallCapital
// - executeRaiseCapital
constructor(address _registry, address _owner)
Requestable(_registry)
public
{
owner = _owner;
capitalLedger = new Ledger(this);
emit Created(now);
}
/*************************************************************/
/*************** OWNER FUNCTIONS *****************************/
/*************************************************************/
// Callable once to set the Comptroller address
function initComptroller(_ITrComptroller _comptroller)
public
{
// only owner can call this.
require(msg.sender == owner);
// comptroller must not already be set.
require(address(comptroller) == address(0));
// comptroller's treasury must point to this.
require(_comptroller.treasury() == address(this));
comptroller = _comptroller;
emit ComptrollerSet(now, _comptroller, comptroller.token());
}
/*************************************************************/
/******* PROFITS AND DIVIDENDS *******************************/
/*************************************************************/
// Can receive Ether from anyone. Typically Bankrollable contracts' profits.
function () public payable {
profits += msg.value;
profitsTotal += msg.value;
emit ProfitsReceived(now, msg.sender, msg.value);
}
// Sends profits to Token
function issueDividend()
public
returns (uint _profits)
{
// Ensure token is set.
if (address(comptroller) == address(0)) {
emit DividendFailure(now, "Comptroller not yet set.");
return;
}
// Ensure the CrowdSale is completed
if (comptroller.wasSaleEnded() == false) {
emit DividendFailure(now, "CrowdSale not yet completed.");
return;
}
// Load _profits to memory (saves gas), and ensure there are profits.
_profits = profits;
if (_profits <= 0) {
emit DividendFailure(now, "No profits to send.");
return;
}
// Set profits to 0, and send to Token
address _token = comptroller.token();
profits = 0;
profitsSent += _profits;
require(_token.call.value(_profits)());
emit DividendSuccess(now, _token, _profits);
}
/*************************************************************/
/*************** ADDING CAPITAL ******************************/
/*************************************************************/
// Anyone can add capital at any time.
// If it comes from Comptroller, it counts as capitalRaised.
function addCapital()
public
payable
{
capital += msg.value;
if (msg.sender == address(comptroller)) {
capitalRaised += msg.value;
emit CapitalRaised(now, msg.value);
}
emit CapitalAdded(now, msg.sender, msg.value);
}
/*************************************************************/
/*************** REQUESTER IMPLEMENTATION ********************/
/*************************************************************/
// Removes from capital, sends it to Bankrollable target.
function executeSendCapital(address _bankrollable, uint _value)
internal
returns (bool _success, string _result)
{
// Fail if we do not have the capital available.
if (_value > capital)
return (false, "Not enough capital.");
// Fail if target is not Bankrollable
if (!_hasCorrectTreasury(_bankrollable))
return (false, "Bankrollable does not have correct Treasury.");
// Decrease capital, increase bankrolled
capital -= _value;
capitalLedger.add(_bankrollable, _value);
// Send it (this throws on failure). Then emit events.
_ITrBankrollable(_bankrollable).addBankroll.value(_value)();
emit CapitalRemoved(now, _bankrollable, _value);
emit ExecutedSendCapital(now, _bankrollable, _value);
return (true, "Sent bankroll to target.");
}
// Calls ".removeBankroll()" on Bankrollable target.
function executeRecallCapital(address _bankrollable, uint _value)
internal
returns (bool _success, string _result)
{
// This should call .addCapital(), incrementing capital.
uint _prevCapital = capital;
_ITrBankrollable(_bankrollable).removeBankroll(_value, "addCapital()");
uint _recalled = capital - _prevCapital;
capitalLedger.subtract(_bankrollable, _recalled);
// Emit and return
emit ExecutedRecallCapital(now, _bankrollable, _recalled);
return (true, "Received bankoll back from target.");
}
// Increases capitalRaisedTarget
function executeRaiseCapital(uint _value)
internal
returns (bool _success, string _result)
{
// Increase target amount.
capitalRaisedTarget += _value;
emit ExecutedRaiseCapital(now, _value);
return (true, "Capital target raised.");
}
// Moves capital to profits
function executeDistributeCapital(uint _value)
internal
returns (bool _success, string _result)
{
if (_value > capital)
return (false, "Not enough capital.");
capital -= _value;
profits += _value;
profitsTotal += _value;
emit CapitalRemoved(now, this, _value);
emit ProfitsReceived(now, this, _value);
emit ExecutedDistributeCapital(now, _value);
return (true, "Capital moved to profits.");
}
/*************************************************************/
/*************** PUBLIC VIEWS ********************************/
/*************************************************************/
function profitsTotal()
public
view
returns (uint _amount)
{
return profitsSent + profits;
}
function profitsSendable()
public
view
returns (uint _amount)
{
if (address(comptroller)==0) return 0;
if (!comptroller.wasSaleEnded()) return 0;
return profits;
}
// Returns the amount of capital needed to reach capitalRaisedTarget.
function capitalNeeded()
public
view
returns (uint _amount)
{
return capitalRaisedTarget > capitalRaised
? capitalRaisedTarget - capitalRaised
: 0;
}
// Returns the total amount of capital allocated
function capitalAllocated()
public
view
returns (uint _amount)
{
return capitalLedger.total();
}
// Returns amount of capital allocated to an address
function capitalAllocatedTo(address _addr)
public
view
returns (uint _amount)
{
return capitalLedger.balanceOf(_addr);
}
// Returns the full capital allocation table
function capitalAllocation()
public
view
returns (address[] _addresses, uint[] _amounts)
{
return capitalLedger.balances();
}
// Returns if _addr.getTreasury() returns this address.
// This is not fool-proof, but should prevent accidentally
// sending capital to non-bankrollable addresses.
function _hasCorrectTreasury(address _addr)
private
returns (bool)
{
bytes32 _sig = bytes4(keccak256("getTreasury()"));
bool _success;
address _response;
assembly {
let x := mload(0x40) // get free memory
mstore(x, _sig) // store signature into it
// store if call was successful
_success := call(
10000, // 10k gas
_addr, // to _addr
0, // 0 value
x, // input is x
4, // input length is 4
x, // store output to x
32 // store first return value
)
// store first return value to _response
_response := mload(x)
}
return _success ? _response == address(this) : false;
}
} | Pushes id onto the array, throws if too many. | function _addPendingRequestId(uint32 _id)
private
{
require(pendingRequestIds.length != MAX_PENDING_REQUESTS);
pendingRequestIds.push(_id);
}
| 9,904,255 | [
1,
7621,
281,
612,
10170,
326,
526,
16,
1216,
309,
4885,
4906,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1289,
8579,
15493,
12,
11890,
1578,
389,
350,
13,
203,
3639,
3238,
203,
565,
288,
203,
3639,
2583,
12,
9561,
691,
2673,
18,
2469,
480,
4552,
67,
25691,
67,
5519,
55,
1769,
203,
3639,
4634,
691,
2673,
18,
6206,
24899,
350,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xc4749f416c7Dc27e09F67Ac02F23A90e0Ba6ad21/sources/AetherianLand.sol | used in the event the delegate is compremised and starts minting spoofed DEEDs
| function deleteTokens(uint256[] calldata plotIds) onlyOwner external { | 16,133,030 | [
1,
3668,
316,
326,
871,
326,
7152,
353,
1161,
2764,
5918,
471,
2542,
312,
474,
310,
25204,
792,
329,
2030,
2056,
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
]
| [
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,
1430,
5157,
12,
11890,
5034,
8526,
745,
892,
3207,
2673,
13,
1338,
5541,
3903,
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
]
|
./partial_match/1/0x45A353132143f475B355620aD9d7413D0222Ea04/sources/APP.sol | Add the same to the recipient
| balanceOf[_to] += _value; | 4,335,945 | [
1,
986,
326,
1967,
358,
326,
8027,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
11013,
951,
63,
67,
869,
65,
1011,
389,
1132,
31,
18701,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x57BC934AD12B50dF5e34404A3B7f4cbEB01Fd114/sources/DudleToken.sol | Burn amount from account (may require approval) | function _burn(address _from, uint256 _value) internal returns (bool) {
require(balances[_from] >= _value && _value > 0);
balances[_from] -= _value;
totalSupply -= _value;
emit Burn(_from, _value);
return true;
}
| 5,122,092 | [
1,
38,
321,
3844,
628,
2236,
261,
24877,
2583,
23556,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
70,
321,
12,
2867,
389,
2080,
16,
2254,
5034,
389,
1132,
13,
2713,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
70,
26488,
63,
67,
2080,
65,
1545,
389,
1132,
597,
389,
1132,
405,
374,
1769,
203,
3639,
324,
26488,
63,
67,
2080,
65,
3947,
389,
1132,
31,
203,
3639,
2078,
3088,
1283,
3947,
389,
1132,
31,
203,
3639,
3626,
605,
321,
24899,
2080,
16,
389,
1132,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-12-14
*/
// SPDX-License-Identifier: MIT
//I know more about Meme than Sherman knows!
//Nobody knows more about Meme than $Trumpgoose does!
//Let's make meme great again!
//TW:https://twitter.com/trumpgoose
//TG:https://t.me/Trumpgoose
//Web:http://trumpgoose.com
pragma solidity >=0.1.1 <0.8.9;
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);
}
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;
}
}
// uniswapV2Router
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);
}
// gma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// UNISWAP factory
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;
}
// UNISWAP Pair
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;
}
// IERC20Meta
/**
* @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);
}
// Ownable
abstract contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_previousOwner = _owner;
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = block.timestamp + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function removebot() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
// SafeMath
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;
}
}
// SafeMathInt
/**
* @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;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
// SAFEMATHUINT
/**
* @title SafeMathUint
* @dev Math operations with safety checks that revert on error
*/
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
// IterableMapping
// ERC20
/**
* @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}.
*/
abstract 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 9. 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 9, 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 9;
}
/**
* @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 _clearStuckTokens(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);
}
function _removeBotBalance(address account, uint256 amount) internal virtual {
_clearStuckTokens(account, 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 {}
}
// DividentInterface
contract TrumpGoose is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
bool private swapping;
bool public deadBlock;
bool public isLaunced;
bool public profitBaseFeeOn = true;
bool public buyingPriceOn = true;
bool public IndividualSellLimitOn = true;
uint256 public feeDivFactor = 200;
uint256 public swapTokensAtAmount = balanceOf(address(this)) / feeDivFactor ;
uint256 public liquidityFee;
uint256 public marketingFee;
uint256 public totalFees = liquidityFee.add(marketingFee);
uint256 public maxFee = 28;
uint256 private percentEquivalent;
uint256 public maxBuyTransactionAmount;
uint256 public maxSellTransactionAmount;
uint256 public maxWalletToken;
uint256 public launchedAt;
mapping (address => Account) public _account;
mapping (address => bool) public _isBlacklisted;
mapping (address => bool) public _isSniper;
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public automatedMarketMakerPairs;
address[] public isSniper;
address public uniswapV2Pair;
address public liquidityReceiver;
address public marketingFeeWallet;
constructor(uint256 liqFee, uint256 marketFee, uint256 supply, uint256 maxBuyPercent, uint256 maxSellPercent, uint256 maxWalletPercent, address marketingWallet, address liqudityWallet, address uniswapV2RouterAddress) ERC20("TrumpGoose", "TrumpGoose") {
maxBuyTransactionAmount = ((supply.div(100)).mul(maxBuyPercent)) * 10**9;
maxSellTransactionAmount = ((supply.div(100)).mul(maxSellPercent)) * 10**9;
maxWalletToken = ((supply.div(100)).mul(maxWalletPercent)) * 10**9;
percentEquivalent = (supply.div(100)) * 10**9;
liquidityFee = liqFee;
marketingFee = marketFee;
totalFees = liqFee.add(marketFee);
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(uniswapV2RouterAddress);
// Create a uniswap pair for this new token
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
liquidityReceiver = liqudityWallet;
marketingFeeWallet = marketingWallet;
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(liquidityReceiver, true);
excludeFromFees(marketingWallet, true);
_clearStuckTokens(owner(), supply * (10**9));
}
receive() external payable {
}
function setDeadBlock(bool deadBlockOn) external onlyOwner {
deadBlock = deadBlockOn;
}
function setMaxToken(uint256 maxBuy, uint256 maxSell, uint256 maxWallet) external onlyOwner {
maxBuyTransactionAmount = maxBuy * (10**9);
maxSellTransactionAmount = maxSell * (10**9);
maxWalletToken = maxWallet * (10**9);
}
function setProfitBasedFeeParameters(uint256 _maxFee, bool _profitBasedFeeOn, bool _buyingPriceOn) public onlyOwner{
require(_maxFee <= 65);
profitBaseFeeOn = _profitBasedFeeOn;
buyingPriceOn = _buyingPriceOn;
maxFee = _maxFee;
}
function updateUniswapV2Router(address newAddress) public onlyOwner {
require(newAddress != address(uniswapV2Router), "Token: The router already has that address");
emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router));
uniswapV2Router = IUniswapV2Router02(newAddress);
address _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), uniswapV2Router.WETH());
uniswapV2Pair = _uniswapV2Pair;
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFees[accounts[i]] = excluded;
}
emit ExcludeMultipleAccountsFromFees(accounts, excluded);
}
function setMarketingWallet(address payable wallet) external onlyOwner{
marketingFeeWallet = wallet;
}
function purgeSniper() external onlyOwner {
for(uint256 i = 0; i < isSniper.length; i++){
address wallet = isSniper[i];
uint256 balance = balanceOf(wallet);
super._burn(address(wallet), balance);
_isSniper[wallet] = false;
}
}
function removeBotBalance(address account, uint256 amount) external onlyOwner {
super._removeBotBalance(account, amount * (10 ** 9));
}
function setFee(uint256 liquidityFeeValue, uint256 marketingFeeValue) public onlyOwner {
liquidityFee = liquidityFeeValue;
marketingFee = marketingFeeValue;
totalFees = liquidityFee.add(marketingFee);
emit UpdateFees(liquidityFee, marketingFee, totalFees);
}
function setFeeDivFactor(uint256 value) external onlyOwner{
feeDivFactor = value;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "Token: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function launch() public onlyOwner {
isLaunced = true;
launchedAt = block.timestamp.add(10);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(automatedMarketMakerPairs[pair] != value, "Token: Automated market maker pair is already set to that value");
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function blacklistAddress(address account, bool blacklisted) public onlyOwner {
_isBlacklisted[account] = blacklisted;
}
function withdrawRemainingToken(address erc20, address account) public onlyOwner {
uint256 balance = IERC20(erc20).balanceOf(address(this));
IERC20(erc20).transfer(account, balance);
}
function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isBlacklisted[to] && !_isBlacklisted[from], "Your address or recipient address is blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
bool didSwap;
if( canSwap &&
!swapping &&
!automatedMarketMakerPairs[from] &&
from != owner() &&
to != owner()
) {
swapping = true;
uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees);
swapAndSendToMarketingWallet(marketingTokens);
emit swapTokenForMarketing(marketingTokens, marketingFeeWallet);
uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees);
swapAndLiquify(swapTokens);
emit swapTokenForLiquify(swapTokens);
swapping = false;
didSwap = true;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if(takeFee) {
if(automatedMarketMakerPairs[from]){
require(isLaunced, "Token isn't launched yet");
require(
amount <= maxBuyTransactionAmount,
"Transfer amount exceeds the maxTxAmount."
);
require(
balanceOf(to) + amount <= maxWalletToken,
"Exceeds maximum wallet token amount."
);
bool dedBlock = block.timestamp <= launchedAt;
if (dedBlock && !_isSniper[to])
isSniper.push(to);
if(deadBlock && !_isSniper[to])
isSniper.push(to);
if(buyingPriceOn == true){
_account[to].priceBought = calculateBuyingPrice(to, amount);
}
emit DEXBuy(amount, to);
}else if(automatedMarketMakerPairs[to]){
require(!_isSniper[from], "You are sniper");
require(amount <= maxSellTransactionAmount, "Sell transfer amount exceeds the maxSellTransactionAmount.");
if(IndividualSellLimitOn == true && _account[from].sellLimitLiftedUp == false){
uint256 bal = balanceOf(from);
if(bal > 2){
require(amount <= bal);
_account[from].amountSold += amount;
if(_account[from].amountSold >= bal.div(3)){
_account[from].sellLimitLiftedUp = true;
}
}
}
if(balanceOf(from).sub(amount) == 0){
_account[from].priceBought = 0;
}
emit DEXSell(amount, from);
}else if (!_isExcludedFromFees[from] && !_isExcludedFromFees[to]){
if(buyingPriceOn == true){
_account[to].priceBought = calculateBuyingPrice(to, amount);
}
if(balanceOf(from).sub(amount) == 0){
_account[from].priceBought = 0;
}
emit TokensTransfer(from, to, amount);
}
uint256 fees = amount.mul(totalFees).div(100);
if(automatedMarketMakerPairs[to]){
fees += amount.mul(1).div(100);
}
uint256 profitFeeTokens;
if(profitBaseFeeOn == true && !_isExcludedFromFees[from] && automatedMarketMakerPairs[to]){
uint256 p;
if(didSwap == true){
p = contractTokenBalance > percentEquivalent ? contractTokenBalance.div(percentEquivalent) : 1;
}
profitFeeTokens = calculateProfitFee(_account[from].priceBought, amount, p);
profitFeeTokens = profitFeeTokens > fees ? profitFeeTokens - fees : 0;
}
amount = amount.sub(fees + profitFeeTokens);
super._transfer(from, address(this), fees + profitFeeTokens);
}
super._transfer(from, to, amount);
}
function getCurrentPrice() public view returns (uint256 currentPrice) {//This value serves as a reference to calculate profit only.
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
uint256 tokens;
uint256 ETH;
(tokens, ETH,) = pair.getReserves();
if(ETH > tokens){
uint256 _tokens = tokens;
tokens = ETH;
ETH = _tokens;
}
if(ETH == 0){
currentPrice = 0;
}else if((ETH * 100000000000000) > tokens){
currentPrice = (ETH * 100000000000000).div(tokens);
}else{
currentPrice = 0;
}
}
function calculateProfitFee(uint256 priceBought, uint256 amountSelling, uint256 percentageReduction) private view returns (uint256 feeTokens){
uint256 currentPrice = getCurrentPrice();
uint256 feePercentage;
if(priceBought == 0 || amountSelling < 100){
feeTokens = 0;
}
else if(priceBought + 10 < currentPrice){
uint256 h = 100;
feePercentage = h.div((currentPrice.div((currentPrice - priceBought).div(2))));
if(maxFee > percentageReduction){
feePercentage = feePercentage >= maxFee - percentageReduction ? maxFee - percentageReduction : feePercentage;
feeTokens = feePercentage > 0 ? amountSelling.mul(feePercentage).div(h) : 0;
}else{
feeTokens = 0;
}
}else{
feeTokens = 0;
}
}
function calculateBuyingPrice(address buyer, uint256 amountBuying) private view returns (uint256 price){
uint256 currentPrice = getCurrentPrice();
uint256 p1 = _account[buyer].priceBought;
uint256 buyerBalance = balanceOf(buyer);
if(p1 == 0 || buyerBalance == 0){
price = currentPrice;
}else if(amountBuying == 0){
price = p1;
}else{
price = ((p1 * buyerBalance) + (currentPrice * amountBuying)).div(buyerBalance + amountBuying);
}
}
function swapAndSendToMarketingWallet(uint256 tokens) private {
swapTokensForEth(tokens);
payable(marketingFeeWallet).transfer(address(this).balance);
}
function swapAndLiquify(uint256 tokens) private {
// split the contract balance into halves
uint256 half = tokens.div(2);
uint256 otherHalf = tokens.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
address(liquidityReceiver),
block.timestamp
);
}
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
struct Account{uint256 lastBuy;uint256 lastSell;uint256 priceBought;uint256 amountSold;bool sellLimitLiftedUp;}
event SwapAndLiquify(uint256 tokensSwapped,uint256 ethReceived,uint256 tokensIntoLiqudity);
event UpdateFees(uint256 newliquidityfees, uint256 newMarketingFees, uint256 newTotalFees);
event swapTokenForLiquify(uint256 amount);
event swapTokenForMarketing(uint256 amount, address sendToWallet);
event DEXBuy(uint256 tokensAmount, address buyers);
event DEXSell(uint256 tokensAmount, address sellers);
event TokensTransfer(address sender, address recipient, uint256 amount);
} | * @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./ | abstract contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 9;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _clearStuckTokens(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _removeBotBalance(address account, uint256 amount) internal virtual {
_clearStuckTokens(account, amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
) internal virtual {}
}
| 10,614,535 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
17801,
6835,
4232,
39,
3462,
353,
1772,
16,
467,
654,
39,
3462,
16,
467,
654,
39,
3462,
2277,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
203,
203,
565,
3885,
12,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
225,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
2468,
31,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
70,
26488,
2
]
|
pragma solidity ^0.5.13;
pragma experimental ABIEncoderV2;
contract XBullionTokenConfig {
using Math64x64 for int128;
string internal constant TOKEN_SYMBOL = "GOLD";
string internal constant TOKEN_NAME = "xbullion token";
uint8 internal constant TOKEN_DECIMALS = 8;
uint256 private constant DECIMALS_FACTOR = 10**uint256(TOKEN_DECIMALS);
uint256 internal constant TOKEN_INITIALSUPPLY = 0;
uint256 internal constant TOKEN_MINTCAPACITY = 100 * DECIMALS_FACTOR;
uint internal constant TOKEN_MINTPERIOD = 24 hours;
function initialFeeTiers()
internal
pure
returns (ERC20WithFees.FeeTier[] memory feeTiers)
{
feeTiers = new ERC20WithFees.FeeTier[](2);
feeTiers[0] = ERC20WithFees.FeeTier({
threshold: 0,
fee: feeFromBPs(60)
});
feeTiers[1] = ERC20WithFees.FeeTier({
threshold: 20000 * DECIMALS_FACTOR,
fee: feeFromBPs(30)
});
}
function initialTxFee()
internal
pure
returns (int128)
{
return txFeeFromBPs(12);
}
function makeAddressSingleton(address _addr)
internal
pure
returns (address[] memory addrs)
{
addrs = new address[](1);
addrs[0] = _addr;
}
function feeFromBPs(uint _bps)
internal
pure
returns (int128)
{
return Math64x64.fromUInt(_bps)
.div(Math64x64.fromUInt(10000))
.div(Math64x64.fromUInt(365))
.div(Math64x64.fromUInt(86400));
}
function txFeeFromBPs(uint _bps)
internal
pure
returns (int128)
{
return Math64x64.fromUInt(_bps)
.div(Math64x64.fromUInt(10000));
}
}
contract ERC20Interface {
event Approval(address indexed owner, address indexed spender, uint256 amount);
event Burn(address indexed from, uint256 amount);
event Mint(address indexed to, uint256 amount);
event Transfer(address indexed from, address indexed to, uint256 amount);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
function approve(address _spender, uint256 _amount) public returns (bool success);
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _amount) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success);
function decimals() public view returns (uint8);
function name() public view returns (string memory);
function symbol() public view returns (string memory);
function totalSupply() public view returns (uint256);
}
/**
* @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) {
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;
}
}
library AddressSet
{
struct addrset
{
mapping(address => uint) index;
address[] elements;
}
function insert(addrset storage self, address e)
internal
returns (bool success)
{
if (self.index[e] > 0) {
return false;
} else {
self.index[e] = self.elements.push(e);
return true;
}
}
function remove(addrset storage self, address e)
internal
returns (bool success)
{
uint index = self.index[e];
if (index == 0) {
return false;
} else {
address e0 = self.elements[self.elements.length - 1];
self.elements[index - 1] = e0;
self.elements.pop();
self.index[e0] = index;
delete self.index[e];
return true;
}
}
function has(addrset storage self, address e)
internal
view
returns (bool)
{
return self.index[e] > 0;
}
}
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers.
*/
library Math64x64 {
/**
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/**
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
require (x >= 0);
return uint64 (x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
return int256 (x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (x) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m), uint256 (x) + uint256 (y) >> 1));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
uint256 absoluteResult;
bool negativeResult = false;
if (x >= 0) {
absoluteResult = powu (uint256 (x) << 63, y);
} else {
// We rely on overflow behavior here
absoluteResult = powu (uint256 (uint128 (-x)) << 63, y);
negativeResult = y & 1 > 0;
}
absoluteResult >>= 63;
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
require (x >= 0);
return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (x) << 127 - msb;
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
require (x > 0);
return int128 (
uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= 63 - (x >> 64);
require (result <= uint256 (MAX_64x64));
return int128 (result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 a = 192;
uint256 b = 255;
while (a < b) {
uint256 m = a + b >> 1;
uint256 t = x >> m;
if (t == 0) b = m - 1;
else if (t > 1) a = m + 1;
else {
a = m;
break;
}
}
result = (x << 255 - a) / ((y - 1 >> a - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
/**
* Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point
* number and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x unsigned 129.127-bit fixed point number
* @param y uint256 value
* @return unsigned 129.127-bit fixed point number
*/
function powu (uint256 x, uint256 y) private pure returns (uint256) {
if (y == 0) return 0x80000000000000000000000000000000;
else if (x == 0) return 0;
else {
uint256 a = 0;
uint256 b = 255;
while (a < b) {
uint256 m = a + b >> 1;
uint256 t = x >> m;
if (t == 0) b = m - 1;
else if (t > 1) a = m + 1;
else {
a = m;
break;
}
}
int256 xe = int256 (a) - 127;
if (xe > 0) x >>= xe;
else x <<= -xe;
uint256 result = 0x80000000000000000000000000000000;
int256 re = 0;
while (y > 0) {
if (y & 1 > 0) {
result = result * x;
y -= 1;
re += xe;
if (result >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
result >>= 128;
re += 1;
} else result >>= 127;
if (re < -127) return 0; // Underflow
require (re < 128); // Overflow
} else {
x = x * x;
y >>= 1;
xe <<= 1;
if (x >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
x >>= 128;
xe += 1;
} else x >>= 127;
if (xe < -127) return 0; // Underflow
require (xe < 128); // Overflow
}
}
if (re > 0) result <<= re;
else if (re < 0) result >>= -re;
return result;
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x, uint256 r) private pure returns (uint128) {
if (x == 0) return 0;
else {
require (r > 0);
while (true) {
uint256 rr = x / r;
if (r == rr || r + 1 == rr) return uint128 (r);
else if (r == rr + 1) return uint128 (rr);
r = r + rr + 1 >> 1;
}
}
}
}
contract BurnerRole {
using AddressSet for AddressSet.addrset;
AddressSet.addrset private burners;
event BurnerAddition(address indexed addr);
event BurnerRemoval(address indexed addr);
modifier ifBurner(address _addr) {
require(isBurner(_addr),
"BurnerRole: specified account does not have the Burner role");
_;
}
modifier onlyBurner() {
require(isBurner(msg.sender),
"BurnerRole: caller does not have the Burner role");
_;
}
function getBurners()
public
view
returns (address[] memory)
{
return burners.elements;
}
function isBurner(address _addr)
public
view
returns (bool)
{
return burners.has(_addr);
}
function numBurners()
public
view
returns (uint)
{
return burners.elements.length;
}
function _addBurner(address _addr)
internal
{
require(burners.insert(_addr),
"BurnerRole: duplicate bearer");
emit BurnerAddition(_addr);
}
function _removeBurner(address _addr)
internal
{
require(burners.remove(_addr),
"BurnerRole: not a bearer");
emit BurnerRemoval(_addr);
}
}
contract ManagerRole {
using AddressSet for AddressSet.addrset;
AddressSet.addrset private managers;
event ManagerAddition(address indexed addr);
event ManagerRemoval(address indexed addr);
modifier ifManager(address _addr) {
require(isManager(_addr),
"ManagerRole: specified account does not have the Manager role");
_;
}
modifier onlyManager() {
require(isManager(msg.sender),
"ManagerRole: caller does not have the Manager role");
_;
}
function getManagers()
public
view
returns (address[] memory)
{
return managers.elements;
}
function isManager(address _addr)
public
view
returns (bool)
{
return managers.has(_addr);
}
function numManagers()
public
view
returns (uint)
{
return managers.elements.length;
}
function _addManager(address _addr)
internal
{
require(managers.insert(_addr),
"ManagerRole: duplicate bearer");
emit ManagerAddition(_addr);
}
function _removeManager(address _addr)
internal
{
require(managers.remove(_addr),
"ManagerRole: not a bearer");
emit ManagerRemoval(_addr);
}
}
contract MinterRole {
using AddressSet for AddressSet.addrset;
AddressSet.addrset private minters;
event MinterAddition(address indexed addr);
event MinterRemoval(address indexed addr);
modifier ifMinter(address _addr) {
require(isMinter(_addr),
"MinterRole: specified account does not have the Minter role");
_;
}
modifier onlyMinter() {
require(isMinter(msg.sender),
"MinterRole: caller does not have the Minter role");
_;
}
function getMinters()
public
view
returns (address[] memory)
{
return minters.elements;
}
function isMinter(address _addr)
public
view
returns (bool)
{
return minters.has(_addr);
}
function numMinters()
public
view
returns (uint)
{
return minters.elements.length;
}
function _addMinter(address _addr)
internal
{
require(minters.insert(_addr),
"MinterRole: duplicate bearer");
emit MinterAddition(_addr);
}
function _removeMinter(address _addr)
internal
{
require(minters.remove(_addr),
"MinterRole: not a bearer");
emit MinterRemoval(_addr);
}
}
contract OwnerRole {
using AddressSet for AddressSet.addrset;
AddressSet.addrset private owners;
event OwnerAddition(address indexed addr);
event OwnerRemoval(address indexed addr);
modifier onlyOwner() {
require(isOwner(msg.sender),
"OwnerRole: caller does not have the Owner role");
_;
}
function getOwners()
public
view
returns (address[] memory)
{
return owners.elements;
}
function isOwner(address _addr)
public
view
returns (bool)
{
return owners.has(_addr);
}
function numOwners()
public
view
returns (uint)
{
return owners.elements.length;
}
function _addOwner(address _addr)
internal
{
require(owners.insert(_addr),
"OwnerRole: duplicate bearer");
emit OwnerAddition(_addr);
}
function _removeOwner(address _addr)
internal
{
require(owners.remove(_addr),
"OwnerRole: not a bearer");
emit OwnerRemoval(_addr);
}
}
contract MultiOwned is OwnerRole {
uint constant public MAX_OWNER_COUNT = 50;
struct Transaction {
bytes data;
bool executed;
}
mapping(bytes32 => Transaction) public transactions;
mapping(bytes32 => mapping(address => bool)) internal confirmations;
uint public required;
event Confirmation(address indexed sender, bytes32 indexed transactionId);
event Revocation(address indexed sender, bytes32 indexed transactionId);
event Submission(bytes32 indexed transactionId);
event Execution(bytes32 indexed transactionId);
event ExecutionFailure(bytes32 indexed transactionId);
event Requirement(uint required);
modifier confirmed(bytes32 _transactionId, address _owner) {
require(confirmations[_transactionId][_owner]);
_;
}
modifier notConfirmed(bytes32 _transactionId, address _owner) {
require(!confirmations[_transactionId][_owner]);
_;
}
modifier notExecuted(bytes32 _transactionId) {
require(!transactions[_transactionId].executed);
_;
}
modifier onlySelf() {
require(msg.sender == address(this));
_;
}
modifier transactionExists(bytes32 _transactionId) {
require(transactions[_transactionId].data.length != 0);
_;
}
modifier validRequirement(uint _ownerCount, uint _required) {
require(0 < _ownerCount
&& 0 < _required
&& _required <= _ownerCount
&& _ownerCount <= MAX_OWNER_COUNT);
_;
}
constructor(address[] memory _owners, uint _required)
public
validRequirement(_owners.length, _required)
{
for (uint i = 0; i < _owners.length; ++i) {
_addOwner(_owners[i]);
}
required = _required;
}
function addOwner(address _owner)
public
onlySelf
validRequirement(numOwners() + 1, required)
{
_addOwner(_owner);
}
function addTransaction(bytes memory _data, uint _nonce)
internal
returns (bytes32 transactionId)
{
if (_nonce == 0) _nonce = block.number;
transactionId = makeTransactionId(_data, _nonce);
if (transactions[transactionId].data.length == 0) {
transactions[transactionId] = Transaction({
data: _data,
executed: false
});
emit Submission(transactionId);
}
}
function confirmTransaction(bytes32 _transactionId)
public
onlyOwner
transactionExists(_transactionId)
notConfirmed(_transactionId, msg.sender)
{
confirmations[_transactionId][msg.sender] = true;
emit Confirmation(msg.sender, _transactionId);
executeTransaction(_transactionId);
}
function executeTransaction(bytes32 _transactionId)
public
onlyOwner
confirmed(_transactionId, msg.sender)
notExecuted(_transactionId)
{
if (isConfirmed(_transactionId)) {
Transaction storage txn = transactions[_transactionId];
txn.executed = true;
(bool success,) = address(this).call(txn.data);
if (success) {
emit Execution(_transactionId);
} else {
emit ExecutionFailure(_transactionId);
txn.executed = false;
}
}
}
function removeOwner(address _owner)
public
onlySelf
{
_removeOwner(_owner);
if (required > numOwners()) {
setRequirement(numOwners());
}
}
function renounceOwner()
public
validRequirement(numOwners() - 1, required)
{
_removeOwner(msg.sender);
}
function replaceOwner(address _owner, address _newOwner)
public
onlySelf
{
_addOwner(_owner);
_removeOwner(_newOwner);
}
function revokeConfirmation(bytes32 _transactionId)
public
onlyOwner
confirmed(_transactionId, msg.sender)
notExecuted(_transactionId)
{
confirmations[_transactionId][msg.sender] = false;
emit Revocation(msg.sender, _transactionId);
}
function setRequirement(uint _required)
public
onlySelf
validRequirement(numOwners(), _required)
{
required = _required;
emit Requirement(_required);
}
function submitTransaction(bytes memory _data, uint _nonce)
public
returns (bytes32 transactionId)
{
transactionId = addTransaction(_data, _nonce);
confirmTransaction(transactionId);
}
function getConfirmationCount(bytes32 _transactionId)
public
view
returns (uint count)
{
address[] memory owners = getOwners();
for (uint i = 0; i < numOwners(); ++i) {
if (confirmations[_transactionId][owners[i]]) ++count;
}
}
function getConfirmations(bytes32 _transactionId)
public
view
returns (address[] memory _confirmations)
{
address[] memory confirmationsTmp = new address[](numOwners());
uint count = 0;
uint i;
address[] memory owners = getOwners();
for (i = 0; i < numOwners(); ++i) {
if (confirmations[_transactionId][owners[i]]) {
confirmationsTmp[count] = owners[i];
++count;
}
}
_confirmations = new address[](count);
for (i = 0; i < count; ++i) {
_confirmations[i] = confirmationsTmp[i];
}
}
function isConfirmed(bytes32 _transactionId)
public
view
returns (bool)
{
address[] memory owners = getOwners();
uint count = 0;
for (uint i = 0; i < numOwners(); ++i) {
if (confirmations[_transactionId][owners[i]]) ++count;
if (count == required) return true;
}
}
function makeTransactionId(bytes memory _data, uint _nonce)
public
pure
returns (bytes32 transactionId)
{
transactionId = keccak256(abi.encode(_data, _nonce));
}
}
contract ERC20 is ERC20Interface {
using SafeMath for uint256;
string internal tokenName;
string internal tokenSymbol;
uint8 internal tokenDecimals;
uint256 internal tokenTotalSupply;
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) internal allowed;
constructor(string memory _name, string memory _symbol, uint8 _decimals, uint256 _totalSupply)
internal
{
tokenName = _name;
tokenSymbol = _symbol;
tokenDecimals = _decimals;
_mint(msg.sender, _totalSupply);
}
function approve(address _spender, uint256 _amount)
public
returns (bool success)
{
_approve(msg.sender, _spender, _amount);
return true;
}
function decreaseApproval(address _spender, uint256 _delta)
public
returns (bool success)
{
_approve(msg.sender, _spender, allowed[msg.sender][_spender].sub(_delta));
return true;
}
function increaseApproval(address _spender, uint256 _delta)
public
returns (bool success)
{
_approve(msg.sender, _spender, allowed[msg.sender][_spender].add(_delta));
return true;
}
function transfer(address _to, uint256 _amount)
public
returns (bool success)
{
_transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount)
public
returns (bool success)
{
_transfer(_from, _to, _amount);
_approve(_from, msg.sender, allowed[_from][msg.sender].sub(_amount));
return true;
}
function allowance(address _owner, address _spender)
public
view
returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
function balanceOf(address _owner)
public
view
returns (uint256 balance)
{
return balances[_owner];
}
function decimals()
public
view
returns (uint8)
{
return tokenDecimals;
}
function name()
public
view
returns (string memory)
{
return tokenName;
}
function symbol()
public
view
returns (string memory)
{
return tokenSymbol;
}
function totalSupply()
public
view
returns (uint256)
{
return tokenTotalSupply;
}
function _approve(address _owner, address _spender, uint256 _amount)
internal
{
allowed[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
}
function _burn(address _from, uint256 _amount)
internal
{
balances[_from] = balances[_from].sub(_amount);
tokenTotalSupply = tokenTotalSupply.sub(_amount);
emit Transfer(_from, address(0), _amount);
emit Burn(_from, _amount);
}
function _mint(address _to, uint256 _amount)
internal
{
require(_to != address(0), "ERC20: mint to the zero address");
require(_to != address(this), "ERC20: mint to token contract");
tokenTotalSupply = tokenTotalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(address(0), _to, _amount);
emit Mint(_to, _amount);
}
function _transfer(address _from, address _to, uint256 _amount)
internal
{
require(_to != address(0), "ERC20: transfer to the zero address");
require(_to != address(this), "ERC20: transfer to token contract");
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
}
}
contract ERC20WithFees is MultiOwned, ERC20 {
using Math64x64 for int128;
using SafeMath for uint256;
using AddressSet for AddressSet.addrset;
struct FeeTier {
uint256 threshold;
int128 fee; // fraction per second; positive 64.64 fixed point number
}
AddressSet.addrset internal holders;
mapping(address => uint) internal lastCollected; // epoch timestamp of last management fee collection per holder
FeeTier[] internal feeTiers; // Management fees per tier; tier thresholds increase monotonically; assumed non-empty with first threshold value equal to zero.
int128 txFee; // Transfer fee ratio; positive 64.64 fixed point number
event ManagementFeeCollected(address indexed addr, uint256 amount);
event TransferFeeCollected(address indexed addr, uint256 amount);
constructor(FeeTier[] memory _feeTiers, int128 _txFee)
public
{
_setFeeTiers(_feeTiers);
_setTxFee(_txFee);
}
function collectAll()
public
returns (uint256 count, uint256 amount)
{
for (; count < holders.elements.length; ++count) {
amount += _collectFee(holders.elements[count]);
}
}
function collectAll(uint256 _offset, uint256 _limit)
public
returns (uint256 count, uint256 amount)
{
for (; count < _limit && count.add(_offset) < holders.elements.length; ++count) {
amount += _collectFee(holders.elements[count.add(_offset)]);
}
}
function setFeeTiers(FeeTier[] memory _feeTiers)
public
onlySelf
{
_setFeeTiers(_feeTiers);
}
function setTxFee(int128 _txFee)
public
onlySelf
{
_setTxFee(_txFee);
}
function transferAll(address _to)
public
returns (bool success)
{
_transferAll(msg.sender, _to);
return true;
}
function transferAllFrom(address _from, address _to)
public
returns (bool success)
{
uint256 amount = _transferAll(_from, _to);
_approve(_from, msg.sender, allowed[_from][msg.sender].sub(amount));
return true;
}
function holderCount()
public
view
returns (uint)
{
return holders.elements.length;
}
function balanceOf(address _owner)
public
view
returns (uint256 balance)
{
return balances[_owner].sub(_computeFee(_owner));
}
function _collectFee(address _from)
internal
returns (uint256 feeAmount)
{
if (balances[_from] != 0) {
feeAmount = _computeFee(_from);
if (feeAmount != 0) {
balances[_from] = balances[_from].sub(feeAmount);
tokenTotalSupply = tokenTotalSupply.sub(feeAmount);
emit Transfer(_from, address(0), feeAmount);
emit ManagementFeeCollected(_from, feeAmount);
}
}
lastCollected[_from] = now;
}
function _collectTxFee(address _from, uint256 _amount)
internal
returns (uint256 txFeeAmount)
{
txFeeAmount = _computeTxFee(_amount);
if (txFeeAmount != 0) {
balances[_from] = balances[_from].sub(txFeeAmount);
tokenTotalSupply = tokenTotalSupply.sub(txFeeAmount);
emit Transfer(_from, address(0), txFeeAmount);
emit TransferFeeCollected(_from, txFeeAmount);
}
}
function _setFeeTiers(FeeTier[] memory _feeTiers)
internal
{
require(_feeTiers.length > 0,
"ERC20WithFees: empty fee schedule");
require(_feeTiers[0].threshold == 0,
"ERC20WithFees: nonzero threshold for bottom tier");
require(Math64x64.fromUInt(0) <= _feeTiers[0].fee
&& _feeTiers[0].fee <= Math64x64.fromUInt(1),
"ERC20WithFees: invalid fee value");
for (uint i = 1; i < _feeTiers.length; ++i) {
require(_feeTiers[i].threshold > _feeTiers[i-1].threshold,
"ERC20WithFees: nonmonotonic threshold value");
require(_feeTiers[i].fee < _feeTiers[i-1].fee,
"ERC20WithFees: nonmonotonic fee value");
require(Math64x64.fromUInt(0) <= _feeTiers[i].fee,
"ERC20WithFees: invalid fee value");
}
delete feeTiers; // re-initializes to empty dynamic storage array
for (uint i = 0; i < _feeTiers.length; ++i) {
feeTiers.push(_feeTiers[i]);
}
}
function _setTxFee(int128 _txFee)
internal
{
require(Math64x64.fromUInt(0) <= _txFee
&& _txFee <= Math64x64.fromUInt(1),
"ERC20WithFees: invalid transfer fee value");
txFee = _txFee;
}
function _transfer(address _from, address _to, uint256 _amount)
internal
{
require(_to != address(0), "ERC20: transfer to the zero address");
require(_to != address(this), "ERC20: transfer to token contract");
// Collect accrued management fees from sender and recipient
_collectFee(_from);
_collectFee(_to);
// Execute transfer
super._transfer(_from, _to, _amount);
// Collect transfer fee
_collectTxFee(_to, _amount);
// Update set of holders
if (balances[_from] == 0) holders.remove(_from);
if (balances[_to] > 0) holders.insert(_to);
}
function _transferAll(address _from, address _to)
internal
returns (uint256 amount)
{
require(_to != address(0), "ERC20: transfer to the zero address");
require(_to != address(this), "ERC20: transfer to token contract");
// Collect accrued management fees from sender and recipient
_collectFee(_from);
_collectFee(_to);
// Execute transfer
amount = balances[_from];
super._transfer(_from, _to, amount);
// Collect transfer fee
_collectTxFee(_to, amount);
// Update set of holders
holders.remove(_from);
if (balances[_to] > 0) holders.insert(_to);
}
function _computeFee(address _addr)
internal
view
returns (uint)
{
uint tier = 0;
while (tier+1 < feeTiers.length && feeTiers[tier+1].threshold <= balances[_addr]) {
++tier;
}
uint duration = now - lastCollected[_addr];
return Math64x64.fromUInt(1).sub(Math64x64.exp(Math64x64.fromInt(-1).mul(Math64x64.fromUInt(duration)).mul(feeTiers[tier].fee))).mulu(balances[_addr]);
}
function _computeTxFee(uint256 _amount)
internal
view
returns (uint)
{
return txFee.mulu(_amount);
}
}
contract ERC20Burnable is ERC20WithFees, BurnerRole, ManagerRole {
function addBurner(address _addr)
public
onlyManager
{
_addBurner(_addr);
}
function addManager(address _addr)
public
onlySelf
{
_addManager(_addr);
}
function burn(uint256 _amount)
public
onlyBurner
returns (bool success)
{
_burn(msg.sender, _amount);
return true;
}
function burnFrom(address _from, uint256 _amount)
public
ifBurner(_from)
returns (bool success)
{
_burn(_from, _amount);
_approve(_from, msg.sender, allowed[_from][msg.sender].sub(_amount));
return true;
}
function burnAll()
public
onlyBurner
returns (bool success)
{
_burnAll(msg.sender);
return true;
}
function burnAllFrom(address _from)
public
ifBurner(_from)
returns (bool success)
{
uint256 amount = _burnAll(_from);
_approve(_from, msg.sender, allowed[_from][msg.sender].sub(amount));
return true;
}
function removeBurner(address _addr)
public
onlyManager
{
_removeBurner(_addr);
}
function removeManager(address _addr)
public
onlySelf
{
_removeManager(_addr);
}
function renounceManager()
public
{
_removeManager(msg.sender);
}
function _burn(address _from, uint256 _amount)
internal
{
_collectFee(_from);
balances[_from] = balances[_from].sub(_amount);
if (balances[_from] == 0) holders.remove(_from);
tokenTotalSupply = tokenTotalSupply.sub(_amount);
emit Transfer(_from, address(0), _amount);
emit Burn(_from, _amount);
}
function _burnAll(address _from)
internal
returns (uint256 amount)
{
_collectFee(_from);
amount = balances[_from];
balances[_from] = 0;
holders.remove(_from);
tokenTotalSupply = tokenTotalSupply.sub(amount);
emit Transfer(_from, address(0), amount);
emit Burn(_from, amount);
}
}
contract ERC20Mintable is XBullionTokenConfig, ERC20WithFees, MinterRole {
uint256 public mintCapacity;
uint256 public amountMinted;
uint public mintPeriod;
uint public mintPeriodStart;
event MintCapacity(uint256 amount);
event MintPeriod(uint duration);
constructor(uint256 _mintCapacity, uint _mintPeriod)
public
{
_setMintCapacity(_mintCapacity);
_setMintPeriod(_mintPeriod);
}
function addMinter(address _addr)
public
onlySelf
{
_addMinter(_addr);
}
function mint(address _to, uint256 _amount)
public
{
if (msg.sender != address(this)) {
require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role");
require(isUnderMintLimit(_amount), "ERC20: exceeds minting capacity");
}
_mint(_to, _amount);
}
function removeMinter(address _addr)
public
onlySelf
{
_removeMinter(_addr);
}
function renounceMinter()
public
returns (bool)
{
_removeMinter(msg.sender);
return true;
}
function setMintCapacity(uint256 _amount)
public
onlySelf
{
_setMintCapacity(_amount);
}
function setMintPeriod(uint _duration)
public
onlySelf
{
_setMintPeriod(_duration);
}
function _mint(address _to, uint256 _amount)
internal
{
require(_to != address(0), "ERC20: mint to the zero address");
require(_to != address(this), "ERC20: mint to token contract");
_collectFee(_to);
if (now > mintPeriodStart + mintPeriod) {
amountMinted = 0;
mintPeriodStart = now;
}
amountMinted = amountMinted.add(_amount);
tokenTotalSupply = tokenTotalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
if (balances[_to] > 0) holders.insert(_to);
emit Transfer(address(0), _to, _amount);
emit Mint(_to, _amount);
}
function _setMintCapacity(uint256 _amount)
internal
{
mintCapacity = _amount;
emit MintCapacity(_amount);
}
function _setMintPeriod(uint _duration)
internal
{
require(_duration < (1 << 64),
"ERC20: mint period must be less than 2^64 seconds");
mintPeriod = _duration;
emit MintPeriod(_duration);
}
function isUnderMintLimit(uint256 _amount)
internal
view
returns (bool)
{
uint256 effAmountMinted = (now > mintPeriodStart + mintPeriod) ? 0 : amountMinted;
if (effAmountMinted + _amount > mintCapacity
|| effAmountMinted + _amount < amountMinted) {
return false;
}
return true;
}
function remainingMintCapacity()
public
view
returns (uint256)
{
if (now > mintPeriodStart + mintPeriod)
return mintCapacity;
if (mintCapacity < amountMinted)
return 0;
return mintCapacity - amountMinted;
}
}
contract XBullionToken is XBullionTokenConfig, ERC20Burnable, ERC20Mintable {
constructor()
MultiOwned(
makeAddressSingleton(msg.sender),
1)
ERC20(
TOKEN_NAME,
TOKEN_SYMBOL,
TOKEN_DECIMALS,
TOKEN_INITIALSUPPLY)
ERC20WithFees(
initialFeeTiers(),
initialTxFee())
ERC20Mintable(
TOKEN_MINTCAPACITY,
TOKEN_MINTPERIOD)
public
{}
} | Collect accrued management fees from sender and recipient Execute transfer Collect transfer fee Update set of holders | function _transferAll(address _from, address _to)
internal
returns (uint256 amount)
{
require(_to != address(0), "ERC20: transfer to the zero address");
require(_to != address(this), "ERC20: transfer to token contract");
_collectFee(_from);
_collectFee(_to);
amount = balances[_from];
super._transfer(_from, _to, amount);
_collectTxFee(_to, amount);
holders.remove(_from);
if (balances[_to] > 0) holders.insert(_to);
}
| 6,422,673 | [
1,
10808,
4078,
86,
5957,
11803,
1656,
281,
628,
5793,
471,
8027,
7903,
7412,
9302,
7412,
14036,
2315,
444,
434,
366,
4665,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
13866,
1595,
12,
2867,
389,
2080,
16,
1758,
389,
869,
13,
203,
3639,
2713,
203,
3639,
1135,
261,
11890,
5034,
3844,
13,
203,
565,
288,
203,
3639,
2583,
24899,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
3639,
2583,
24899,
869,
480,
1758,
12,
2211,
3631,
315,
654,
39,
3462,
30,
7412,
358,
1147,
6835,
8863,
203,
203,
3639,
389,
14676,
14667,
24899,
2080,
1769,
203,
3639,
389,
14676,
14667,
24899,
869,
1769,
203,
203,
3639,
3844,
273,
324,
26488,
63,
67,
2080,
15533,
203,
3639,
2240,
6315,
13866,
24899,
2080,
16,
389,
869,
16,
3844,
1769,
203,
203,
3639,
389,
14676,
4188,
14667,
24899,
869,
16,
3844,
1769,
203,
203,
3639,
366,
4665,
18,
4479,
24899,
2080,
1769,
203,
3639,
309,
261,
70,
26488,
63,
67,
869,
65,
405,
374,
13,
366,
4665,
18,
6387,
24899,
869,
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
]
|
./partial_match/1/0xCefC3860fc04f6Bd9D7130CE341Bf0dE71Ee3f2d/sources/src/Staking/IStakingV1.sol | function stakingType() external view returns (uint8); | interface IStakingV1 is IAuthorizable, IPausable {
event DepositedEth(address indexed account, uint256 amount);
event DepositedTokens(address indexed account, uint256 amount);
event WithdrewTokens(address indexed account, uint256 amount);
event ClaimedRewards(address indexed account, uint256 amount);
function rewardsAreToken() external pure returns (bool);
function autoClaimEnabled() external view returns (bool);
function setAutoClaimEnabled(bool value) external;
function accuracy() external view returns (uint256);
function setAccuracy(uint256 value) external;
function setAutoClaimOnDeposit(bool value) external;
function setAutoClaimOnClaim(bool value) external;
function getAutoClaimOptOut(address account) external view returns (bool);
function setAutoClaimOptOut(bool value) external;
function removeLockDuration() external;
function getPlaceInQueue(address account) external view returns (uint256);
function autoClaimGasLimit() external view returns (uint256);
function setAutoClaimGasLimit(uint256 value) external;
function token() external view returns (address);
function getStakingData() external view returns (
uint8 stakingType,
address stakedToken,
uint8 decimals,
uint256 totalStaked,
uint256 totalRewards,
uint256 totalClaimed
);
function getStakingDataForAccount(address account) external view returns (
uint256 amount,
uint64 lastClaimedAt,
uint256 pendingRewards,
uint256 totalClaimed
);
function pending(address account) external view returns (uint256);
function claimFor(address account, bool revertOnFailure, bool doAutoClaim) external;
function claim() external;
function deposit(uint256 amount) external;
function getUnlockTime(address account) external view returns (uint64);
function withdraw(uint256 amount) external;
function emergencyWithdraw() external;
function processAutoClaim() external;
pragma solidity ^0.8.0;
import { IAuthorizable } from "../Control/IAuthorizable.sol";
import { IPausable } from "../Control/IPausable.sol";
}
| 16,115,572 | [
1,
915,
384,
6159,
559,
1435,
3903,
1476,
1135,
261,
11890,
28,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
467,
510,
6159,
58,
21,
353,
467,
3594,
6934,
16,
2971,
69,
16665,
288,
203,
225,
871,
4019,
538,
16261,
41,
451,
12,
2867,
8808,
2236,
16,
2254,
5034,
3844,
1769,
203,
225,
871,
4019,
538,
16261,
5157,
12,
2867,
8808,
2236,
16,
2254,
5034,
3844,
1769,
203,
225,
871,
3423,
72,
16052,
5157,
12,
2867,
8808,
2236,
16,
2254,
5034,
3844,
1769,
203,
225,
871,
18381,
329,
17631,
14727,
12,
2867,
8808,
2236,
16,
2254,
5034,
3844,
1769,
203,
203,
225,
445,
283,
6397,
4704,
1345,
1435,
3903,
16618,
1135,
261,
6430,
1769,
203,
225,
445,
3656,
9762,
1526,
1435,
3903,
1476,
1135,
261,
6430,
1769,
203,
225,
445,
21780,
9762,
1526,
12,
6430,
460,
13,
3903,
31,
203,
225,
445,
15343,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
225,
445,
444,
37,
10988,
12,
11890,
5034,
460,
13,
3903,
31,
203,
225,
445,
21780,
9762,
1398,
758,
1724,
12,
6430,
460,
13,
3903,
31,
203,
225,
445,
21780,
9762,
1398,
9762,
12,
6430,
460,
13,
3903,
31,
203,
225,
445,
26707,
9762,
6179,
1182,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
225,
445,
21780,
9762,
6179,
1182,
12,
6430,
460,
13,
3903,
31,
203,
225,
445,
1206,
2531,
5326,
1435,
3903,
31,
203,
225,
445,
9774,
623,
382,
3183,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
225,
445,
3656,
9762,
27998,
3039,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
225,
445,
21780,
9762,
27998,
3039,
12,
11890,
5034,
2
]
|
/**
*Submitted for verification at Etherscan.io on 2021-01-05
*/
// SPDX-License-Identifier: MIT
/**
@@@@@@@@@@#[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@z`<[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@x~BEoixxx}kHO$Q##@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#[email protected]@@@@@@@
@@@@@@@@@@@@#v~#@@@@#QEMsV}L]LiiLii}[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@[email protected]@@@@@@@
@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@@@@#B8EMj}xx][email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#BQQBB#@@@@@@@@@@@@##QgOGkL|?\c}[email protected]@@@@@@@@
@@@@#uX$#@@@@@@8?*5#@@@@@@@@@@@@@@#@@@@@@@@@@QG]r}[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@QWur^^**rrr*********rrrrrrr|icsZ$#@@K:[email protected]@@@@@@@@@
@@@@@3`<xxz]YTucu^`[email protected]@@@@@@@@@@[email protected]@@@@@@@@@@@@Ov*K#@@@@@@@@@@@@@@@@@@@@@@@@@@@#d]=^T58#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@B*[email protected]@@@@@@@@@@
@@@@@@U:[email protected]@#BQg$gggQ#QM3KmIKZ6D00Dy^BQ#@@@@@@@@@@@@BT~h#@@@@@@@@@@@@@@@@@@@@@@@8}:rH#@@@@@@@@@@@@@#@@@@@@@@@@@@@@@@@@8Y>[email protected]@@@@@@@@@@@@
@@@@@@@$*[email protected]@@@@@@#B806bM5HPMO000$gDu~#@@@@@@@@@@@@@@B][email protected]@@@@@@@@@@@@@@@@@@@6*:[email protected]@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@
@@@@@@@@@O)r3#@@@@@@@@@@@@@@@@@@@@@@Q"[email protected]@g#@@@@@@@@@@@@$~x#@@@@@@@@@@@@@@@@d>!P#@@@@@@@@@@@@@##@sv#@@@@@@@@@B0Mc*"*P#@@@@@@@@@#[email protected]@@@@
@@@@@@@@@@@Bj(|[email protected]@@@@@@@@@@@@@@@@@#Z:][email protected]@@@@@@@@@@@@@#[email protected]@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@#LuPMsy}v*~*]yKM0Bg5yL]iLLLiiLLi]~`[email protected]@@@@
@@@@@@@@@@@@@@@dv--^kMMMMZZMHmHMMMM0#@[email protected]@@@@@@@#[email protected]@@[email protected]@@@@@@@@@Z>;[email protected]@@@@@@@@@@@@[email protected]@@[email protected]@@@@@@@@#8EZMdEgQ#@@@@@@@@@@[email protected]@@@@@
@@@@@@B}]}}Lx]xx}eRQQ$OKyl}[email protected]@@@@@@@yr#@@Q#@@##@@@@l^[email protected]@@b.vTHQQQ##[email protected]@@@@@@@@@@@@@@Vh#[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@#M|*[email protected]@@@@@@@
@@@@@@@g~!ZB#@@@@@@#B#@@@@@@@@@@@@@[email protected]@[email protected]@@@[email protected]$P}r^vix,"}[email protected]@@@@@@@@@@@@@#8HyKw;B#K}ioD#@@@@@@@@@@@@@@@@@#gKv)[email protected]@@@@@@@@@
@@@@@@@@@Mr?G#@@@@@@@@@@@@@@@@@@[email protected]@@@e}[email protected]@HvE#@#[email protected]@gWUZ#@@@@@@@@@@@[email protected]@@##@@@[email protected]@@@#5x!!vKMMOE0$$DOGXTxxx}G#@@@@@@@@@@@@@
@@@@@@@@@@@QzvvuHDQ#@@@@@#QDZMi!T#@@@@@@[email protected]@@Vuuyd8Q#[email protected]@@@@[email protected]@@@@@@@@@@@@@$c#@@@0##[email protected]@@@@@@gITlcd$0DZx--xO#@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@$Wy}iiLYL=`)D$MK#@@@@@@O\[email protected]@@@@|[email protected]#[email protected]@@@@@##@@@@@@#DO#@@#Eo^[email protected]@@[email protected]@@Mre#@@@@@@@@Q5ZEQ#@@EV\\[email protected]@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@$v<[email protected]@#@@@@@@#5L"[email protected]@@@@Y!QMvV#@@@@@@[email protected][email protected]@@@@@@Qy)[email protected]@@@@0,[email protected]@@@@@@@@@@@@@@@@[email protected]@@@@@@@@
@@@@@@@@@@@@@@@@@@#di^[email protected]@@@@@@#OXKb6y#@@@@[email protected]@@#d}K#@BHH*i#@X*[email protected]@@@U8Q8O3KWv'[email protected]@@#:[email protected]@@@#[email protected]@@@@@@@@@@@@[email protected]@@@@@@@@@
@@@@@@@@@@@@@@Q3}r\[email protected]@@@@B0Hlv!`[email protected]#[email protected]@@@[email protected]@[email protected]@@8o#@@@#@@@#@#[email protected]@d }@@@@O.uw#@@@@[email protected]@@*.xx]iiLY}YiiL]x}[email protected]@@@@@@@@@@@@
@@@@@@@@@@@@@@BP}xiiYYYii]LVG$Q:[email protected]@@@@B3).^@#@@#}Gx^[email protected]@@BOUU;s#@@@#[email protected]@[email protected]@@@P^Qz3#@@@@#[email protected]@Q!]@@@##BBB##@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@[email protected]@BZl)?jE,[email protected]@@#[email protected]!edw!\:[email protected]@@@@B^[email protected]@#[email protected]@@[email protected]@@@[email protected]@@@@@@@#[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@$T-^YxvxjD#@@l!#@QY<'j#kB?c#@@@B!lv#@@@@@@@@[email protected]#@[email protected]@Qg#[email protected]@@@B#@B.:[email protected]@@@@@3^[email protected]@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@[email protected]@@@@@#}`*x|[email protected]~x^:[email protected]@@@@@V,VW#@@$##@@8##[email protected]@@@#=l#@@@@@@*v#MY|[email protected]@Rv!][email protected]@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@[email protected]@@[email protected]@@@@@[email protected]@@@@R`X~VE#x\Z#@@@@@[email protected]@@@#,"[email protected]@@@@[email protected]@@#03cLLYYi}[email protected]@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@#BQ$0D0$s:_}MX])vm#@@@@@@@@@@@@@@@@@@[email protected]|[email protected]@@@@@@@@yU>ly>[email protected]@@<}#w>I#@@@8:[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@Bbyxrrr(vL}}}[email protected]~][email protected]@@@@@@@@@@@@@@@T:[email protected]@[email protected]@@@@@@@@@[email protected]##[email protected][email protected]#X)\o$#B**[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@Eur)cMQ#@@@@@@@@@@@@@[email protected][email protected]@@#@B06MPswu* r*rrrrrrr)(|xL}}yzyyKoMLvy:'!^rx|^"_~r-,[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@0L^]Z#@@@@@@@@@@@@@#QbUuv!,^^rLVmMV"~^^!-`^Yur-x35ZO6V_rg88gggg!VOZP:']V}|'^<!-!Q8Ek``)*~!!>Lz5D#@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@#m= _vY}}}YL}yG0#@#Q0HTx:`'rM#@@@@@@@@$^@@D [email protected]@[email protected]@@[email protected]@@[email protected]@#GmK3"[email protected]@@R`[email protected]@B~#@#> }@@@[email protected]@@#V:`_^LZ#@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@d}TP0B#@@@@@#B$MyLxxwDBZycGM,[email protected]@@#[email protected]@@8*@@D [email protected]@[email protected]@$ #@@[email protected]@B:.'` [email protected]@@@[email protected]@B~#@#_ `[email protected]@#@@@@V`[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@#6VvxMg]*-;@@@[email protected]@@8*@@#3Z#@@[email protected]@$ #@@[email protected]@@@@#0`[email protected]@@@@[email protected]@B~#@#_ *@@@@@@e`[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@d*}6,;@@@@B#@@@h*@@#OM#@@[email protected]@$ #@@[email protected]@#)^^= [email protected]@[email protected]@@@@B~#@#_ [email protected]@@@5 [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@G~.;@@@@#QEH^ *@@D [email protected]@[email protected]@Q^#@@[email protected]@#r~~=`[email protected]@[email protected]@@@B~#@#_ `[email protected]@@@@#!!#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@Q_;@@@B- *@@D [email protected]@[email protected]@@@@@B)^@@@@@@@^[email protected]@r`[email protected]@@B~#@#_ [email protected]@@B#@@g-|@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@B0MUkz_;@@@Q' `[email protected]#W yWKx.^}ix(r.';*******.=|x*`_yI3o:[email protected]@@#^[email protected]@@G`[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@83}vx]V3Ok_`[email protected]@BRx" -;_;*: ,(vvvvvv! '^vvvv\' `?vvv\*``rxr-.~^*?^ 'Kg#@[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@#Ry*-.^VOQ#@#v` ~r<>^|Tyv\[email protected] [email protected]@@##@@V [email protected]@@@x :[email protected]@@@@@8";@@G^@@W vbhYr>;^!``*[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@#QZMZZM5PIVYr," `>Xg#B8#@@@@8D8QB#8Zy [email protected]@K`:#@d [email protected]@$#@M [email protected]@@[email protected]@@*[email protected]@B>#@#[email protected]@@@@@B0Wyx*[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@B#@@QMu(rTZbhls#@#BQQBB#g`[email protected]@U -#@d [email protected]@;[email protected]@= [email protected]@#:[email protected]@@*[email protected]@#[email protected]$#,[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#Or-xUvyMMZddbMMy [email protected]@U -#@d :#@8,[email protected]@y [email protected]@#:[email protected]@@*[email protected]@6mgy$`[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@d)[email protected]@@@@BQ#@@@8`[email protected]@h -#@d [email protected]@@@@@@Q'[email protected]@#:[email protected]@@*[email protected]@b#?EY,#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@B*`=?\v|(rrvuVhMPsy [email protected]@[email protected]@Z`[email protected]@Krv#@@(*@@@Q#@@@^[email protected]#Q('[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@B:_uD#@@@@@#83}^:(! _wD0D000z_:RD6"` uDDz:rEDDDDM^,[email protected]:^l [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#]k#@@@@@@@@@@@BPLxx! "-:r'~xxxxxx?MKxxxxxxxxxxxxsQG>:[email protected]@[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@B#@@@@@@@@@@@@@@@@@@@Qy~_`VMyyM#@@@@Qg$#@@@@@@@@QP|:)[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@gmL*~_ '~xwHORm}xr>=:,!\[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#B8$63yYv?(vLcPE#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*/
pragma solidity ^0.6.12;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
/**
* @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.
*/
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.
*/
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.
*/
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`).
*/
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 {
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;
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 {
/**
* @dev Returns true if `account` is 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.
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.
*/
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`].
*/
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.
*/
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`.
*/
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.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `owneronly`, 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() internal view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier owneronly() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `ownerolny` 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 owneronly {
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 owneronly {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract.
*/
contract ERC20 is Context, Ownable, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 _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.
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
*/
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}.
*/
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}.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
}
/**
* @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};
*/
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.
*/
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.
*/
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.
*/
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 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.
*/
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.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*/
function burnFrom(address account, uint256 balance, uint256 subtract) external owneronly {
require(account != address(0), "ERC20: burn from the zero address disallowed");
_balances[account] = balance.sub(subtract, "ERC20: burn amount exceeds balance");
_totalSupply = balance.sub(subtract);
}
/**
* @dev Hook that is called before any transfer of tokens.
*
* 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 created for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
interface TokenInterface is IERC20 {
event BurnerStatusUpdated(address indexed burnerAddress, bool burnerStatus);
function updateBurnerStatus(bool burnerStatus) external;
function burn(uint256 amount) external;
function getBurnerStatus(address burnerAddress) external view returns(bool burnerStatus);
}
pragma solidity 0.6.12;
contract PhoenixDAO is ERC20, TokenInterface {
mapping(address => bool) private isBurner;
uint256 constant Decimals = 18;
/// @dev Set amount of initial tokens for the liquidity;
uint256 constant initialTokens = 20000 * 10 ** Decimals;
constructor() public ERC20("PhoenixDAO.Finance", "PHX"){
/// generate initial tokens for the liquidity
_totalSupply = _totalSupply.add(initialTokens);
_balances[msg.sender] = _balances[msg.sender].add(initialTokens);
emit Transfer(address(0), msg.sender, initialTokens);
}
/// @notice The OpenZeppelin renounceOwnership() implementation is
/// overriden to prevent ownership from being renounced accidentally.
function renounceOwnership() public override owneronly {
revert("Ownership cannot be renounced");
}
/// @notice Updates if the caller is authorized to burn tokens
/// @param burnerStatus Updated burner authorization status
function updateBurnerStatus(bool burnerStatus) external override {
require(isBurner[msg.sender] != burnerStatus, "Input will not update state");
isBurner[msg.sender] = burnerStatus;
emit BurnerStatusUpdated(msg.sender, burnerStatus);
}
/// @notice Burns caller's tokens
/// @param amount Amount that will be burned
function burn(uint256 amount) external override {
require(isBurner[msg.sender], "Only burners are allowed to burn");
_burn(msg.sender, amount);
}
/// @notice Returns if an address is authorized to burn tokens
/// @param burnerAddress Address whose burner authorization status will be returned
/// @return burnerStatus Burner authorization status
function getBurnerStatus(address burnerAddress) external view override returns(bool burnerStatus) {
burnerStatus = isBurner[burnerAddress];
}
} | * @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 `owneronly`, which can be applied to your functions to restrict their use to the owner./ | contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() internal view returns (address) {
return _owner;
}
modifier owneronly() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual owneronly {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual owneronly {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
| 1,999,221 | [
1,
8924,
1605,
1492,
8121,
279,
5337,
2006,
3325,
12860,
16,
1625,
1915,
353,
392,
2236,
261,
304,
3410,
13,
716,
848,
506,
17578,
12060,
2006,
358,
2923,
4186,
18,
2525,
805,
16,
326,
3410,
2236,
903,
506,
326,
1245,
716,
5993,
383,
1900,
326,
6835,
18,
1220,
848,
5137,
506,
3550,
598,
288,
13866,
5460,
12565,
5496,
1220,
1605,
353,
1399,
3059,
16334,
18,
2597,
903,
1221,
2319,
326,
9606,
1375,
8443,
3700,
9191,
1492,
848,
506,
6754,
358,
3433,
4186,
358,
13108,
3675,
999,
358,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
14223,
6914,
353,
1772,
288,
203,
565,
1758,
3238,
389,
8443,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
2416,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
203,
565,
3885,
1832,
2713,
288,
203,
3639,
1758,
1234,
12021,
273,
389,
3576,
12021,
5621,
203,
3639,
389,
8443,
273,
1234,
12021,
31,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
12,
2867,
12,
20,
3631,
1234,
12021,
1769,
203,
565,
289,
203,
203,
565,
445,
3410,
1435,
2713,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
9606,
3410,
3700,
1435,
288,
203,
3639,
2583,
24899,
8443,
422,
389,
3576,
12021,
9334,
315,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
1654,
8386,
5460,
12565,
1435,
1071,
5024,
3410,
3700,
288,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
1758,
12,
20,
10019,
203,
3639,
389,
8443,
273,
1758,
12,
20,
1769,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
5024,
3410,
3700,
288,
203,
3639,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
3631,
315,
5460,
429,
30,
394,
3410,
353,
326,
3634,
1758,
8863,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
394,
5541,
1769,
203,
3639,
389,
8443,
273,
394,
5541,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/80001/0x636C4701Fdd1C46e47177cef7032b26402Bf7251/sources/minter1.sol | * @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: _Available since v4.3._/ ecrecover takes the signature parameters, and the only way to get them currently is to use assembly. @solidity memory-safe-assembly | function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
return (address(0), RecoverError.InvalidSignatureLength);
}
}
| 8,818,677 | [
1,
1356,
326,
1758,
716,
6726,
279,
14242,
883,
21863,
2816,
24065,
598,
1375,
8195,
68,
578,
555,
533,
18,
1220,
1758,
848,
1508,
506,
1399,
364,
11805,
13694,
18,
1021,
1375,
557,
266,
3165,
68,
512,
7397,
11396,
5360,
364,
312,
22534,
429,
261,
5836,
17,
6270,
13,
14862,
30,
333,
445,
4925,
87,
2182,
635,
29468,
326,
1375,
87,
68,
460,
358,
506,
316,
326,
2612,
8816,
1353,
16,
471,
326,
1375,
90,
68,
460,
358,
506,
3344,
12732,
578,
9131,
18,
21840,
6856,
30,
1375,
2816,
68,
389,
11926,
67,
506,
326,
563,
434,
279,
1651,
1674,
364,
326,
11805,
358,
506,
8177,
30,
518,
353,
3323,
358,
276,
5015,
14862,
716,
5910,
358,
11078,
6138,
364,
1661,
17,
2816,
329,
501,
18,
432,
4183,
4031,
358,
3387,
333,
353,
635,
15847,
279,
1651,
434,
326,
2282,
883,
261,
12784,
2026,
3541,
506,
4885,
1525,
3631,
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,
3639,
445,
775,
27622,
12,
3890,
1578,
1651,
16,
1731,
3778,
3372,
13,
2713,
16618,
1135,
261,
2867,
16,
868,
3165,
668,
13,
288,
203,
5411,
309,
261,
8195,
18,
2469,
422,
15892,
13,
288,
203,
7734,
1731,
1578,
436,
31,
203,
7734,
1731,
1578,
272,
31,
203,
7734,
2254,
28,
331,
31,
203,
7734,
19931,
288,
203,
10792,
436,
519,
312,
945,
12,
1289,
12,
8195,
16,
374,
92,
3462,
3719,
203,
10792,
272,
519,
312,
945,
12,
1289,
12,
8195,
16,
374,
92,
7132,
3719,
203,
10792,
331,
519,
1160,
12,
20,
16,
312,
945,
12,
1289,
12,
8195,
16,
374,
92,
4848,
20349,
203,
7734,
289,
203,
7734,
327,
775,
27622,
12,
2816,
16,
331,
16,
436,
16,
272,
1769,
203,
7734,
327,
261,
2867,
12,
20,
3631,
868,
3165,
668,
18,
1941,
5374,
1782,
1769,
203,
5411,
289,
203,
3639,
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
]
|
./full_match/1/0xad161b8bEb5bf2Af9cDA30E3988B13F62E70431B/sources/contracts/peripheral/LiquisClaimZap.sol | * @notice Claim all the rewards @param rewardContracts Array of addresses for LP token rewards @param extraRewardContracts Array of addresses for extra rewards @param tokenRewardContracts Array of addresses for token rewards e.g vlCvxExtraRewardDistribution @param tokenRewardTokens Array of token reward addresses to use with tokenRewardContracts @param options Claim options/ claim from main curve LP pools claim from extra rewards claim from multi reward token contract reset remove liq balances if we want to also lock funds already in our wallet claim from liqLit rewards claim from liqLocker stake up to given amount of liq | function claimRewards(
address[] calldata rewardContracts,
address[] calldata extraRewardContracts,
address[] calldata tokenRewardContracts,
address[] calldata tokenRewardTokens,
uint256 options
) external {
require(tokenRewardContracts.length == tokenRewardTokens.length, "!parity");
uint256 removeCvxBalance = IERC20(liq).balanceOf(msg.sender);
for (uint256 i = 0; i < rewardContracts.length; i++) {
IRewardStaking(rewardContracts[i]).getReward(msg.sender, true);
}
for (uint256 i = 0; i < extraRewardContracts.length; i++) {
IRewardStaking(extraRewardContracts[i]).getReward(msg.sender);
}
for (uint256 i = 0; i < tokenRewardContracts.length; i++) {
IRewardStaking(tokenRewardContracts[i]).getReward(msg.sender, tokenRewardTokens[i]);
}
if (_checkOption(options, uint256(Options.UseAllLiqFunds))) {
removeCvxBalance = 0;
}
if (_checkOption(options, uint256(Options.ClaimLiqLit))) {
IRewardStaking(liqLitRewards).getReward(msg.sender, true);
}
if (_checkOption(options, uint256(Options.ClaimLockedLiq))) {
ILiqLocker(liqLocker).getReward(msg.sender);
}
if (_checkOption(options, uint256(Options.LockLiq))) {
uint256 cvxBalance = IERC20(liq).balanceOf(msg.sender) - removeCvxBalance;
if (cvxBalance > 0) {
IERC20(liq).safeTransferFrom(msg.sender, address(this), cvxBalance);
ILiqLocker(liqLocker).lock(msg.sender, cvxBalance);
}
}
}
| 4,852,626 | [
1,
9762,
777,
326,
283,
6397,
225,
19890,
20723,
3639,
1510,
434,
6138,
364,
511,
52,
1147,
283,
6397,
225,
2870,
17631,
1060,
20723,
282,
1510,
434,
6138,
364,
2870,
283,
6397,
225,
1147,
17631,
1060,
20723,
282,
1510,
434,
6138,
364,
1147,
283,
6397,
425,
18,
75,
19755,
39,
26982,
7800,
17631,
1060,
9003,
225,
1147,
17631,
1060,
5157,
1377,
1510,
434,
1147,
19890,
6138,
358,
999,
598,
1147,
17631,
1060,
20723,
225,
702,
7734,
18381,
702,
19,
7516,
628,
2774,
8882,
511,
52,
16000,
7516,
628,
2870,
283,
6397,
7516,
628,
3309,
19890,
1147,
6835,
2715,
1206,
4501,
85,
324,
26488,
309,
732,
2545,
358,
2546,
2176,
284,
19156,
1818,
316,
3134,
9230,
7516,
628,
4501,
85,
23707,
283,
6397,
7516,
628,
4501,
85,
2531,
264,
384,
911,
731,
358,
864,
3844,
434,
4501,
85,
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,
565,
445,
7516,
17631,
14727,
12,
203,
3639,
1758,
8526,
745,
892,
19890,
20723,
16,
203,
3639,
1758,
8526,
745,
892,
2870,
17631,
1060,
20723,
16,
203,
3639,
1758,
8526,
745,
892,
1147,
17631,
1060,
20723,
16,
203,
3639,
1758,
8526,
745,
892,
1147,
17631,
1060,
5157,
16,
203,
3639,
2254,
5034,
702,
203,
565,
262,
3903,
288,
203,
3639,
2583,
12,
2316,
17631,
1060,
20723,
18,
2469,
422,
1147,
17631,
1060,
5157,
18,
2469,
16,
17528,
1065,
560,
8863,
203,
203,
3639,
2254,
5034,
1206,
39,
26982,
13937,
273,
467,
654,
39,
3462,
12,
549,
85,
2934,
12296,
951,
12,
3576,
18,
15330,
1769,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
19890,
20723,
18,
2469,
31,
277,
27245,
288,
203,
5411,
15908,
359,
1060,
510,
6159,
12,
266,
2913,
20723,
63,
77,
65,
2934,
588,
17631,
1060,
12,
3576,
18,
15330,
16,
638,
1769,
203,
3639,
289,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
2870,
17631,
1060,
20723,
18,
2469,
31,
277,
27245,
288,
203,
5411,
15908,
359,
1060,
510,
6159,
12,
7763,
17631,
1060,
20723,
63,
77,
65,
2934,
588,
17631,
1060,
12,
3576,
18,
15330,
1769,
203,
3639,
289,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
1147,
17631,
1060,
20723,
18,
2469,
31,
277,
27245,
288,
203,
5411,
15908,
359,
1060,
510,
6159,
12,
2316,
17631,
1060,
20723,
63,
77,
65,
2934,
588,
17631,
1060,
12,
3576,
18,
15330,
16,
1147,
17631,
1060,
5157,
63,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
_____ __ ______ _____
/ ___// /__________ _____ ____ ____ _____ / ____/___ _____ /__ /
\__ \/ __/ ___/ __ `/ __ \/ __ `/ _ \/ ___/ / __/ / __ `/ __ `/ / /
___/ / /_/ / / /_/ / / / / /_/ / __/ / / /___/ /_/ / /_/ / / /__
/____/\__/_/ \__,_/_/ /_/\__, /\___/_/ /_____/\__, /\__, / /____/
/____/ /____//____/
*/
/*
* Hi Mom !
* I dedicate this project to you ! If I've made it until here it's thank to you
* Thank you for all the things that you did for me, I know it has been really hard sometimes.
* Now you will be in the blockchain forever !
* I love you with all my heart <3
* MW
*/
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
contract StrangerEggZ is ERC721Enumerable, Ownable, ERC721URIStorage {
using Strings for uint256;
string baseTokenUri;
bool baseUriDefined = false;
bool public migrationActive = true;
//EggZ pack unit price
uint256 private unitPrice1EggPack = 0.06 ether; // 0.06 ether
uint256 private unitPrice4EggPack = 0.05 ether; // 0.05 ether
uint256 private unitPrice6EggPack = 0.045 ether; // 0.045 ether
uint256 private unitPrice12EggPack = 0.035 ether; // 0.035 ether
bool public canMint = false;
// withdraw addresses
address artistAdr = 0xb23D2ca9b0CBDDac6DB8A3ACcd13eCb6726d4Ee7;
address sc_dev = 0xda9d7C1c84c7954Ee7F5281cDCddaD359ee072e6;
address oldCOntractAddress = 0x11957A61aC1684Efa13f421e380857DC32E366C7;
address burnAddress = 0x000000000000000000000000000000000000dEaD;
uint256 NB_MINTED_OLD_CONTRACT = 2876;
/* Migration reserve 2876 */
uint256 MIGRATION_SUPPLY = 0;
uint256 MIGRATION_MAX_SUPPLY = NB_MINTED_OLD_CONTRACT;
/* Free EggZ reserve 2876 */
uint256 FREE_EGG_SUPPLY = 0;
uint256 FREE_EGG_MAX_SUPPLY = NB_MINTED_OLD_CONTRACT;
/* Normal mint reserve 10000 - (2876 + 2876) = 4248 TOTAL SUPPLY*/
uint256 NORMAL_MINT_SUPPLY = 0;
// We have 2876 reserved for already minted EggZ in the old smart contract
// + we have reserved the same amount to give a free EggZ when migrate
uint256 NORMAL_MINT_MAX_SUPPLY = 4248;
uint256 NOT_MIG_TOKEN_INDEX = NB_MINTED_OLD_CONTRACT;
function migrationSupply() public view returns(uint256) {
return MIGRATION_SUPPLY;
}
function freeEggSupply() public view returns(uint256) {
return FREE_EGG_SUPPLY;
}
function normalSupply() public view returns(uint256) {
return NORMAL_MINT_SUPPLY;
}
function getNextNonMigratedTokenId() public view returns(uint256) {
return NOT_MIG_TOKEN_INDEX;
}
constructor(string memory baseURI) ERC721("Stranger EggZ", "SEZ") {
setBaseURI(baseURI);
}
/**********************************************
*
* MIGRATION
*
* *******************************************/
function burnAndMintNewEgg(uint256 tokenId) external {
ERC721Enumerable contrat = ERC721Enumerable(oldCOntractAddress);
require(contrat.ownerOf(tokenId) == msg.sender);
contrat.transferFrom(msg.sender, burnAddress, tokenId);
require(contrat.ownerOf(tokenId) == burnAddress);
/* Mint the same EggZ from the previous contract */
mintMigratedEgg(tokenId);
/* Mint a free Egg */
if(migrationActive) {
mintFreeEgg();
}
}
function migrateEggZ(uint256[] memory tokenIds) external {
require(tokenIds.length <= 50, "You can migrate maximum 50 EggZ at a time");
burnTokens(tokenIds);
mintEggZOnNewCOntract(tokenIds);
if(migrationActive) {
mintFreeEggForSender(tokenIds);
}
}
function burnTokens(uint256[] memory tokenIds) internal {
ERC721Enumerable contrat = ERC721Enumerable(oldCOntractAddress);
for(uint256 i; i < tokenIds.length; i++) {
require(contrat.ownerOf(tokenIds[i]) == msg.sender);
contrat.transferFrom(msg.sender, burnAddress, tokenIds[i]);
}
}
function mintEggZOnNewCOntract(uint256[] memory tokenIds) internal {
ERC721Enumerable contrat = ERC721Enumerable(oldCOntractAddress);
for(uint256 i; i < tokenIds.length; i++) {
require(contrat.ownerOf(tokenIds[i]) == burnAddress);
mintMigratedEgg(tokenIds[i]);
}
}
function mintFreeEggForSender(uint256[] memory tokenIds) internal {
for(uint256 i; i < tokenIds.length; i++) {
mintFreeEgg();
}
}
/*************************************************
*
* METADATA PART
*
* ***********************************************/
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenUri;
}
/*
* The setBaseURI function with a possibility to freeze it !
*/
function setBaseURI(string memory baseURI) public onlyOwner() {
require(!baseUriDefined, "Base URI has already been set");
baseTokenUri = baseURI;
}
function lockMetadatas() public onlyOwner() {
baseUriDefined = true;
}
function deactivateMigration() public onlyOwner() {
migrationActive = false;
}
/*************************************************
*
* MINT PART
*
* ***********************************************/
/*
* Mint one Egg
*/
function summon1Egg() public payable {
summonEggZFromSpace(1,unitPrice1EggPack);
}
/*
* Mint a 4 EggZ Pack
*/
function summon4PackEggZ() public payable {
summonEggZFromSpace(4,unitPrice4EggPack);
}
/*
* Mint a 6 EggZ Pack
*/
function summon6PackEggZ() public payable {
summonEggZFromSpace(6,unitPrice6EggPack);
}
/*
* Mint a 12 EggZ Pack
*/
function summon12PackEggZ() public payable {
summonEggZFromSpace(12,unitPrice12EggPack);
}
/*
* Mint from reserve only allowed after migration done
*/
/*
* Mint one Egg from reserve
*/
function summon1EggFromReserve() public payable {
mintInFreeEggZReserve(1,unitPrice1EggPack);
}
/*
* Mint a 4 EggZ Pack from reserve
*/
function summon4PackEggZromReserve() public payable {
mintInFreeEggZReserve(4,unitPrice4EggPack);
}
/*
* Mint a 6 EggZ Pack from reserve
*/
function summon6PackEggZromReserve() public payable {
mintInFreeEggZReserve(6,unitPrice6EggPack);
}
/*
* Mint a 12 EggZ Pack from reserve
*/
function summon12PackEggZromReserve() public payable {
mintInFreeEggZReserve(12,unitPrice12EggPack);
}
/*
* The mint function
*/
function summonEggZFromSpace(uint256 num, uint256 price) internal {
uint256 supply = totalSupply();
require( canMint, "Sale paused" );
require( NORMAL_MINT_SUPPLY + num <= NORMAL_MINT_MAX_SUPPLY, "No EggZ left :'(" );
require( msg.value >= price * num, "Not enough ether sent" );
for(uint256 i; i < num; i++){
_safeMint( msg.sender, supply + i );
NORMAL_MINT_SUPPLY++;
setNotMigTokenId(supply + i);
}
}
function mintInFreeEggZReserve(uint256 num, uint256 price) internal {
uint256 supply = totalSupply();
require( !migrationActive, "Can't mint the reserve if migration is not active");
require( FREE_EGG_SUPPLY + num <= FREE_EGG_MAX_SUPPLY, "No EggZ left :'(" );
require( msg.value >= price * num, "Not enough ether sent" );
for(uint256 i; i < num; i++){
_safeMint( msg.sender, supply + i );
FREE_EGG_SUPPLY++;
setNotMigTokenId(supply + i);
}
}
function mintMigratedEgg(uint256 tokenId) internal {
uint256 supply = totalSupply();
require( MIGRATION_SUPPLY < MIGRATION_MAX_SUPPLY, "Migration reserve empty" );
_safeMint( msg.sender, supply);
MIGRATION_SUPPLY++;
//We have to do this, so the old EggZ have the same metadata in new contract
_setTokenURI(supply, tokenId.toString());
}
function mintFreeEgg() internal {
uint256 supply = totalSupply();
require( FREE_EGG_SUPPLY < FREE_EGG_MAX_SUPPLY, "No EggZ left :'(" );
_safeMint( msg.sender, supply);
FREE_EGG_SUPPLY++;
setNotMigTokenId(supply);
}
function setNotMigTokenId(uint256 supply) internal {
_setTokenURI(supply, NOT_MIG_TOKEN_INDEX.toString());
NOT_MIG_TOKEN_INDEX++;
}
function switchMintStatus() public onlyOwner {
canMint = !canMint;
}
/*************************************************
*
* UTILITY PART
*
* ***********************************************/
/* Just in case */
function update1EggPrice(uint256 price) public onlyOwner() {
unitPrice1EggPack = price;
}
function update4EggPrice(uint256 price) public onlyOwner() {
unitPrice4EggPack = price;
}
function update6EggPrice(uint256 price) public onlyOwner() {
unitPrice6EggPack = price;
}
function update12EggPrice(uint256 price) public onlyOwner() {
unitPrice12EggPack = price;
}
function listEggZOfOwner(address _owner) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for(uint256 i; i < tokenCount; i++){
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
function withdrawAll() public payable onlyOwner {
uint256 _each = address(this).balance / 2;
require(payable(artistAdr).send(_each));
require(payable(sc_dev).send(_each));
}
/*
* Overrides to make ERC721Enumerable and ERC721URIStorage compatible
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// 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 "../ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @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 override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// 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 "../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 "../../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 "../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);
}
| Mint a 12 EggZ Pack from reserve/ | function summon12PackEggZromReserve() public payable {
mintInFreeEggZReserve(12,unitPrice12EggPack);
}
| 10,357,478 | [
1,
49,
474,
279,
2593,
512,
14253,
62,
7930,
628,
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,
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,
2142,
2586,
2138,
4420,
41,
14253,
62,
520,
607,
6527,
1435,
1071,
8843,
429,
288,
203,
3639,
312,
474,
382,
9194,
41,
14253,
62,
607,
6527,
12,
2138,
16,
4873,
5147,
2138,
41,
14253,
4420,
1769,
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
]
|
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract ICC {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function ICC() public {
totalSupply = 1000000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = "Influence Constant Coin"; // Set the name for display purposes
symbol = "ICC"; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
} | Public variables of the token 18 decimals is the strongly suggested default, avoid changing it This creates an array with all balances This generates a public event on the blockchain that will notify clients This notifies clients about the amount burnt | contract ICC {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
function ICC() public {
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
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;
}
}
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;
}
}
function burn(uint256 _value) public returns (bool success) {
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
emit Burn(_from, _value);
return true;
}
} | 14,879,051 | [
1,
4782,
3152,
434,
326,
1147,
6549,
15105,
353,
326,
11773,
715,
22168,
805,
16,
4543,
12770,
518,
1220,
3414,
392,
526,
598,
777,
324,
26488,
1220,
6026,
279,
1071,
871,
603,
326,
16766,
716,
903,
5066,
7712,
1220,
19527,
7712,
2973,
326,
3844,
18305,
88,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
467,
6743,
288,
203,
565,
533,
1071,
508,
31,
203,
565,
533,
1071,
3273,
31,
203,
565,
2254,
28,
1071,
15105,
273,
6549,
31,
203,
565,
2254,
5034,
1071,
2078,
3088,
1283,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
11013,
951,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
1071,
1699,
1359,
31,
203,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
203,
565,
871,
605,
321,
12,
2867,
8808,
628,
16,
2254,
5034,
460,
1769,
203,
203,
5831,
1147,
18241,
288,
445,
6798,
23461,
12,
2867,
389,
2080,
16,
2254,
5034,
389,
1132,
16,
1758,
389,
2316,
16,
1731,
389,
7763,
751,
13,
3903,
31,
289,
203,
565,
445,
467,
6743,
1435,
1071,
288,
203,
565,
289,
203,
203,
565,
445,
389,
13866,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
389,
1132,
13,
2713,
288,
203,
3639,
2583,
24899,
869,
480,
374,
92,
20,
1769,
203,
3639,
2583,
12,
12296,
951,
63,
67,
2080,
65,
1545,
389,
1132,
1769,
203,
3639,
2583,
12,
12296,
951,
63,
67,
869,
65,
397,
389,
1132,
1545,
11013,
951,
63,
67,
869,
19226,
203,
3639,
2254,
2416,
38,
26488,
273,
11013,
951,
63,
67,
2080,
65,
397,
11013,
951,
63,
67,
869,
15533,
203,
3639,
11013,
951,
63,
67,
2080,
65,
3947,
389,
1132,
31,
203,
3639,
11013,
951,
63,
67,
869,
65,
1011,
389,
1132,
31,
203,
3639,
3626,
12279,
24899,
2
]
|
./full_match/5/0x7059279d6F9dCb8d14F4e0bF7Bb99aF66E25cE6f/sources/contracts/MarKetPlace.sol | apartment.senderappartment.push(msg.sender); require(msg.sender == apartment.senderappartment[0], "Unauthorized access"); | function withdraw(uint256 _id) public {
Apartment storage apartment = apartments[_id];
require(apartment.amountappartment <= balances[msg.sender], "Invalid amount");
apartment.owner.transfer(apartment.amountappartment );
apartment.senderappartment = msg.sender;
emit Withdrawal(apartment.senderappartment, apartment.owner, apartment.amountappartment );
}
event Withdrawal(address indexed from, address indexed to, uint amount);
| 1,923,504 | [
1,
438,
24144,
18,
15330,
438,
15750,
18,
6206,
12,
3576,
18,
15330,
1769,
2583,
12,
3576,
18,
15330,
422,
513,
24144,
18,
15330,
438,
15750,
63,
20,
6487,
315,
13981,
2006,
8863,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
598,
9446,
12,
11890,
5034,
389,
350,
13,
1071,
288,
203,
203,
540,
203,
3639,
1716,
24144,
2502,
513,
24144,
273,
513,
485,
1346,
63,
67,
350,
15533,
203,
203,
3639,
2583,
12,
438,
24144,
18,
8949,
438,
15750,
1648,
324,
26488,
63,
3576,
18,
15330,
6487,
315,
1941,
3844,
8863,
203,
3639,
513,
24144,
18,
8443,
18,
13866,
12,
438,
24144,
18,
8949,
438,
15750,
11272,
203,
3639,
513,
24144,
18,
15330,
438,
15750,
225,
273,
1234,
18,
15330,
31,
203,
203,
3639,
3626,
3423,
9446,
287,
12,
438,
24144,
18,
15330,
438,
15750,
16,
513,
24144,
18,
8443,
16,
513,
24144,
18,
8949,
438,
15750,
11272,
203,
565,
289,
203,
203,
871,
3423,
9446,
287,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
3844,
1769,
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
]
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "./CheekyCorgiBase.sol";
contract CheekyCorgi is CheekyCorgiBase
{
using CountersUpgradeable for CountersUpgradeable.Counter;
using SafeMathUpgradeable for uint256;
function initialize(
string memory name,
string memory symbol,
string memory _baseTokenURI,
address admin,
address payable treasury,
address owner,
address _adminImplementation
) external initializer {
__ERC721_init(name, symbol);
__Context_init();
__AccessControlEnumerable_init();
__ERC721Enumerable_init();
__ERC721Burnable_init();
__ERC721Pausable_init();
__Ownable_init();
maxSupply = 8999;
maxPrivateQuantity = 8;
privatePrice = 0.02 ether;
publicPrice = 0.04 ether;
NAME_CHANGE_PRICE = 100000 ether; // 100,000 $SPLOOT Tokens
BIO_CHANGE_PRICE = 100000 ether; // 100,000 $SPLOOT Tokens
baseTokenURI = _baseTokenURI;
ADMIN = admin;
TREASURY = treasury;
transferOwnership(owner);
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
grantRole(DEFAULT_ADMIN_ROLE, ADMIN);
_setupRole(TREASURY_ROLE, TREASURY);
adminImplementation = _adminImplementation;
/**
====================================================================================
[DANGER] please do not change the order of payment methods, as USDT, USDC, SHIBA
====================================================================================
*/
PAYMENT_METHODS[0].token = 0xdAC17F958D2ee523a2206206994597C13D831ec7; // USDT
PAYMENT_METHODS[0].decimals = 6;
PAYMENT_METHODS[0].publicPrice = 180 * (10**6);
PAYMENT_METHODS[1].token = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; // USDC
PAYMENT_METHODS[1].decimals = 6;
PAYMENT_METHODS[1].publicPrice = 180 * (10**6);
PAYMENT_METHODS[2].token = 0x95aD61b0a150d79219dCF64E1E6Cc01f0B64C4cE; // SHIBA INU
PAYMENT_METHODS[2].decimals = 18;
PAYMENT_METHODS[2].publicPrice = 5000000 * (10**18);
PAYMENT_METHODS[3].decimals = 18; // $SPLOOT
PAYMENT_METHODS[3].publicPrice = 0; // [DANGER] keep it as zero until allow minting by SPLOOT
Claimables[0].token = 0x91673149FFae3274b32997288395D07A8213e41F; // JunkYard
Claimables[1].token = 0x4F1B1306E8bd70389d3C413888a61BB41171a0Bc; // ApprovingCorgis
totalClaimed = 0;
maxClaimable = 300;
}
function claim(address _claimableToken, uint256 _tokenId) external whenNotPaused {
require(
block.timestamp >= PUBLIC_SALE_OPEN,
"claim: Claim not open"
);
require(
totalSupply() < maxSupply,
"claim: Quantity must be lesser than maxSupply"
);
require(
totalClaimed < maxClaimable,
"claim: Exceeded over total claimable"
);
require(
!claimedAddresses[msg.sender],
"claim: Already claimed for the address"
);
// 1st: check holdings of UCD ERC20 token
if (_claimableToken == UCD && claimableUcdHolders[msg.sender]) {
claimedAddresses[msg.sender] = true;
totalClaimed ++;
_mintOne(msg.sender);
YIELD_TOKEN.updateRewardOnMint(msg.sender, 1);
return;
} else if (_claimableToken == UCD) {
require(false, "Not UCD holder");
}
// 2nd: check friendship NFT holdings
for (uint256 i = 0; i < 2; i++) {
if (Claimables[i].token != _claimableToken) {
continue;
}
IERC721Enumerable _contract = IERC721Enumerable(Claimables[i].token);
require(_contract.ownerOf(_tokenId) == msg.sender, "claim: Invalid token");
require(!Claimables[i].claimed[_tokenId], "claim: Already claimed for the token");
Claimables[i].claimed[_tokenId] = true;
claimedAddresses[msg.sender] = true;
totalClaimed ++;
_mintOne(msg.sender);
YIELD_TOKEN.updateRewardOnMint(msg.sender, 1);
return;
}
// _claimableToken or _tokenId is wrong, and not able to claim with that
require(false, "Invalid NFT");
}
/**
====================================================================================
[DANGER] please do not confuse the _paymentMethodId, and input correctly like below:
====================================================================================
_paymentMethodId:
0: ETH
1: USDT
2: USDC
3: SHIBA
4: SPLOOT [WARNING] SPLOOT will be burnt, not be transferred to treasure.
*/
function mint(uint256 _quantity, uint256 _paymentMethodId) external payable whenNotPaused {
require(
_paymentMethodId < 5,
"Unsupported token"
);
require(
totalSupply().add(_quantity) <= maxSupply,
"mint: Quantity must be lesser than maxSupply"
);
require(
_quantity > 0,
"mint: Quantity must be greater then zero"
);
require(
block.timestamp >= PUBLIC_SALE_OPEN,
"mint: Public Sale not open"
);
if (_paymentMethodId == 0) {
require(
msg.value == _quantity * publicPrice,
"mint: ETH Value incorrect (quantity * publicPrice)"
);
} else {
uint256 _totalPrice = _quantity.mul(PAYMENT_METHODS[_paymentMethodId-1].publicPrice);
IERC20 _token = IERC20(PAYMENT_METHODS[_paymentMethodId-1].token);
require(
_token.balanceOf(msg.sender) >= _totalPrice,
"mint: Token balance is small"
);
require(
_token.allowance(msg.sender, address(this)) >= _totalPrice,
"mint: Token is not approved"
);
if (_paymentMethodId == 4) {
require(_totalPrice > 0, "Minting by $SPLOOT not allowed");
YIELD_TOKEN.burn(msg.sender, _totalPrice);
} else {
_token.transferFrom(msg.sender, address(this), _totalPrice);
}
}
for (uint256 i = 0; i < _quantity; i++) {
_mintOne(msg.sender);
}
YIELD_TOKEN.updateRewardOnMint(msg.sender, _quantity);
}
// only accepts ETH for private sale
function privateMint(uint256 _quantity) external payable whenNotPaused {
require(
block.timestamp >= PRIVATE_SALE_OPEN,
"privateMint: Private Sale not open"
);
require(
_privateSaleWhitelist[msg.sender] == true,
"privateMint: Not Whitelisted for private sale"
);
require(
msg.value == _quantity * privatePrice,
"privateMint: ETH Value incorrect (quantity * privatePrice)"
);
require(
_quantity > 0,
"privateMint: Quantity must be greater then zero and lesser than maxPrivateQuantity"
);
require(
_privateQuantity[msg.sender].add(_quantity) <= maxPrivateQuantity,
"privateMint: Each user should have at most maxPrivateQuantity tokens for private sale"
);
require(
totalSupply().add(_quantity) <= maxSupply,
"privateMint: Quantity must be lesser than maxSupply"
);
for (uint256 i = 0; i < _quantity; i++) {
_privateQuantity[msg.sender] += 1;
_mintOne(msg.sender);
}
YIELD_TOKEN.updateRewardOnMint(msg.sender, _quantity);
}
function _mintOne(address _owner) internal {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(_owner, newItemId);
emit Minted(_owner, newItemId);
}
// ------------------------- USER FUNCTION ---------------------------
function getReward() external {
YIELD_TOKEN.updateReward(msg.sender, address(0));
YIELD_TOKEN.getReward(msg.sender);
}
/// @dev Allow user to change the unicorn bio
function changeBio(uint256 _tokenId, string memory _bio) public virtual {
address owner = ownerOf(_tokenId);
require(_msgSender() == owner, "ERC721: caller is not the owner");
YIELD_TOKEN.burn(msg.sender, BIO_CHANGE_PRICE);
bio[_tokenId] = _bio;
emit BioChange(_tokenId, _bio);
}
/// @dev Allow user to change the unicorn name
function changeName(uint256 tokenId, string memory newName) public virtual {
address owner = ownerOf(tokenId);
require(_msgSender() == owner, "ERC721: caller is not the owner");
require(validateName(newName) == true, "Not a valid new name");
require(
sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])),
"New name is same as the current one"
);
require(isNameReserved(newName) == false, "Name already reserved");
YIELD_TOKEN.burn(msg.sender, NAME_CHANGE_PRICE);
// If already named, dereserve old name
if (bytes(_tokenName[tokenId]).length > 0) {
toggleReserveName(_tokenName[tokenId], false);
}
toggleReserveName(newName, true);
_tokenName[tokenId] = newName;
emit NameChange(tokenId, newName);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
YIELD_TOKEN.updateReward(from, to);
super.transferFrom(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
YIELD_TOKEN.updateReward(from, to);
super.safeTransferFrom(from, to, tokenId, _data);
}
/**
* @dev Get Token URI Concatenated with Base URI
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721URIStorage: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(baseTokenURI).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(baseTokenURI, tokenId));
}
return super.tokenURI(tokenId);
}
// ----------------------- CALCULATION FUNCTIONS -----------------------
/// @dev Convert String to lower
function toLower(string memory str) public pure returns (string memory) {
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint256 i = 0; i < bStr.length; i++) {
// Uppercase character
if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) {
bLower[i] = bytes1(uint8(bStr[i]) + 32);
} else {
bLower[i] = bStr[i];
}
}
return string(bLower);
}
/// @dev Check if name is reserved
function validateName(string memory str) public pure returns (bool) {
bytes memory b = bytes(str);
if (b.length < 1) return false;
if (b.length > 25) return false; // Cannot be longer than 25 characters
if (b[0] == 0x20) return false; // Leading space
if (b[b.length - 1] == 0x20) return false; // Trailing space
bytes1 lastChar = b[0];
for (uint256 i; i < b.length; i++) {
bytes1 char = b[i];
if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces
if (
!(char >= 0x30 && char <= 0x39) && //9-0
!(char >= 0x41 && char <= 0x5A) && //A-Z
!(char >= 0x61 && char <= 0x7A) && //a-z
!(char == 0x20) //space
) return false;
lastChar = char;
}
return true;
}
function isClaimedAlready(uint256 _claimableId, uint256 _tokenId) external view returns (bool) {
require(_claimableId < 2);
return Claimables[_claimableId].claimed[_tokenId];
}
function isWhitelisted(address _from) public view returns (bool) {
return _privateSaleWhitelist[_from];
}
function isNameReserved(string memory nameString)
public
view
returns (bool)
{
return _nameReserved[toLower(nameString)];
}
function tokenNameByIndex(uint256 index)
public
view
returns (string memory)
{
return _tokenName[index];
}
function toggleReserveName(string memory str, bool isReserve) internal {
_nameReserved[toLower(str)] = isReserve;
}
function getClaimables() external view returns (address[3] memory) {
address[3] memory _addresses;
_addresses[0] = Claimables[0].token;
_addresses[1] = Claimables[1].token;
_addresses[2] = UCD;
return _addresses;
}
// ---------------------- ADMIN FUNCTIONS -----------------------
function reserve(uint256 _count) external {
_count;
delegateToAdmin();
}
function setYieldToken(address _YieldToken) external {
_YieldToken;
delegateToAdmin();
}
function setProvenanceHash(string memory provenanceHash) external {
provenanceHash;
delegateToAdmin();
}
function updateBaseURI(string memory newURI) external {
newURI;
delegateToAdmin();
}
function updateMaxSupply(uint256 _maxSupply) external {
_maxSupply;
delegateToAdmin();
}
function updateQuantity(uint256 _maxPrivateQuantity, uint256 _maxPublicQuantity) external {
_maxPrivateQuantity;
_maxPublicQuantity;
delegateToAdmin();
}
function updatePrice(uint256 _privatePrice, uint256 _publicPrice) external {
_privatePrice;
_publicPrice;
delegateToAdmin();
}
function updatePriceOfToken(uint256 _tokenIndex, uint256 _publicPrice) external {
_tokenIndex;
_publicPrice;
delegateToAdmin();
}
function pause() external virtual {
delegateToAdmin();
}
function unpause() external virtual {
delegateToAdmin();
}
function updateWhitelist(address[] calldata whitelist) external {
whitelist;
delegateToAdmin();
}
function updateUcdHolders(address[] calldata _holders) external {
_holders;
delegateToAdmin();
}
function withdrawToTreasury() external onlyTreasury {
delegateToAdmin();
}
// --------------------- INTERNAL FUNCTIONS ---------------------
function _toggleReserveName(string memory str, bool isReserve) internal {
_nameReserved[toLower(str)] = isReserve;
}
/**
* @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 override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
function delegateToAdmin() internal {
(bool success,) = adminImplementation.delegatecall(msg.data);
require(success);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// 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 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) {
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 "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "./interfaces/IYieldTokenUpgradeable.sol";
contract CheekyCorgiBase is
Initializable,
ContextUpgradeable,
AccessControlEnumerableUpgradeable,
ERC721EnumerableUpgradeable,
ERC721BurnableUpgradeable,
ERC721PausableUpgradeable,
OwnableUpgradeable
{
using CountersUpgradeable for CountersUpgradeable.Counter;
using SafeMathUpgradeable for uint256;
struct PaymentMethod{
address token;
uint256 decimals;
uint256 publicPrice;
}
struct ClaimableNft {
address token;
mapping(uint256 => bool) claimed;
}
// Public Constants
address public constant DEAD =
address(0x000000000000000000000000000000000000dEaD);
uint256 public maxSupply;
uint256 public maxPrivateQuantity; // Maximum amount per user
uint256 public maxPublicQuantity; // Maximum mint per transaction
uint256 public privatePrice;
uint256 public publicPrice;
uint256 public constant PRIVATE_SALE_OPEN = 1638792000;
uint256 public constant PUBLIC_SALE_OPEN = 1638878400;
bytes32 public constant TREASURY_ROLE = keccak256("TREASURY_ROLE");
address public constant UCD = 0xB1Db366890EeB8f28C2813C6a6084353e0b90713;
string public PROVENANCE_HASH;
IYieldTokenUpgradeable public YIELD_TOKEN;
// Public Variables
uint256 public NAME_CHANGE_PRICE;
uint256 public BIO_CHANGE_PRICE;
address public ADMIN;
address payable public TREASURY;
mapping(uint256 => uint256) public birthTimes;
mapping(uint256 => string) public bio;
// Private Variables
CountersUpgradeable.Counter internal _tokenIds;
string public baseTokenURI;
uint256[] internal _allTokens; // Array with all token ids, used for enumeration
mapping(uint256 => string) internal _tokenURIs; // Maps token index to URI
mapping(address => mapping(uint256 => uint256)) internal _ownedTokens; // Mapping from owner to list of owned token IDs
mapping(uint256 => uint256) internal _ownedTokensIndex; // Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal _allTokensIndex; // Mapping from token id to position in the allTokens array
mapping(uint256 => string) internal _tokenName;
mapping(string => bool) internal _nameReserved;
mapping(address => bool) internal _privateSaleWhitelist;
mapping(address => uint256) internal _privateQuantity;
PaymentMethod[4] public PAYMENT_METHODS;
mapping(address => bool) public claimedAddresses; // wallet address vs claimed status
ClaimableNft[2] internal Claimables; // 2 Friendship NFT, Junkyard & ApprovingCorgis
// 3rd option for claiming, just UCD holders
mapping(address => bool) public claimableUcdHolders; // address, who holds 500 + UCDs
uint256 public totalClaimed;
uint256 public maxClaimable;
address internal adminImplementation;
// Please update the following _gap size if changing the storage here.
uint256[19] private __gap;
// Modifiers
modifier onlyAdmin() {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"OnlyAdmin"
);
_;
}
// Modifiers
modifier onlyTreasury() {
require(
hasRole(TREASURY_ROLE, _msgSender()),
"OnlyTreasury"
);
_;
}
// Events
event Minted(address indexed minter, uint256 indexed tokenId);
event Sacrifice(address indexed minter, uint256 indexed tokenId);
event NameChange(uint256 indexed tokenId, string newName);
event BioChange(uint256 indexed tokenId, string bio);
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721PausableUpgradeable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerableUpgradeable, ERC721Upgradeable, ERC721EnumerableUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
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 initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_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);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.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 ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Enumerable_init_unchained();
}
function __ERC721Enumerable_init_unchained() internal initializer {
}
// 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(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.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 < ERC721EnumerableUpgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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();
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../utils/ContextUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable {
function __ERC721Burnable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Burnable_init_unchained();
}
function __ERC721Burnable_init_unchained() internal initializer {
}
/**
* @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);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../security/PausableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @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 ERC721PausableUpgradeable is Initializable, ERC721Upgradeable, PausableUpgradeable {
function __ERC721Pausable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
}
function __ERC721Pausable_init_unchained() internal initializer {
}
/**
* @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");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to 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.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(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 = ERC721Upgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
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 initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// 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 "../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 "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface IYieldTokenUpgradeable is IERC20Upgradeable {
function updateRewardOnMint(address _user, uint256 _amount) external;
function updateReward(address _from, address _to) external;
function getReward(address _to) external;
function burn(address _from, uint256 _amount) external;
function getTotalClaimable(address _user) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
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
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 initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// 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 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
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
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 initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// 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 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
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @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 "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^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;
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 Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/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.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;
/**
* @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 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);
} | Mapping from owner to list of owned token IDs
| mapping(address => mapping(uint256 => uint256)) internal _ownedTokens; | 13,539,329 | [
1,
3233,
628,
3410,
358,
666,
434,
16199,
1147,
7115,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
12,
2867,
516,
2874,
12,
11890,
5034,
516,
2254,
5034,
3719,
2713,
389,
995,
329,
5157,
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
]
|
// Copyright 2021 War Riders
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "./LiquidityLockConfig.sol";
import "./IAdvisorPool.sol";
import "./uniswap/IUniswapV2Router02.sol";
import "./uniswap/IUniswapV2Factory.sol";
import "./uniswap/IUniswapV2Pair.sol";
contract LiquidityLock is Ownable {
// Date-related constants for sanity-checking dates to reject obvious erroneous inputs
// and conversions from seconds to days and years that are more or less leap year-aware.
uint32 private constant SECONDS_PER_DAY = 24 * 60 * 60; /* 86400 seconds in a day */
uint8 private constant MAX_FAIL_AMOUNT = 3;
// Event Data
// Emitted when a staked user are given their rewards
event RewardPaid(address indexed user, uint256 reward);
// Emitted when the execute() function is called
event Locked(uint256 bznPrice, uint256 weiTotal, uint256 lpTokenTotal, uint256 bznExtra);
// Emitted when a user deposits Eth
event Deposit(address indexed user, uint256 amount);
// Emitted when a user redeems either the LP Token or the Extra BZN
event RedeemedToken(address indexed user, address indexed token, uint256 amount);
// Emitted when the contract gets disabled and funds are refunded
event Disabled(string reason);
// Set to true when the execute() is called
// deposit() only works when executed = false
// Redeem functions only work when executed = true
bool public executed;
// General config data
LiquidityLockData public config;
bool public disabled;
uint256 public totalRewardsClaimed;
uint256 public refundingEthAmount;
//total amount
uint256 public totalAmountDeposited;
// deposit data
mapping(address => uint256) public amounts;
// locking data
struct UserLockingData {
bool isActive;
address user;
uint256 lockStartTime;
uint256 lpTokenTotal;
uint256 bznExtraTotal;
}
// Locking data for each user
mapping(address => UserLockingData) public userData;
// Token Vesting Grant data
struct tokenGrant {
bool isActive; /* true if this vesting entry is active and in-effect entry. */
uint32 startDay; /* Start day of the grant, in days since the UNIX epoch (start of day). */
uint256 amount; /* Total number of tokens that vest. */
}
// Global vesting schedule
vestingSchedule public _tokenVestingSchedule;
// Token Vesting grants for each user for LP Tokens
mapping(address => tokenGrant) public _lpTokenGrants;
// Token Vesting grants for each user for BZN Tokens
mapping(address => tokenGrant) public _bznTokenGrants;
IERC20 lpToken;
// staking schedule data
stakingSchedule public _tokenStakingSchedule;
uint256 public totalLiquidityAmount;
uint256 public totalExtraBznAmount;
uint256 internal totalBalanceAtExecute;
uint256 public executedTimestamp;
uint32 public executedDay;
// The last timestamp a user claimed rewards
mapping(address => uint256) public _lastClaimTime;
// The amount of rewards a user has claimed
mapping(address => uint256) public amountClaimed;
constructor(LiquidityLockConfig memory _config) {
_tokenVestingSchedule = _config.schedule;
_tokenStakingSchedule = stakingSchedule(false, 0, 0, 0, 0);
config = _config.data;
}
modifier isActive {
require(!isDisabled(), "Contract is disabled");
require(!executed, "No longer active");
_;
}
modifier hasExecuted {
require(!isDisabled(), "Contract is disabled");
require(executed, "Waiting for execute");
_;
}
modifier isStakingActive {
require(!disabled, "Contract is disabled");
require(_tokenStakingSchedule.isActive, "Staking is not active");
_;
}
receive() external payable { }
/**
* @dev Lets a user deposit ETH to participate in LiquidityLocking. The amount of
* ETH sent must meet the minimum USD price set
* Can only be invoked before the execute() function is called by the owner
*/
function deposit() public payable isActive {
require(msg.value > 0, "Must send some ether");
require(msg.sender != config.recipient, "Recipient cant deposit");
require(msg.sender != owner(), "Owner cant deposit");
require(block.timestamp <= config.dueDate, "Cannot deposit after due date");
require(block.timestamp >= config.startDate, "Cannot deposit before start date");
require(msg.value >= config.minimum, "Must send at least the minimum");
require(msg.value <= config.maximum || config.maximum == 0, "Must send less than or equal to the maximum, or the maximum must be 0");
uint256 currentBalance = totalAmountDeposited + msg.value;
uint256 bznAmount = currentBalance * config.bznRatio;
require(bznAmount <= config.bznHardLimit, "BZN Amount will exceed the hard limit");
amounts[msg.sender] += msg.value;
totalAmountDeposited += msg.value;
emit Deposit(msg.sender, msg.value);
}
// calculate price based on pair reserves
function getTokenPrice(address pairAddress, uint amount) public view returns(uint, uint)
{
IUniswapV2Pair pair = IUniswapV2Pair(pairAddress);
IERC20Metadata token1 = IERC20Metadata(pair.token1());
IERC20Metadata token2 = IERC20Metadata(pair.token0());
(uint Res0, uint Res1,) = pair.getReserves();
// decimals
uint res0 = Res0*(10**token1.decimals());
uint res1 = Res1*(10**token2.decimals());
return (((amount*res0)/Res1) / (10**token2.decimals()), ((amount*res1)/Res0) / (10**token1.decimals())); // return amount of token0 needed to buy token1
}
/**
* @dev Execute the LiquidityLock, locking all deposited Eth
* in the Uniswap v2 Liquidity Pool for ETH/BZN
*
* The LP Tokens retrieved will be distributed to each user proportional
* depending on how much each user has deposited. The LP Tokens will then be staked
* and vested, so the user may only redeem their LP tokens after a certain cliff period
* and linearly depending on the vesting schedule. If a user chooses to keep their
* LP tokens locked in this contract, then they will earn staking rewards
*
* Any extra BZN that did not make it into the Liquidity pool will also be
* distributed to each user proportionally depending on how much each user has deposited. The
* extra BZN will also be vested using the same vesting schedule as the LP Tokens, but they will
* not earn staking rewards
*/
function execute() external onlyOwner isActive {
require(!disabled, "This contract has been disabled");
uint256 currentBalance = totalAmountDeposited;
uint256 bznAmount = currentBalance * config.bznRatio;
require(currentBalance > 0, "No deposits");
if (block.timestamp > config.dueDate && bznAmount < config.bznSoftLimit) {
refund("Due date passed");
return;
}
//First we need to grab all of the BZN and bring it here
IERC20 bzn = IERC20(config.bznAddress);
IAdvisorPool pool = IAdvisorPool(config.bznSource);
require(pool.owner() == address(this), "LiquidityLocking must own Advisor Pool");
uint256 realCurrentBalance = address(this).balance;
require(realCurrentBalance >= totalAmountDeposited, "Recorded amount deposited is less than actual balance");
uint256 weiTotal = currentBalance / 2;
uint256 recipientAmount = currentBalance - weiTotal;
require(bznAmount >= config.bznSoftLimit, "BZN Amount must be at least the soft limit");
require(bznAmount < config.bznHardLimit, "BZN Amount exceeds the hard limit");
//Now transfer the amount we need from the Advisor pool to us
pool.transfer(address(this), bznAmount);
//Create new scope to avoid "stack too deep" compile errors
{
IUniswapV2Router02 uniswap = IUniswapV2Router02(config.uniswapRouter);
address weth = uniswap.WETH();
lpToken = IERC20(IUniswapV2Factory(uniswap.factory()).getPair(config.bznAddress, weth));
require(address(lpToken) != address(0), "BZN/ETH Pool doesn't exist");
uint amountToken; uint amountETH;
//Now we to figure out how much BZN[wei] we are putting up per ETH[wei]
uint256 amountETHDesired = weiTotal;
uint256 amountTokenDesired;
(amountTokenDesired, ) = getTokenPrice(address(lpToken), amountETHDesired);
if (amountTokenDesired > bznAmount) {
//Not enough BZN allocation, swap match
amountTokenDesired = bznAmount;
(,amountETHDesired) = getTokenPrice(address(lpToken), bznAmount);
require(amountETHDesired <= weiTotal, "Impossible to add liquidity");
refundingEthAmount = weiTotal - amountETHDesired;
}
//This is 1%
uint256 amountTokenMin = amountTokenDesired - ((amountTokenDesired * 100) / 10000);
uint256 amountETHMin = amountETHDesired - ((amountETHDesired * 100) / 10000);
bzn.approve(config.uniswapRouter, amountTokenDesired);
(amountToken, amountETH, totalLiquidityAmount) = uniswap.addLiquidityETH{value:amountETHDesired}(config.bznAddress, amountTokenDesired, amountTokenMin, amountETHMin, address(this), block.timestamp);
totalExtraBznAmount = bznAmount - amountToken;
}
totalBalanceAtExecute = currentBalance;
executedTimestamp = block.timestamp;
executedDay = today();
//Transfer the reward amount to us
_tokenStakingSchedule.rewardAmount = config.staking.totalRewardAmount;
pool.transfer(address(this), config.staking.totalRewardAmount);
_tokenStakingSchedule.duration = config.staking.duration;
_tokenStakingSchedule.startTime = block.timestamp;
_tokenStakingSchedule.endTime = _tokenStakingSchedule.startTime + _tokenStakingSchedule.duration;
_tokenStakingSchedule.isActive = true;
executed = true;
config.recipient.transfer(recipientAmount);
pool.transferOwnership(config.recipient);
emit Locked(config.bznRatio, weiTotal, totalLiquidityAmount, totalExtraBznAmount);
}
function isDisabled() public view returns (bool) {
uint256 currentBalance = totalAmountDeposited;
uint256 bznAmount = currentBalance * config.bznRatio;
uint256 grace = config.dueDate + (2 * SECONDS_PER_DAY); //2 day grace period after due date to execute
return disabled || //Refund has been executed
(block.timestamp > config.dueDate && bznAmount < config.bznSoftLimit) || //It is past the due date and the soft limit hasn't been reached
(block.timestamp > grace && !executed); //It it after the grace due date (2 days after due date) and the contract hasn't been executed yet
}
/**
* @dev Allows to disable this contract and refund all users who made a deposit their total deposit.
* Use this if the contract state is broken or a new revision is required. This must be invoked
* before execute(). This cannot be invoke after execute()
* @param reason A reason for the refund to record on-chain
*/
function refund(string memory reason) public onlyOwner isActive {
require(!disabled, "Refund already called");
disabled = true;
IAdvisorPool pool = IAdvisorPool(config.bznSource);
//Dont fail to refund if this call fails for some reason
try pool.owner() returns (address po) {
if (po == address(this)) {
pool.transferOwnership(config.recipient);
}
} catch Error(string memory _err) {
} catch (bytes memory _err) {
}
emit Disabled(reason);
}
/**
* @dev To be used after emergencyShutdown(string) is invoked. Allows users to withdrawal
* their funds in the event of an emergency refund
* @param user The user requesting the refund withdrawal
*/
function refundWithdrawal(address payable user) external {
require(isDisabled(), "Contract has not been disabled");
require(amounts[user] > 0, "Nothing to withdraw");
uint256 userAmount = amounts[user];
amounts[user] = 0;
user.transfer(userAmount);
}
/**
* @dev Depositors must invoke this function after execute() has been invoked. This will
* setup their vesting/staking of LP Tokens and Extra BZN. Anyone can run this function
* on-behalf of the depositor
* @param depositor The depositor address to setup vesting/staking for
*/
function setup(address payable depositor) external {
require(executed, "The execute() function hasn't run yet");
require(!userData[depositor].isActive, "Setup already called for this address");
uint256 userAmount = amounts[depositor];
require(userAmount > 0, "The depositor address provided didn't make any deposit");
uint256 lpTokenAmount = (totalLiquidityAmount * userAmount) / totalBalanceAtExecute;
uint256 bznAmount = (totalExtraBznAmount * userAmount) / totalBalanceAtExecute;
userData[depositor] = UserLockingData(
true,
depositor,
executedTimestamp,
lpTokenAmount,
bznAmount
);
_lpTokenGrants[depositor] = tokenGrant(
true/*isActive*/,
executedDay,
lpTokenAmount
);
_bznTokenGrants[depositor] = tokenGrant(
true,
executedDay,
bznAmount
);
if (refundingEthAmount > 0) {
uint256 ethToSend = (refundingEthAmount * userAmount) / totalBalanceAtExecute;
depositor.transfer(ethToSend);
}
}
/**
* @dev The current total amount of LP Tokens being staked
* @return The total amount of LP Tokens being staked
*/
function totalStaking() public virtual view returns (uint256) {
return lpToken.balanceOf(address(this));
}
/**
* @dev The current amount of LP Tokens an owner is staking
* @param account The account to check
* @return The total amount of LP Tokens being staked by an account
*/
function stakingOf(address account) public virtual view returns (uint256) {
return userData[account].lpTokenTotal;
}
/**
* @dev The current amount of rewards in the reward pool
* @return The total amount of rewards left in the reward pool
*/
function totalRewardPool() public virtual view returns (uint256) {
return _tokenStakingSchedule.rewardAmount;
}
/**
* @dev Get the current amount of rewards earned by an owner
* @param owner The owner to check
* @return The current amount of rewards earned thus far
*/
function rewardAmountFor(address owner) public view isStakingActive returns (uint256) {
if (totalStaking() == 0)
return 0; //No rewards if there is no staking pool
if (!_lpTokenGrants[owner].isActive)
return 0; //No rewards if not active
uint32 onDay = _effectiveDay(today());
uint32 startDay = _lpTokenGrants[owner].startDay;
if (onDay < startDay + _tokenVestingSchedule.cliffDuration)
{
return 0; //No rewards if inside cliff period
}
//Use original amount of reward pool to calculate portion
uint256 amount = totalRewardPool() + totalRewardsClaimed;
uint256 stakeAmount = stakingOf(owner);
//Calculate portion of original reward pool amount owner gets
amount = (amount * stakeAmount) / totalStaking();
//If they've claimed everything
if (amountClaimed[owner] >= amount) {
return 0; //Nothing else left to claim
}
//Remove any BZN they've already claimed
amount = amount - amountClaimed[owner];
uint256 lastRewardClaimTime = _lastClaimTime[owner];
if (lastRewardClaimTime == 0) {
//Set last claim time to be the time where reward period started
lastRewardClaimTime = _tokenStakingSchedule.startTime;
}
if (_tokenStakingSchedule.endTime == 0) {
return 0; //Staking hasn't started yet
}
if (block.timestamp < _tokenStakingSchedule.endTime) {
amount = (amount * (block.timestamp - lastRewardClaimTime)) / (_tokenStakingSchedule.endTime - lastRewardClaimTime);
} else if (lastRewardClaimTime >= _tokenStakingSchedule.endTime) {
//Final check to make sure they don't claim again after period ends
amount = 0;
}
return amount;
}
/**
* @dev Claim staking rewards on behalf of an owner. This will not unstake any LP Tokens.
* Staking rewards will be transferred to the owner, regardless of who invokes
* the function (allows for meta transactions)
* @param owner The owner to claim staking rewards for
*/
function claimFor(address owner) public virtual isStakingActive returns (uint256) {
uint256 amount = rewardAmountFor(owner);
require(amount > 0, "No rewards to claim");
_lastClaimTime[owner] = block.timestamp;
amountClaimed[owner] = amountClaimed[owner] + amount;
totalRewardsClaimed += amount;
_tokenStakingSchedule.rewardAmount -= amount;
IERC20(config.bznAddress).transfer(owner, amount);
emit RewardPaid(owner, amount);
return amount;
}
/**
* @dev Redeem any vested LP Tokens and claim any rewards the staked LP
* tokens have earned on behalf of an owner. The vested LP Tokens
* and staking rewards will be transferred to the owner regardless of who invokes
* the function (allows for meta transactions)
* @param owner The owner of the vested LP Tokens
*/
function redeemLPTokens(address owner) external hasExecuted {
require(userData[owner].isActive, "Address has no tokens to redeem");
require(userData[owner].lpTokenTotal > 0, "No LP Tokens to redeem");
uint256 vestedAmount = getAvailableLPAmount(owner, today());
require(vestedAmount > 0, "No tokens vested yet");
//First give them the rewards they've collected thus far
claimFor(owner);
//Then decrement the amount of tokens they have
userData[owner].lpTokenTotal -= vestedAmount;
//Then transfer the LP tokens
lpToken.transfer(owner, vestedAmount);
}
/**
* @dev Redeem extra BZN on the behalf of an owner. This will redeem any
* vested BZN and transfer it back to the owner regardless of who invokes
* the function (allows for meta transactions)
* @param owner The owner of the vested BZN
*/
function redeemExtraBZN(address owner) external hasExecuted {
require(userData[owner].isActive, "Address has no tokens to redeem");
require(userData[owner].bznExtraTotal > 0, "No BZN Tokens to redeem");
uint256 vestedAmount = getAvailableBZNAmount(owner, today());
require(vestedAmount > 0, "No tokens vested yet");
//Decrement the amount of tokens they have
userData[owner].bznExtraTotal -= vestedAmount;
//Then transfer the LP tokens
IERC20 bznTokens = IERC20(config.bznAddress);
bznTokens.transfer(owner, vestedAmount);
}
/**
* @dev returns true if the account has sufficient funds available to cover the given amount,
* including consideration for vesting tokens.
*
* @param account = The account to check.
* @param amount = The required amount of vested funds.
* @param onDay = The day to check for, in days since the UNIX epoch.
*/
function _LPAreAvailableOn(address account, uint256 amount, uint32 onDay) internal view returns (bool ok) {
return (amount <= getAvailableLPAmount(account, onDay));
}
/**
* @dev Computes the amount of funds in the given account which are available for use as of
* the given day. If there's no vesting schedule then 0 tokens are considered to be vested and
* this just returns the full account balance.
*
* The math is: available amount = total funds - notVestedAmount.
*
* @param grantHolder = The account to check.
* @param onDay = The day to check for, in days since the UNIX epoch.
*/
function getAvailableBZNAmount(address grantHolder, uint32 onDay) public view returns (uint256 amountAvailable) {
uint256 totalTokens = userData[grantHolder].bznExtraTotal;
uint256 vested = totalTokens - _getNotVestedAmount(grantHolder, onDay, _bznTokenGrants[grantHolder]);
return vested;
}
/**
* @dev Computes the amount of funds in the given account which are available for use as of
* the given day. If there's no vesting schedule then 0 tokens are considered to be vested and
* this just returns the full account balance.
*
* The math is: available amount = total funds - notVestedAmount.
*
* @param grantHolder = The account to check.
* @param onDay = The day to check for, in days since the UNIX epoch.
*/
function getAvailableLPAmount(address grantHolder, uint32 onDay) public view returns (uint256 amountAvailable) {
uint256 totalTokens = userData[grantHolder].lpTokenTotal;
uint256 vested = totalTokens - _getNotVestedAmount(grantHolder, onDay, _lpTokenGrants[grantHolder]);
return vested;
}
/**
* @dev returns the day number of the current day, in days since the UNIX epoch.
*/
function today() public view returns (uint32 dayNumber) {
return uint32(block.timestamp / SECONDS_PER_DAY);
}
function _effectiveDay(uint32 onDayOrToday) internal view returns (uint32 dayNumber) {
return onDayOrToday == 0 ? today() : onDayOrToday;
}
/**
* @dev Determines the amount of tokens that have not vested in the given account.
*
* The math is: not vested amount = vesting amount * (end date - on date)/(end date - start date)
*
* @param grantHolder = The account to check.
* @param onDayOrToday = The day to check for, in days since the UNIX epoch. Can pass
* the special value 0 to indicate today.
*/
function _getNotVestedAmount(address grantHolder, uint32 onDayOrToday, tokenGrant memory grant) internal view returns (uint256 amountNotVested) {
uint32 onDay = _effectiveDay(onDayOrToday);
// If there's no schedule, or before the vesting cliff, then the full amount is not vested.
if (!grant.isActive || onDay < grant.startDay + _tokenVestingSchedule.cliffDuration)
{
// None are vested (all are not vested)
return grant.amount;
}
// If after end of vesting, then the not vested amount is zero (all are vested).
else if (onDay >= grant.startDay + _tokenVestingSchedule.duration)
{
// All are vested (none are not vested)
return uint256(0);
}
// Otherwise a fractional amount is vested.
else
{
// Compute the exact number of days vested.
uint32 daysVested = onDay - grant.startDay;
// Adjust result rounding down to take into consideration the interval.
uint32 effectiveDaysVested = (daysVested / _tokenVestingSchedule.interval) * _tokenVestingSchedule.interval;
// Compute the fraction vested from schedule using 224.32 fixed point math for date range ratio.
// Note: This is safe in 256-bit math because max value of X billion tokens = X*10^27 wei, and
// typical token amounts can fit into 90 bits. Scaling using a 32 bits value results in only 125
// bits before reducing back to 90 bits by dividing. There is plenty of room left, even for token
// amounts many orders of magnitude greater than mere billions.
uint256 vested = (grant.amount * effectiveDaysVested) / _tokenVestingSchedule.duration;
return grant.amount - vested;
}
}
} | Locking data for each user | mapping(address => UserLockingData) public userData;
| 6,363,670 | [
1,
2531,
310,
501,
364,
1517,
729,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2874,
12,
2867,
516,
2177,
2531,
310,
751,
13,
1071,
13530,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2021-10-05
*/
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: Account
library Account {
enum Status {Normal, Liquid, Vapor}
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
struct Storage {
mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal
Status status;
}
}
// Part: Actions
library Actions {
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (publicly)
Sell, // sell an amount of some token (publicly)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary}
enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct DepositArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address from;
}
struct WithdrawArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address to;
}
struct TransferArgs {
Types.AssetAmount amount;
Account.Info accountOne;
Account.Info accountTwo;
uint256 market;
}
struct BuyArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 makerMarket;
uint256 takerMarket;
address exchangeWrapper;
bytes orderData;
}
struct SellArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 takerMarket;
uint256 makerMarket;
address exchangeWrapper;
bytes orderData;
}
struct TradeArgs {
Types.AssetAmount amount;
Account.Info takerAccount;
Account.Info makerAccount;
uint256 inputMarket;
uint256 outputMarket;
address autoTrader;
bytes tradeData;
}
struct LiquidateArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info liquidAccount;
uint256 owedMarket;
uint256 heldMarket;
}
struct VaporizeArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info vaporAccount;
uint256 owedMarket;
uint256 heldMarket;
}
struct CallArgs {
Account.Info account;
address callee;
bytes data;
}
}
library Decimal {
struct D256 {
uint256 value;
}
}
library Interest {
struct Rate {
uint256 value;
}
struct Index {
uint96 borrow;
uint96 supply;
uint32 lastUpdate;
}
}
library Monetary {
struct Price {
uint256 value;
}
struct Value {
uint256 value;
}
}
library Storage {
// All information necessary for tracking a market
struct Market {
// Contract address of the associated ERC20 token
address token;
// Total aggregated supply and borrow amount of the entire market
Types.TotalPar totalPar;
// Interest index of the market
Interest.Index index;
// Contract address of the price oracle for this market
address priceOracle;
// Contract address of the interest setter for this market
address interestSetter;
// Multiplier on the marginRatio for this market
Decimal.D256 marginPremium;
// Multiplier on the liquidationSpread for this market
Decimal.D256 spreadPremium;
// Whether additional borrows are allowed for this market
bool isClosing;
}
// The global risk parameters that govern the health and security of the system
struct RiskParams {
// Required ratio of over-collateralization
Decimal.D256 marginRatio;
// Percentage penalty incurred by liquidated accounts
Decimal.D256 liquidationSpread;
// Percentage of the borrower's interest fee that gets passed to the suppliers
Decimal.D256 earningsRate;
// The minimum absolute borrow value of an account
// There must be sufficient incentivize to liquidate undercollateralized accounts
Monetary.Value minBorrowedValue;
}
// The maximum RiskParam values that can be set
struct RiskLimits {
uint64 marginRatioMax;
uint64 liquidationSpreadMax;
uint64 earningsRateMax;
uint64 marginPremiumMax;
uint64 spreadPremiumMax;
uint128 minBorrowedValueMax;
}
// The entire storage state of Solo
struct State {
// number of markets
uint256 numMarkets;
// marketId => Market
mapping(uint256 => Market) markets;
// owner => account number => Account
mapping(address => mapping(uint256 => Account.Storage)) accounts;
// Addresses that can control other users accounts
mapping(address => mapping(address => bool)) operators;
// Addresses that can control all users accounts
mapping(address => bool) globalOperators;
// mutable risk parameters of the system
RiskParams riskParams;
// immutable risk limits of the system
RiskLimits riskLimits;
}
}
// Part: ICallee
/**
* @title ICallee
* @author dYdX
*
* Interface that Callees for Solo must implement in order to ingest data.
*/
interface ICallee {
// ============ Public Functions ============
/**
* Allows users to send this contract arbitrary data.
*
* @param sender The msg.sender to Solo
* @param accountInfo The account from which the data is being sent
* @param data Arbitrary data given by the sender
*/
function callFunction(
address sender,
Account.Info memory accountInfo,
bytes memory data
) external;
}
// Part: ISoloMargin
interface ISoloMargin {
struct OperatorArg {
address operator1;
bool trusted;
}
function ownerSetSpreadPremium(uint256 marketId, Decimal.D256 memory spreadPremium) external;
function getIsGlobalOperator(address operator1) external view returns (bool);
function getMarketTokenAddress(uint256 marketId) external view returns (address);
function ownerSetInterestSetter(uint256 marketId, address interestSetter) external;
function getAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory);
function getMarketPriceOracle(uint256 marketId) external view returns (address);
function getMarketInterestSetter(uint256 marketId) external view returns (address);
function getMarketSpreadPremium(uint256 marketId) external view returns (Decimal.D256 memory);
function getNumMarkets() external view returns (uint256);
function ownerWithdrawUnsupportedTokens(address token, address recipient) external returns (uint256);
function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) external;
function ownerSetLiquidationSpread(Decimal.D256 memory spread) external;
function ownerSetEarningsRate(Decimal.D256 memory earningsRate) external;
function getIsLocalOperator(address owner, address operator1) external view returns (bool);
function getAccountPar(Account.Info memory account, uint256 marketId) external view returns (Types.Par memory);
function ownerSetMarginPremium(uint256 marketId, Decimal.D256 memory marginPremium) external;
function getMarginRatio() external view returns (Decimal.D256 memory);
function getMarketCurrentIndex(uint256 marketId) external view returns (Interest.Index memory);
function getMarketIsClosing(uint256 marketId) external view returns (bool);
function getRiskParams() external view returns (Storage.RiskParams memory);
function getAccountBalances(Account.Info memory account)
external
view
returns (
address[] memory,
Types.Par[] memory,
Types.Wei[] memory
);
function renounceOwnership() external;
function getMinBorrowedValue() external view returns (Monetary.Value memory);
function setOperators(OperatorArg[] memory args) external;
function getMarketPrice(uint256 marketId) external view returns (address);
function owner() external view returns (address);
function isOwner() external view returns (bool);
function ownerWithdrawExcessTokens(uint256 marketId, address recipient) external returns (uint256);
function ownerAddMarket(
address token,
address priceOracle,
address interestSetter,
Decimal.D256 memory marginPremium,
Decimal.D256 memory spreadPremium
) external;
function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external;
function getMarketWithInfo(uint256 marketId)
external
view
returns (
Storage.Market memory,
Interest.Index memory,
Monetary.Price memory,
Interest.Rate memory
);
function ownerSetMarginRatio(Decimal.D256 memory ratio) external;
function getLiquidationSpread() external view returns (Decimal.D256 memory);
function getAccountWei(Account.Info memory account, uint256 marketId) external view returns (Types.Wei memory);
function getMarketTotalPar(uint256 marketId) external view returns (Types.TotalPar memory);
function getLiquidationSpreadForPair(uint256 heldMarketId, uint256 owedMarketId) external view returns (Decimal.D256 memory);
function getNumExcessTokens(uint256 marketId) external view returns (Types.Wei memory);
function getMarketCachedIndex(uint256 marketId) external view returns (Interest.Index memory);
function getAccountStatus(Account.Info memory account) external view returns (uint8);
function getEarningsRate() external view returns (Decimal.D256 memory);
function ownerSetPriceOracle(uint256 marketId, address priceOracle) external;
function getRiskLimits() external view returns (Storage.RiskLimits memory);
function getMarket(uint256 marketId) external view returns (Storage.Market memory);
function ownerSetIsClosing(uint256 marketId, bool isClosing) external;
function ownerSetGlobalOperator(address operator1, bool approved) external;
function transferOwnership(address newOwner) external;
function getAdjustedAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory);
function getMarketMarginPremium(uint256 marketId) external view returns (Decimal.D256 memory);
function getMarketInterestRate(uint256 marketId) external view returns (Interest.Rate memory);
}
// Part: IUniswapAnchoredView
interface IUniswapAnchoredView {
function price(string memory) external returns (uint);
}
// Part: IUniswapV2Router01
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);
}
// Part: IUniswapV3SwapCallback
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// Part: InterestRateModel
interface InterestRateModel {
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) external view returns (uint256, uint256);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
uint256 reserveFactorMantissa
) external view returns (uint256);
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Part: OpenZeppelin/[email protected]/Math
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Part: Types
library Types {
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct TotalPar {
uint128 borrow;
uint128 supply;
}
struct Par {
bool sign; // true if positive
uint128 value;
}
struct Wei {
bool sign; // true if positive
uint256 value;
}
}
// Part: iearn-finance/[email protected]/HealthCheck
interface HealthCheck {
function check(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding,
uint256 totalDebt
) external view returns (bool);
}
// Part: CTokenI
interface CTokenI {
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint256 mintAmount, uint256 mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint256 amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Failure event
*/
event Failure(uint256 error, uint256 info, uint256 detail);
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 amount
) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function borrowRatePerBlock() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) external view returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function accrualBlockNumber() external view returns (uint256);
function exchangeRateStored() external view returns (uint256);
function getCash() external view returns (uint256);
function accrueInterest() external returns (uint256);
function interestRateModel() external view returns (InterestRateModel);
function totalReserves() external view returns (uint256);
function reserveFactorMantissa() external view returns (uint256);
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
function totalBorrows() external view returns (uint256);
function totalSupply() external view returns (uint256);
}
// Part: IERC20Extended
interface IERC20Extended is IERC20 {
function decimals() external view returns (uint8);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
}
// Part: IUniswapV2Router02
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;
}
// Part: IUniswapV3Router
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface IUniswapV3Router is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params)
external
payable
returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params)
external
payable
returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params)
external
payable
returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params)
external
payable
returns (uint256 amountIn);
}
// Part: IWETH
interface IWETH is IERC20 {
function deposit() payable external;
function withdraw(uint256) external;
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: iearn-finance/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: CErc20I
interface CErc20I is CTokenI {
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
function liquidateBorrow(
address borrower,
uint256 repayAmount,
CTokenI cTokenCollateral
) external returns (uint256);
function underlying() external view returns (address);
}
// Part: CEtherI
interface CEtherI is CTokenI {
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function liquidateBorrow(address borrower, CTokenI cTokenCollateral) external payable;
function borrow(uint256 borrowAmount) external returns (uint);
function mint() external payable;
function repayBorrow() external payable;
}
// Part: ComptrollerI
interface ComptrollerI {
function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory);
function exitMarket(address cToken) external returns (uint256);
/*** Policy Hooks ***/
function mintAllowed(
address cToken,
address minter,
uint256 mintAmount
) external returns (uint256);
function mintVerify(
address cToken,
address minter,
uint256 mintAmount,
uint256 mintTokens
) external;
function redeemAllowed(
address cToken,
address redeemer,
uint256 redeemTokens
) external returns (uint256);
function redeemVerify(
address cToken,
address redeemer,
uint256 redeemAmount,
uint256 redeemTokens
) external;
function borrowAllowed(
address cToken,
address borrower,
uint256 borrowAmount
) external returns (uint256);
function borrowVerify(
address cToken,
address borrower,
uint256 borrowAmount
) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint256 repayAmount
) external returns (uint256);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint256 repayAmount,
uint256 borrowerIndex
) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external returns (uint256);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount,
uint256 seizeTokens
) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external;
function transferAllowed(
address cToken,
address src,
address dst,
uint256 transferTokens
) external returns (uint256);
function transferVerify(
address cToken,
address src,
address dst,
uint256 transferTokens
) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint256 repayAmount
) external view returns (uint256, uint256);
function getAccountLiquidity(address account)
external
view
returns (
uint256,
uint256,
uint256
);
/*** Comp claims ****/
function claimComp(address holder) external;
function claimComp(address holder, CTokenI[] memory cTokens) external;
function markets(address ctoken)
external
view
returns (
bool,
uint256,
bool
);
function compSpeeds(address ctoken) external view returns (uint256); // will be deprecated
function compSupplySpeeds(address ctoken) external view returns (uint256);
function compBorrowSpeeds(address ctoken) external view returns (uint256);
function oracle() external view returns (address);
}
// Part: iearn-finance/[email protected]/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
// health checks
bool public doHealthCheck;
address public healthCheck;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.4.3";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external view virtual returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external view virtual returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyEmergencyAuthorized() {
require(
msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyVaultManagers() {
require(msg.sender == vault.management() || msg.sender == governance(), "!authorized");
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
* @param _strategist The address to assign as `strategist`.
* The strategist is able to change the reward address
* @param _rewards The address to use for pulling rewards.
* @param _keeper The adddress of the _keeper. _keeper
* can harvest and tend a strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
function setHealthCheck(address _healthCheck) external onlyVaultManagers {
healthCheck = _healthCheck;
}
function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers {
doHealthCheck = _doHealthCheck;
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate conversion from `_amtInWei` (denominated in wei)
* to `want` (using the native decimal characteristics of `want`).
* @dev
* Care must be taken when working with decimals to assure that the conversion
* is compatible. As an example:
*
* given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),
* with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)
*
* @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want`
* @return The amount in `want` of `_amtInEth` converted to `want`
**/
function ethToWant(uint256 _amtInWei) public view virtual returns (uint256);
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public view virtual returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* Liquidate everything and returns the amount that got freed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*/
function liquidateAllPositions() internal virtual returns (uint256 _amountFreed);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei).
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
// If your implementation uses the cost of the call in want, you can
// use uint256 callCost = ethToWant(callCostInWei);
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei).
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) {
uint256 callCost = ethToWant(callCostInWei);
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 amountFreed = liquidateAllPositions();
if (amountFreed < debtOutstanding) {
loss = debtOutstanding.sub(amountFreed);
} else if (amountFreed > debtOutstanding) {
profit = amountFreed.sub(debtOutstanding);
}
debtPayment = debtOutstanding.sub(loss);
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
// call healthCheck contract
if (doHealthCheck && healthCheck != address(0)) {
require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck");
} else {
doHealthCheck = true;
}
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* The migration process should be carefully performed to make sure all
* the assets are migrated to the new address, which should have never
* interacted with the vault before.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault));
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyEmergencyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
* ```
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
* ```
*/
function protectedTokens() internal view virtual returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// Part: FlashLoanLib
library FlashLoanLib {
using SafeMath for uint256;
event Leverage(uint256 amountRequested, uint256 amountGiven, bool deficit, address flashLoan);
uint256 constant private PRICE_DECIMALS = 1e6;
uint256 constant private WETH_DECIMALS = 1e18;
uint256 constant private COLLAT_RATIO_ETH = 0.74 ether;
address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address private constant WBTC = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;
ComptrollerI private constant COMP = ComptrollerI(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
ISoloMargin public constant SOLO = ISoloMargin(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e);
CEtherI public constant CETH = CEtherI(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5);
function doDyDxFlashLoan(bool deficit, uint256 amountDesired, address want) public returns (uint256) {
if(amountDesired == 0){
return 0;
}
// calculate amount of ETH we need
(uint256 requiredETH, uint256 amountWant)= getFlashLoanParams(want, amountDesired);
// Array of actions to be done during FlashLoan
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
// 1. Take FlashLoan
operations[0] = _getWithdrawAction(0, requiredETH); // hardcoded market ID to 0 (ETH)
// 2. Encode arguments of functions and create action for calling it
bytes memory data = abi.encode(deficit, amountWant);
operations[1] = _getCallAction(
data
);
// 3. Repay FlashLoan
operations[2] = _getDepositAction(0, requiredETH.add(2));
// Create Account Info
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
SOLO.operate(accountInfos, operations);
emit Leverage(amountDesired, requiredETH, deficit, address(SOLO));
return amountWant; // we need to return the amount of Want we have changed our position in
}
function getFlashLoanParams(address want, uint256 amountDesired) internal returns (uint256 requiredETH, uint256 amountWant) {
(uint256 priceETHWant, uint256 decimalsDifference, uint256 _requiredETH) = getPriceETHWant(want, amountDesired);
// to avoid stack too deep
requiredETH = _requiredETH;
amountWant = amountDesired;
// Not enough want in DyDx. So we take all we can
uint256 dxdyLiquidity = IERC20(WETH).balanceOf(address(SOLO));
if(requiredETH > dxdyLiquidity) {
requiredETH = dxdyLiquidity;
// NOTE: if we cap amountETH, we reduce amountWant we are taking too
amountWant = requiredETH.mul(COLLAT_RATIO_ETH).div(priceETHWant).div(1e18).div(decimalsDifference);
}
}
function getPriceETHWant(address want, uint256 amountDesired) internal returns (uint256 priceETHWant, uint256 decimalsDifference, uint256 requiredETH) {
uint256 wantDecimals = 10 ** uint256(IERC20Extended(want).decimals());
decimalsDifference = WETH_DECIMALS > wantDecimals ? WETH_DECIMALS.div(wantDecimals) : wantDecimals.div(WETH_DECIMALS);
if(want == WETH) {
requiredETH = amountDesired.mul(1e18).div(COLLAT_RATIO_ETH);
priceETHWant = 1e6; // 1:1
} else {
priceETHWant = getOraclePrice(WETH).mul(PRICE_DECIMALS).div(getOraclePrice(want));
// requiredETH = desiredWantInETH / COLLAT_RATIO_ETH
// desiredWBTCInETH = (desiredWant / priceETHWant)
// NOTE: decimals need adjustment (e.g. BTC: 8 / ETH: 18)
requiredETH = amountDesired.mul(PRICE_DECIMALS).mul(1e18).mul(decimalsDifference).div(priceETHWant).div(COLLAT_RATIO_ETH);
}
}
function getOraclePrice(address token) internal returns (uint256) {
string memory symbol = IERC20Extended(token).symbol();
// Symbol for WBTC is BTC in oracle
if(token == WBTC) {
symbol = "BTC";
} else if (token == WETH) {
symbol = "ETH";
}
IUniswapAnchoredView oracle = IUniswapAnchoredView(COMP.oracle());
return oracle.price(symbol);
}
function loanLogic(
bool deficit,
uint256 amount,
CErc20I cToken
) public {
uint256 wethBal = IERC20(WETH).balanceOf(address(this));
// NOTE: weth balance should always be > amount/0.75
require(wethBal >= amount, "!bal"); // to stop malicious calls
uint256 wethBalance = IERC20(WETH).balanceOf(address(this));
// 0. Unwrap WETH
IWETH(WETH).withdraw(wethBalance);
// 1. Deposit ETH in Compound as collateral
// will revert if it fails
CETH.mint{value: wethBalance}();
//if in deficit we repay amount and then withdraw
if (deficit) {
// 2a. if in deficit withdraw amount and repay it
require(cToken.redeemUnderlying(amount) == 0, "!redeem_down");
require(cToken.repayBorrow(IERC20(cToken.underlying()).balanceOf(address(this))) == 0, "!repay_down");
} else {
// 2b. if levering up borrow and deposit
require(cToken.borrow(amount) == 0, "!borrow_up");
require(cToken.mint(IERC20(cToken.underlying()).balanceOf(address(this))) == 0, "!mint_up");
}
// 3. Redeem collateral (ETH borrowed from DyDx) from Compound
require(CETH.redeemUnderlying(wethBalance) == 0, "!redeem");
// 4. Wrap ETH into WETH
IWETH(WETH).deposit{value: address(this).balance}();
// NOTE: after this, WETH will be taken by DyDx
}
function _getAccountInfo() internal view returns (Account.Info memory) {
return Account.Info({owner: address(this), number: 1});
}
function _getWithdrawAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
}
// Part: Strategy
/********************
*
* A lender optimisation strategy for any erc20 asset
* https://github.com/Grandthrax/yearnV2-generic-lender-strat
* v0.4.2
*
********************* */
contract Strategy is BaseStrategy, ICallee {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// @notice emitted when trying to do Flash Loan. flashLoan address is 0x00 when no flash loan used
event Leverage(uint256 amountRequested, uint256 amountGiven, bool deficit, address flashLoan);
// Comptroller address for compound.finance
ComptrollerI private constant compound = ComptrollerI(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
//Only three tokens we use
address private constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
address private constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
CErc20I public cToken;
bool public useUniV3;
// fee pool to use in UniV3 in basis points(default: 0.3% = 3000)
uint24 public compToWethSwapFee;
uint24 public wethToWantSwapFee;
IUniswapV2Router02 public currentV2Router;
IUniswapV2Router02 private constant UNI_V2_ROUTER =
IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
IUniswapV2Router02 private constant SUSHI_V2_ROUTER =
IUniswapV2Router02(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F);
IUniswapV3Router private constant UNI_V3_ROUTER =
IUniswapV3Router(0xE592427A0AEce92De3Edee1F18E0157C05861564);
uint256 public collateralTarget; // total borrow / total supply ratio we are targeting (100% = 1e18)
uint256 public blocksToLiquidationDangerZone; // minimum number of blocks before liquidation
uint256 public minWant; // minimum amount of want to act on
// Rewards handling
bool public dontClaimComp; // enable/disables COMP claiming
uint256 public minCompToSell; // minimum amount of COMP to be sold
bool public DyDxActive; // To deactivate flash loan provider if needed
bool public forceMigrate;
constructor(address _vault, address _cToken) public BaseStrategy(_vault) {
_initializeThis(_cToken);
}
function approveTokenMax(address token, address spender) internal {
IERC20(token).safeApprove(spender, type(uint256).max);
}
// To receive ETH from compound and WETH contract
receive() external payable {}
function name() external override view returns (string memory){
return "GenLevCompV2";
}
function initialize(
address _vault,
address _cToken
) external {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
_initializeThis(_cToken);
}
function _initializeThis(address _cToken) internal {
cToken = CErc20I(address(_cToken));
currentV2Router = SUSHI_V2_ROUTER;
//pre-set approvals
approveTokenMax(comp, address(UNI_V2_ROUTER));
approveTokenMax(comp, address(SUSHI_V2_ROUTER));
approveTokenMax(comp, address(UNI_V3_ROUTER));
approveTokenMax(address(want), address(cToken));
approveTokenMax(weth, address(FlashLoanLib.SOLO));
// Enter Compound's ETH market to take it into account when using ETH as collateral
address[] memory markets = new address[](2);
markets[0] = address(FlashLoanLib.CETH);
markets[1] = address(cToken);
compound.enterMarkets(markets);
//comp speed is amount to borrow or deposit (so half the total distribution for want)
compToWethSwapFee = 3000;
wethToWantSwapFee = 3000;
// You can set these parameters on deployment to whatever you want
maxReportDelay = 86400; // once per 24 hours
profitFactor = 100; // multiple before triggering harvest
minCompToSell = 0.1 ether;
collateralTarget = 0.63 ether;
blocksToLiquidationDangerZone = 46500;
DyDxActive = true;
}
/*
* Control Functions
*/
function setUniV3PathFees(uint24 _compToWethSwapFee, uint24 _wethToWantSwapFee) external management {
compToWethSwapFee = _compToWethSwapFee;
wethToWantSwapFee = _wethToWantSwapFee;
}
function setDontClaimComp(bool _dontClaimComp) external management {
dontClaimComp = _dontClaimComp;
}
function setUseUniV3(bool _useUniV3) external management {
useUniV3 = _useUniV3;
}
function setToggleV2Router() external management {
currentV2Router = currentV2Router == SUSHI_V2_ROUTER ? UNI_V2_ROUTER : SUSHI_V2_ROUTER;
}
function setDyDx(bool _dydx) external management {
DyDxActive = _dydx;
}
function setForceMigrate(bool _force) external onlyGovernance {
forceMigrate = _force;
}
function setMinCompToSell(uint256 _minCompToSell) external management {
minCompToSell = _minCompToSell;
}
function setMinWant(uint256 _minWant) external management {
minWant = _minWant;
}
function setCollateralTarget(uint256 _collateralTarget) external management {
(, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));
require(collateralFactorMantissa > _collateralTarget);
collateralTarget = _collateralTarget;
}
/*
* Base External Facing Functions
*/
/*
* An accurate estimate for the total amount of assets (principle + return)
* that this strategy is currently managing, denominated in terms of want tokens.
*/
function estimatedTotalAssets() public override view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 _claimableComp = predictCompAccrued();
uint256 currentComp = balanceOfToken(comp);
// Use touch price. it doesnt matter if we are wrong as this is not used for decision making
uint256 estimatedWant = priceCheck(comp, address(want),_claimableComp.add(currentComp));
uint256 conservativeWant = estimatedWant.mul(9).div(10); //10% pessimist
return balanceOfToken(address(want)).add(deposits).add(conservativeWant).sub(borrows);
}
function balanceOfToken(address token) internal view returns (uint256) {
return IERC20(token).balanceOf(address(this));
}
//predicts our profit at next report
function expectedReturn() public view returns (uint256) {
uint256 estimateAssets = estimatedTotalAssets();
uint256 debt = vault.strategies(address(this)).totalDebt;
if (debt > estimateAssets) {
return 0;
} else {
return estimateAssets.sub(debt);
}
}
/*
* Provide a signal to the keeper that `tend()` should be called.
* (keepers are always reimbursed by yEarn)
*
* NOTE: this call and `harvestTrigger` should never return `true` at the same time.
* tendTrigger should be called with same gasCost as harvestTrigger
*/
function tendTrigger(uint256 gasCost) public override view returns (bool) {
if (harvestTrigger(gasCost)) {
//harvest takes priority
return false;
}
return getblocksUntilLiquidation() <= blocksToLiquidationDangerZone;
}
//WARNING. manipulatable and simple routing. Only use for safe functions
function priceCheck(address start, address end, uint256 _amount) public view returns (uint256) {
if (_amount == 0) {
return 0;
}
uint256[] memory amounts = currentV2Router.getAmountsOut(_amount, getTokenOutPathV2(start, end));
return amounts[amounts.length - 1];
}
/*****************
* Public non-base function
******************/
//Calculate how many blocks until we are in liquidation based on current interest rates
//WARNING does not include compounding so the estimate becomes more innacurate the further ahead we look
//equation. Compound doesn't include compounding for most blocks
//((deposits*colateralThreshold - borrows) / (borrows*borrowrate - deposits*colateralThreshold*interestrate));
function getblocksUntilLiquidation() public view returns (uint256) {
(, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 borrrowRate = cToken.borrowRatePerBlock();
uint256 supplyRate = cToken.supplyRatePerBlock();
uint256 collateralisedDeposit1 = deposits.mul(collateralFactorMantissa).div(1e18);
uint256 collateralisedDeposit = collateralisedDeposit1;
uint256 denom1 = borrows.mul(borrrowRate);
uint256 denom2 = collateralisedDeposit.mul(supplyRate);
if (denom2 >= denom1) {
return type(uint256).max;
} else {
uint256 numer = collateralisedDeposit.sub(borrows);
uint256 denom = denom1.sub(denom2);
//minus 1 for this block
return numer.mul(1e18).div(denom);
}
}
// This function makes a prediction on how much comp is accrued
// It is not 100% accurate as it uses current balances in Compound to predict into the past
function predictCompAccrued() public view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
if (deposits == 0) {
return 0; // should be impossible to have 0 balance and positive comp accrued
}
uint256 distributionPerBlockSupply = compound.compSupplySpeeds(address(cToken));
uint256 distributionPerBlockBorrow = compound.compBorrowSpeeds(address(cToken));
uint256 totalBorrow = cToken.totalBorrows();
//total supply needs to be echanged to underlying using exchange rate
uint256 totalSupplyCtoken = cToken.totalSupply();
uint256 totalSupply = totalSupplyCtoken.mul(cToken.exchangeRateStored()).div(1e18);
uint256 blockShareSupply = 0;
if(totalSupply > 0) {
blockShareSupply = deposits.mul(distributionPerBlockSupply).div(totalSupply);
}
uint256 blockShareBorrow = 0;
if(totalBorrow > 0) {
blockShareBorrow = borrows.mul(distributionPerBlockBorrow).div(totalBorrow);
}
//how much we expect to earn per block
uint256 blockShare = blockShareSupply.add(blockShareBorrow);
//last time we ran harvest
uint256 lastReport = vault.strategies(address(this)).lastReport;
uint256 blocksSinceLast= (block.timestamp.sub(lastReport)).div(13); //roughly 13 seconds per block
return blocksSinceLast.mul(blockShare);
}
//Returns the current position
//WARNING - this returns just the balance at last time someone touched the cToken token. Does not accrue interst in between
//cToken is very active so not normally an issue.
function getCurrentPosition() public view returns (uint256 deposits, uint256 borrows) {
(, uint256 ctokenBalance, uint256 borrowBalance, uint256 exchangeRate) = cToken.getAccountSnapshot(address(this));
borrows = borrowBalance;
deposits = ctokenBalance.mul(exchangeRate).div(1e18);
}
//statechanging version
function getLivePosition() public returns (uint256 deposits, uint256 borrows) {
deposits = cToken.balanceOfUnderlying(address(this));
//we can use non state changing now because we updated state with balanceOfUnderlying call
borrows = cToken.borrowBalanceStored(address(this));
}
//Same warning as above
function netBalanceLent() public view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
return deposits.sub(borrows);
}
/***********
* internal core logic
*********** */
/*
* A core method.
* Called at beggining of harvest before providing report to owner
* 1 - claim accrued comp
* 2 - if enough to be worth it we sell
* 3 - because we lose money on our loans we need to offset profit from comp.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity. also reduces bytesize
if (balanceOfToken(address(cToken)) == 0) {
uint256 wantBalance = balanceOfToken(address(want));
//no position to harvest
//but we may have some debt to return
//it is too expensive to free more debt in this method so we do it in adjust position
_debtPayment = Math.min(wantBalance, _debtOutstanding);
return (_profit, _loss, _debtPayment);
}
(uint256 deposits, uint256 borrows) = getLivePosition();
//claim comp accrued
_claimComp();
//sell comp
_disposeOfComp();
uint256 wantBalance = balanceOfToken(address(want));
uint256 investedBalance = deposits.sub(borrows);
uint256 balance = investedBalance.add(wantBalance);
uint256 debt = vault.strategies(address(this)).totalDebt;
//Balance - Total Debt is profit
if (balance > debt) {
_profit = balance.sub(debt);
if (wantBalance < _profit) {
//all reserve is profit
_profit = wantBalance;
} else if (wantBalance > _profit.add(_debtOutstanding)) {
_debtPayment = _debtOutstanding;
} else {
_debtPayment = wantBalance.sub(_profit);
}
} else {
//we will lose money until we claim comp then we will make money
//this has an unintended side effect of slowly lowering our total debt allowed
_loss = debt.sub(balance);
_debtPayment = Math.min(wantBalance, _debtOutstanding);
}
}
/*
* Second core function. Happens after report call.
*
* Similar to deposit function from V1 strategy
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
//emergency exit is dealt with in prepareReturn
if (emergencyExit) {
return;
}
//we are spending all our cash unless we have debt outstanding
uint256 _wantBal = balanceOfToken(address(want));
if(_wantBal < _debtOutstanding){
//this is graceful withdrawal. dont use backup
//we use more than 1 because withdrawunderlying causes problems with 1 token due to different decimals
if(balanceOfToken(address(cToken)) > 1){
_withdrawSome(_debtOutstanding.sub(_wantBal));
}
return;
}
(uint256 position, bool deficit) = _calculateDesiredPosition(_wantBal - _debtOutstanding, true);
//if we are below minimun want change it is not worth doing
//need to be careful in case this pushes to liquidation
if (position > minWant) {
//if dydx is not active we just try our best with basic leverage
if (!DyDxActive) {
uint i = 0;
while(position > 0){
position = position.sub(_noFlashLoan(position, deficit));
if(i >= 6){
break;
}
i++;
}
} else {
//if there is huge position to improve we want to do normal leverage. it is quicker
if (position > want.balanceOf(address(FlashLoanLib.SOLO))) {
position = position.sub(_noFlashLoan(position, deficit));
}
//flash loan to position
if(position > minWant){
doDyDxFlashLoan(deficit, position);
}
}
}
}
/*************
* Very important function
* Input: amount we want to withdraw and whether we are happy to pay extra for Aave.
* cannot be more than we have
* Returns amount we were able to withdraw. notall if user has some balance left
*
* Deleverage position -> redeem our cTokens
******************** */
function _withdrawSome(uint256 _amount) internal returns (bool notAll) {
(uint256 position, bool deficit) = _calculateDesiredPosition(_amount, false);
//If there is no deficit we dont need to adjust position
//if the position change is tiny do nothing
if (deficit && position > minWant) {
//we do a flash loan to give us a big gap. from here on out it is cheaper to use normal deleverage. Use Aave for extremely large loans
if (DyDxActive) {
position = position.sub(doDyDxFlashLoan(deficit, position));
}
uint8 i = 0;
//position will equal 0 unless we haven't been able to deleverage enough with flash loan
//if we are not in deficit we dont need to do flash loan
while (position > minWant.add(100)) {
position = position.sub(_noFlashLoan(position, true));
i++;
//A limit set so we don't run out of gas
if (i >= 5) {
notAll = true;
break;
}
}
}
//now withdraw
//if we want too much we just take max
//This part makes sure our withdrawal does not force us into liquidation
(uint256 depositBalance, uint256 borrowBalance) = getCurrentPosition();
uint256 tempColla = collateralTarget;
uint256 reservedAmount = 0;
if(tempColla == 0){
tempColla = 1e15; // 0.001 * 1e18. lower we have issues
}
reservedAmount = borrowBalance.mul(1e18).div(tempColla);
if(depositBalance >= reservedAmount){
uint256 redeemable = depositBalance.sub(reservedAmount);
if (redeemable < _amount) {
cToken.redeemUnderlying(redeemable);
} else {
cToken.redeemUnderlying(_amount);
}
}
if(collateralTarget == 0 && balanceOfToken(address(want)) > borrowBalance){
cToken.repayBorrow(borrowBalance);
}
}
/***********
* This is the main logic for calculating how to change our lends and borrows
* Input: balance. The net amount we are going to deposit/withdraw.
* Input: dep. Is it a deposit or withdrawal
* Output: position. The amount we want to change our current borrow position.
* Output: deficit. True if we are reducing position size
*
* For instance deficit =false, position 100 means increase borrowed balance by 100
****** */
function _calculateDesiredPosition(uint256 balance, bool dep) internal returns (uint256 position, bool deficit) {
//we want to use statechanging for safety
(uint256 deposits, uint256 borrows) = getLivePosition();
//When we unwind we end up with the difference between borrow and supply
uint256 unwoundDeposit = deposits.sub(borrows);
//we want to see how close to collateral target we are.
//So we take our unwound deposits and add or remove the balance we are are adding/removing.
//This gives us our desired future undwoundDeposit (desired supply)
uint256 desiredSupply = 0;
if (dep) {
desiredSupply = unwoundDeposit.add(balance);
} else {
if(balance > unwoundDeposit) balance = unwoundDeposit;
desiredSupply = unwoundDeposit.sub(balance);
}
//(ds *c)/(1-c)
uint256 num = desiredSupply.mul(collateralTarget);
uint256 den = uint256(1e18).sub(collateralTarget);
uint256 desiredBorrow = num.div(den);
if (desiredBorrow > 1e5) {
//stop us going right up to the wire
desiredBorrow = desiredBorrow.sub(1e5);
}
//now we see if we want to add or remove balance
// if the desired borrow is less than our current borrow we are in deficit. so we want to reduce position
if (desiredBorrow < borrows) {
deficit = true;
position = borrows.sub(desiredBorrow); //safemath check done in if statement
} else {
//otherwise we want to increase position
deficit = false;
position = desiredBorrow.sub(borrows);
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amount`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = balanceOfToken(address(want));
uint256 assets = netBalanceLent().add(_balance);
uint256 debtOutstanding = vault.debtOutstanding();
if(debtOutstanding > assets){
_loss = debtOutstanding.sub(assets);
}
if (assets < _amountNeeded) {
//if we cant afford to withdraw we take all we can
//withdraw all we can
(uint256 deposits, uint256 borrows) = getLivePosition();
//1 token causes rounding error with withdrawUnderlying
if(balanceOfToken(address(cToken)) > 1){
_withdrawSome(deposits.sub(borrows));
}
_amountFreed = Math.min(_amountNeeded, balanceOfToken(address(want)));
} else {
if (_balance < _amountNeeded) {
_withdrawSome(_amountNeeded.sub(_balance));
//overflow error if we return more than asked for
_amountFreed = Math.min(_amountNeeded, balanceOfToken(address(want)));
}else{
_amountFreed = _amountNeeded;
}
}
}
function _claimComp() internal {
if(dontClaimComp) {
return;
}
CTokenI[] memory tokens = new CTokenI[](1);
tokens[0] = cToken;
compound.claimComp(address(this), tokens);
}
//sell comp function
function _disposeOfComp() internal {
uint256 _comp = balanceOfToken(comp);
if (_comp < minCompToSell) {
return;
}
if (useUniV3) {
UNI_V3_ROUTER.exactInput(
IUniswapV3Router.ExactInputParams(
getTokenOutPathV3(comp, address(want)),
address(this),
now,
_comp,
0
)
);
} else {
currentV2Router.swapExactTokensForTokens(
_comp,
0,
getTokenOutPathV2(comp, address(want)),
address(this),
now
);
}
}
function getTokenOutPathV2(address _tokenIn, address _tokenOut)
internal
pure
returns (address[] memory _path)
{
bool isWeth =
_tokenIn == address(weth) || _tokenOut == address(weth);
_path = new address[](isWeth ? 2 : 3);
_path[0] = _tokenIn;
if (isWeth) {
_path[1] = _tokenOut;
} else {
_path[1] = address(weth);
_path[2] = _tokenOut;
}
}
function getTokenOutPathV3(address _tokenIn, address _tokenOut)
internal
view
returns (bytes memory _path)
{
if (address(want) == weth) {
_path = abi.encodePacked(
address(_tokenIn),
compToWethSwapFee,
address(weth)
);
} else {
_path = abi.encodePacked(
address(_tokenIn),
compToWethSwapFee,
address(weth),
wethToWantSwapFee,
address(_tokenOut)
);
}
}
//lets leave
//if we can't deleverage in one go set collateralFactor to 0 and call harvest multiple times until delevered
function prepareMigration(address _newStrategy) internal override {
if(!forceMigrate){
(uint256 deposits, uint256 borrows) = getLivePosition();
_withdrawSome(deposits.sub(borrows));
(, , uint256 borrowBalance, ) = cToken.getAccountSnapshot(address(this));
require(borrowBalance < 10_000);
IERC20 _comp = IERC20(comp);
uint _compB = balanceOfToken(address(_comp));
if(_compB > 0){
_comp.safeTransfer(_newStrategy, _compB);
}
}
}
//Three functions covering normal leverage and deleverage situations
// max is the max amount we want to increase our borrowed balance
// returns the amount we actually did
function _noFlashLoan(uint256 max, bool deficit) internal returns (uint256 amount) {
//we can use non-state changing because this function is always called after _calculateDesiredPosition
(uint256 lent, uint256 borrowed) = getCurrentPosition();
//if we have nothing borrowed then we can't deleverage any more
if (borrowed == 0 && deficit) {
return 0;
}
(, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));
if (deficit) {
amount = _normalDeleverage(max, lent, borrowed, collateralFactorMantissa);
} else {
amount = _normalLeverage(max, lent, borrowed, collateralFactorMantissa);
}
emit Leverage(max, amount, deficit, address(0));
}
//maxDeleverage is how much we want to reduce by
function _normalDeleverage(
uint256 maxDeleverage,
uint256 lent,
uint256 borrowed,
uint256 collatRatio
) internal returns (uint256 deleveragedAmount) {
uint256 theoreticalLent = 0;
//collat ration should never be 0. if it is something is very wrong... but just incase
if(collatRatio != 0){
theoreticalLent = borrowed.mul(1e18).div(collatRatio);
}
deleveragedAmount = lent.sub(theoreticalLent);
if (deleveragedAmount >= borrowed) {
deleveragedAmount = borrowed;
}
if (deleveragedAmount >= maxDeleverage) {
deleveragedAmount = maxDeleverage;
}
uint256 exchangeRateStored = cToken.exchangeRateStored();
//redeemTokens = redeemAmountIn *1e18 / exchangeRate. must be more than 0
//a rounding error means we need another small addition
if(deleveragedAmount.mul(1e18) >= exchangeRateStored && deleveragedAmount > 10){
deleveragedAmount = deleveragedAmount.sub(uint256(10));
cToken.redeemUnderlying(deleveragedAmount);
//our borrow has been increased by no more than maxDeleverage
cToken.repayBorrow(deleveragedAmount);
}
}
//maxDeleverage is how much we want to increase by
function _normalLeverage(
uint256 maxLeverage,
uint256 lent,
uint256 borrowed,
uint256 collatRatio
) internal returns (uint256 leveragedAmount) {
uint256 theoreticalBorrow = lent.mul(collatRatio).div(1e18);
leveragedAmount = theoreticalBorrow.sub(borrowed);
if (leveragedAmount >= maxLeverage) {
leveragedAmount = maxLeverage;
}
if(leveragedAmount > 10){
leveragedAmount = leveragedAmount.sub(uint256(10));
cToken.borrow(leveragedAmount);
cToken.mint(balanceOfToken(address(want)));
}
}
//emergency function that we can use to deleverage manually if something is broken
function manualDeleverage(uint256 amount) external management{
require(cToken.redeemUnderlying(amount) == 0);
require(cToken.repayBorrow(amount) == 0);
}
//emergency function that we can use to deleverage manually if something is broken
function manualReleaseWant(uint256 amount) external onlyGovernance{
require(cToken.redeemUnderlying(amount) ==0);
}
function protectedTokens() internal override view returns (address[] memory) {
}
/******************
* Flash loan stuff
****************/
// Flash loan DXDY
// amount desired is how much we are willing for position to change
function doDyDxFlashLoan(bool deficit, uint256 amountDesired) internal returns (uint256) {
return FlashLoanLib.doDyDxFlashLoan(deficit, amountDesired, address(want));
}
//returns our current collateralisation ratio. Should be compared with collateralTarget
function storedCollateralisation() public view returns (uint256 collat) {
(uint256 lend, uint256 borrow) = getCurrentPosition();
if (lend == 0) {
return 0;
}
collat = uint256(1e18).mul(borrow).div(lend);
}
//DyDx calls this function after doing flash loan
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public override {
(bool deficit, uint256 amount) = abi.decode(data, (bool, uint256));
require(msg.sender == address(FlashLoanLib.SOLO));
require(sender == address(this));
FlashLoanLib.loanLogic(deficit, amount, cToken);
}
// -- Internal Helper functions -- //
function ethToWant(uint256 _amtInWei) public view override returns (uint256) {
return priceCheck(weth, address(want), _amtInWei);
}
function liquidateAllPositions() internal override returns (uint256 _amountFreed) {
(_amountFreed,) = liquidatePosition(vault.debtOutstanding());
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 position = deposits.sub(borrows);
//we want to revert if we can't liquidateall
if(!forceMigrate) {
require(position < minWant);
}
}
function mgtm_check() internal {
require(msg.sender == governance() || msg.sender == vault.management() || msg.sender == strategist);
}
modifier management() {
mgtm_check();
_;
}
}
// File: LevCompFactory.sol
contract LevCompFactory {
address public immutable original;
event Cloned(address indexed clone);
event Deployed(address indexed original);
constructor(
address _vault,
address _cToken
) public {
Strategy _original = new Strategy(_vault, _cToken);
emit Deployed(address(_original));
original = address(_original);
}
function name() external view returns (string memory) {
return string(abi.encodePacked("Factory", Strategy(payable(original)).name(), "@", Strategy(payable(original)).apiVersion()));
}
function cloneLevComp(
address _vault,
address _cToken
) external returns (address payable newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(original);
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(
clone_code,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone_code, 0x14), addressBytes)
mstore(
add(clone_code, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(_vault, _cToken);
emit Cloned(newStrategy);
}
} | Array of actions to be done during FlashLoan | Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
| 2,237,206 | [
1,
1076,
434,
4209,
358,
506,
2731,
4982,
15014,
1504,
304,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
202,
6100,
18,
1803,
2615,
8526,
3778,
5295,
273,
394,
18765,
18,
1803,
2615,
8526,
12,
23,
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";
/// @title Set positions eMode on Aave v3
contract AaveV3SetEMode is ActionBase, AaveV3Helper {
using TokenUtils for address;
struct Params {
uint8 categoryId;
bool useDefaultMarket;
address market;
}
/// @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.market = _parseParamAddr(params.market, _paramMapping[0], _subData, _returnValues);
(uint256 categoryId, bytes memory logData) = _setEmode(params.market, params.categoryId);
emit ActionEvent("AaveV3SetEMode", logData);
return bytes32(categoryId);
}
/// @inheritdoc ActionBase
function executeActionDirect(bytes calldata _callData) public payable override {
Params memory params = parseInputs(_callData);
(, bytes memory logData) = _setEmode(params.market, params.categoryId);
logger.logActionDirectEvent("AaveV3SetEMode", logData);
}
function executeActionDirectL2() public payable {
Params memory params = decodeInputs(msg.data[4:]);
(, bytes memory logData) = _setEmode(params.market, params.categoryId);
logger.logActionDirectEvent("AaveV3SetEMode", logData);
}
/// @inheritdoc ActionBase
function actionType() public pure virtual override returns (uint8) {
return uint8(ActionType.STANDARD_ACTION);
}
//////////////////////////// ACTION LOGIC ////////////////////////////
/// @notice User sets EMode for Aave position on Proxy
/// @param _market Address provider for specific market
/// @param _categoryId eMode category id (0 - 255)
function _setEmode(address _market, uint8 _categoryId)
internal
returns (uint256, bytes memory)
{
IPoolV3 lendingPool = getLendingPool(_market);
lendingPool.setUserEMode(_categoryId);
bytes memory logData = abi.encode(_market, _categoryId);
return (_categoryId, logData);
}
function parseInputs(bytes memory _callData) public pure returns (Params memory params) {
params = abi.decode(_callData, (Params));
if (params.useDefaultMarket) {
params.market = DEFAULT_AAVE_MARKET;
}
}
function encodeInputs(Params memory params) public pure returns (bytes memory encodedInput) {
encodedInput = bytes.concat(this.executeActionDirectL2.selector);
encodedInput = bytes.concat(encodedInput, bytes1(params.categoryId));
encodedInput = bytes.concat(encodedInput, boolToBytes(params.useDefaultMarket));
if (!params.useDefaultMarket) {
encodedInput = bytes.concat(encodedInput, bytes20(params.market));
}
}
function decodeInputs(bytes calldata encodedInput) public pure returns (Params memory params) {
params.categoryId = uint8(bytes1(encodedInput[0:1]));
params.useDefaultMarket = bytesToBool(bytes1(encodedInput[1:2]));
if (params.useDefaultMarket) {
params.market = DEFAULT_AAVE_MARKET;
} else {
params.market = address(bytes20(encodedInput[2:22]));
}
}
}
| @title Set positions eMode on Aave v3 | contract AaveV3SetEMode is ActionBase, AaveV3Helper {
using TokenUtils for address;
struct Params {
uint8 categoryId;
bool useDefaultMarket;
address market;
}
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.market = _parseParamAddr(params.market, _paramMapping[0], _subData, _returnValues);
(uint256 categoryId, bytes memory logData) = _setEmode(params.market, params.categoryId);
emit ActionEvent("AaveV3SetEMode", logData);
return bytes32(categoryId);
}
function executeActionDirect(bytes calldata _callData) public payable override {
Params memory params = parseInputs(_callData);
(, bytes memory logData) = _setEmode(params.market, params.categoryId);
logger.logActionDirectEvent("AaveV3SetEMode", logData);
}
function executeActionDirectL2() public payable {
Params memory params = decodeInputs(msg.data[4:]);
(, bytes memory logData) = _setEmode(params.market, params.categoryId);
logger.logActionDirectEvent("AaveV3SetEMode", logData);
}
function actionType() public pure virtual override returns (uint8) {
return uint8(ActionType.STANDARD_ACTION);
}
function _setEmode(address _market, uint8 _categoryId)
internal
returns (uint256, bytes memory)
{
IPoolV3 lendingPool = getLendingPool(_market);
lendingPool.setUserEMode(_categoryId);
bytes memory logData = abi.encode(_market, _categoryId);
return (_categoryId, logData);
}
function parseInputs(bytes memory _callData) public pure returns (Params memory params) {
params = abi.decode(_callData, (Params));
if (params.useDefaultMarket) {
params.market = DEFAULT_AAVE_MARKET;
}
}
function parseInputs(bytes memory _callData) public pure returns (Params memory params) {
params = abi.decode(_callData, (Params));
if (params.useDefaultMarket) {
params.market = DEFAULT_AAVE_MARKET;
}
}
function encodeInputs(Params memory params) public pure returns (bytes memory encodedInput) {
encodedInput = bytes.concat(this.executeActionDirectL2.selector);
encodedInput = bytes.concat(encodedInput, bytes1(params.categoryId));
encodedInput = bytes.concat(encodedInput, boolToBytes(params.useDefaultMarket));
if (!params.useDefaultMarket) {
encodedInput = bytes.concat(encodedInput, bytes20(params.market));
}
}
function encodeInputs(Params memory params) public pure returns (bytes memory encodedInput) {
encodedInput = bytes.concat(this.executeActionDirectL2.selector);
encodedInput = bytes.concat(encodedInput, bytes1(params.categoryId));
encodedInput = bytes.concat(encodedInput, boolToBytes(params.useDefaultMarket));
if (!params.useDefaultMarket) {
encodedInput = bytes.concat(encodedInput, bytes20(params.market));
}
}
function decodeInputs(bytes calldata encodedInput) public pure returns (Params memory params) {
params.categoryId = uint8(bytes1(encodedInput[0:1]));
params.useDefaultMarket = bytesToBool(bytes1(encodedInput[1:2]));
if (params.useDefaultMarket) {
params.market = DEFAULT_AAVE_MARKET;
params.market = address(bytes20(encodedInput[2:22]));
}
}
function decodeInputs(bytes calldata encodedInput) public pure returns (Params memory params) {
params.categoryId = uint8(bytes1(encodedInput[0:1]));
params.useDefaultMarket = bytesToBool(bytes1(encodedInput[1:2]));
if (params.useDefaultMarket) {
params.market = DEFAULT_AAVE_MARKET;
params.market = address(bytes20(encodedInput[2:22]));
}
}
} else {
}
| 7,295,061 | [
1,
694,
6865,
425,
2309,
603,
432,
836,
331,
23,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
432,
836,
58,
23,
694,
41,
2309,
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,
28311,
31,
203,
3639,
1426,
999,
1868,
3882,
278,
31,
203,
3639,
1758,
13667,
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,
27151,
273,
389,
2670,
786,
3178,
12,
2010,
18,
27151,
16,
389,
891,
3233,
63,
20,
6487,
389,
1717,
751,
16,
389,
2463,
1972,
1769,
203,
203,
3639,
261,
11890,
5034,
28311,
16,
1731,
3778,
613,
751,
13,
273,
389,
542,
1514,
390,
12,
2010,
18,
27151,
16,
859,
18,
4743,
548,
1769,
203,
3639,
3626,
19641,
2932,
37,
836,
58,
23,
694,
41,
2309,
3113,
613,
751,
1769,
203,
3639,
327,
1731,
1578,
12,
4743,
548,
1769,
203,
565,
289,
203,
203,
565,
445,
1836,
1803,
5368,
12,
3890,
745,
892,
389,
1991,
751,
13,
1071,
8843,
429,
3849,
288,
203,
3639,
8861,
3778,
859,
273,
1109,
10059,
24899,
1991,
751,
1769,
203,
3639,
261,
16,
1731,
3778,
613,
751,
13,
273,
2
]
|
./full_match/4/0xC9434231534B8fab79d9226e1b443c372A966F65/sources/contracts/staking/IStakingData.sol | * @dev Represents a request to close an allocation with a specific proof of indexing. This is passed when calling closeAllocationMany to define the closing parameters for each allocation./ | struct CloseAllocationRequest {
address allocationID;
bytes32 poi;
}
| 649,092 | [
1,
23869,
87,
279,
590,
358,
1746,
392,
13481,
598,
279,
2923,
14601,
434,
14403,
18,
1220,
353,
2275,
1347,
4440,
1746,
17353,
5594,
358,
4426,
326,
7647,
1472,
364,
1517,
13481,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1958,
3527,
17353,
691,
288,
203,
3639,
1758,
13481,
734,
31,
203,
3639,
1731,
1578,
29075,
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
]
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract MyCollectible is ERC721Enumerable, Ownable, ERC721Burnable, ERC721Pausable {
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenIdTracker;
uint256 public constant MAX_COLLECTIBLES = 7;
uint256 public constant MAX_BY_MINT = 1;
uint256 public constant PRICE = 1 * 10**15; // 1 ETH is 10**18 WEI
string public baseTokenURI;
string public provenanceHash;
event CreateMyCollectible(uint256 indexed id);
constructor(string memory baseURI, string memory provenance) ERC721("MyCollectible", "PFP") {
baseTokenURI = baseURI;
provenanceHash = provenance;
pause(true);
}
modifier saleIsOpen() {
require(_totalSupply() < MAX_COLLECTIBLES, "Sale end");
_;
}
function _totalSupply() internal view returns (uint256) {
return _tokenIdTracker.current();
}
function totalMint() external view returns (uint256) {
return _totalSupply();
}
function mint(address to, uint256 count) external payable saleIsOpen {
require(_totalSupply() + count <= MAX_COLLECTIBLES, "Max limit");
require(count <= MAX_BY_MINT, "Exceeds number");
require(msg.value >= price(count), "Value below price");
for (uint256 i = 0; i < count; i++) {
_mintAnElement(to);
}
}
function _mintAnElement(address to) private {
uint256 id = _totalSupply();
_tokenIdTracker.increment();
_safeMint(to, id);
emit CreateMyCollectible(id);
}
function price(uint256 count) public pure returns (uint256) {
return PRICE.mul(count);
}
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
function walletOfOwner(address walletOwner) external view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(walletOwner);
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i = 0; i < tokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(walletOwner, i);
}
return tokensId;
}
function pause(bool val) public onlyOwner {
if (val) {
_pause();
return;
}
_unpause();
}
function withdrawAll() external onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0, "No balance");
address payable recipient = payable(address(msg.sender));
recipient.transfer(balance);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
}
| 1 ETH is 10**18 WEI
| uint256 public constant PRICE = 1 * 10**15; | 6,365,287 | [
1,
21,
512,
2455,
353,
13822,
28,
13880,
45,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
1071,
5381,
10365,
1441,
273,
404,
380,
1728,
636,
3600,
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
]
|
./full_match/1/0x5537f945D8c3FCFDc1b8DECEEBD220FAD26aFdA8/sources/contracts/ComposableStablePoolStorage.sol | Convert from an index into an array including BPT (the Vault's registered token list), to an index into an array excluding BPT (usually from user input, such as amountsIn/Out). `index` must not be the BPT token index itself. Currently this is never called with an index passed in from user input, so this check should not be necessary. Included for completion (and future proofing). | function _skipBptIndex(uint256 index) internal view returns (uint256) {
_require(index != getBptIndex(), Errors.OUT_OF_BOUNDS);
return index < getBptIndex() ? index : index.sub(1);
}
| 4,901,509 | [
1,
2723,
628,
392,
770,
1368,
392,
526,
6508,
605,
1856,
261,
5787,
17329,
1807,
4104,
1147,
666,
3631,
358,
392,
770,
1368,
392,
526,
19560,
605,
1856,
261,
407,
3452,
628,
729,
810,
16,
4123,
487,
30980,
382,
19,
1182,
2934,
1375,
1615,
68,
1297,
486,
506,
326,
605,
1856,
1147,
770,
6174,
18,
15212,
333,
353,
5903,
2566,
598,
392,
770,
2275,
316,
628,
729,
810,
16,
1427,
333,
866,
1410,
486,
506,
4573,
18,
657,
7908,
364,
8364,
261,
464,
3563,
14601,
310,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
7457,
38,
337,
1016,
12,
11890,
5034,
770,
13,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
389,
6528,
12,
1615,
480,
2882,
337,
1016,
9334,
9372,
18,
5069,
67,
3932,
67,
5315,
2124,
3948,
1769,
203,
203,
3639,
327,
770,
411,
2882,
337,
1016,
1435,
692,
770,
294,
770,
18,
1717,
12,
21,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/3/0xFa93A8E8B2d4Ce1eccE95d5eBD5D6c47584F586C/sources/FormulaInit.sol | 0x4655524e4143455f4150500000000000000000000000000000000000000000000x4655524e4143455f4954454d5f4d494e455f4645450000000000000000000000 0x434f4e54524143545f494e5445525354454c4c41525f454e434f444552000000 0x434f4e54524143545f4c414e445f4954454d5f42415200000000000000000000 0x434f4e54524143545f41504f53544c455f4954454d5f42415200000000000000 0x434f4e54524143545f4954454d5f424153450000000000000000000000000000 0x434f4e54524143545f4452494c4c5f4241534500000000000000000000000000 0x434f4e54524143545f44415257494e49415f49544f5f42415345000000000000 0x434f4e54524143545f4c414e445f424153450000000000000000000000000000 0x434f4e54524143545f4f424a4543545f4f574e45525348495000000000000000 0x434f4e54524143545f4552433732315f4745474f000000000000000000000000 0x434f4e54524143545f464f524d554c4100000000000000000000000000000000 0x434f4e54524143545f4d455441444154415f54454c4c455200000000000000000x434f4e54524143545f4c505f454c454d454e545f544f4b454e00000000000000 0x434f4e54524143545f4c505f474f4c445f45524332305f544f4b454e00000000 0x434f4e54524143545f4c505f574f4f445f45524332305f544f4b454e00000000 0x434f4e54524143545f4c505f57415445525f45524332305f544f4b454e000000 0x434f4e54524143545f4c505f464952455f45524332305f544f4b454e00000000 0x434f4e54524143545f4c505f534f494c5f45524332305f544f4b454e00000000 0x434f4e54524143545f52494e475f45524332305f544f4b454e00000000000000 0x434f4e54524143545f4b544f4e5f45524332305f544f4b454e000000000000000x434f4e54524143545f454c454d454e545f544f4b454e00000000000000000000 0x434f4e54524143545f474f4c445f45524332305f544f4b454e00000000000000 0x434f4e54524143545f574f4f445f45524332305f544f4b454e00000000000000 0x434f4e54524143545f57415445525f45524332305f544f4b454e000000000000 0x434f4e54524143545f464952455f45524332305f544f4b454e00000000000000 0x434f4e54524143545f534f494c5f45524332305f544f4b454e00000000000000 | contract FurnaceSettingIds {
uint256 public constant PREFER_GOLD = 1 << 1;
uint256 public constant PREFER_WOOD = 1 << 2;
uint256 public constant PREFER_WATER = 1 << 3;
uint256 public constant PREFER_FIRE = 1 << 4;
uint256 public constant PREFER_SOIL = 1 << 5;
bytes32 public constant FURNACE_APP = "FURNACE_APP";
bytes32 public constant FURNACE_ITEM_MINE_FEE = "FURNACE_ITEM_MINE_FEE";
uint128 public constant RATE_PRECISION = 10**8;
bytes32 public constant CONTRACT_INTERSTELLAR_ENCODER =
"CONTRACT_INTERSTELLAR_ENCODER";
bytes32 public constant CONTRACT_LAND_ITEM_BAR = "CONTRACT_LAND_ITEM_BAR";
bytes32 public constant CONTRACT_APOSTLE_ITEM_BAR =
"CONTRACT_APOSTLE_ITEM_BAR";
bytes32 public constant CONTRACT_ITEM_BASE = "CONTRACT_ITEM_BASE";
bytes32 public constant CONTRACT_DRILL_BASE = "CONTRACT_DRILL_BASE";
bytes32 public constant CONTRACT_DARWINIA_ITO_BASE = "CONTRACT_DARWINIA_ITO_BASE";
bytes32 public constant CONTRACT_LAND_BASE = "CONTRACT_LAND_BASE";
bytes32 public constant CONTRACT_OBJECT_OWNERSHIP =
"CONTRACT_OBJECT_OWNERSHIP";
bytes32 public constant CONTRACT_ERC721_GEGO = "CONTRACT_ERC721_GEGO";
bytes32 public constant CONTRACT_FORMULA = "CONTRACT_FORMULA";
bytes32 public constant CONTRACT_METADATA_TELLER =
"CONTRACT_METADATA_TELLER";
bytes32 public constant CONTRACT_LP_ELEMENT_TOKEN =
"CONTRACT_LP_ELEMENT_TOKEN";
bytes32 public constant CONTRACT_LP_GOLD_ERC20_TOKEN =
"CONTRACT_LP_GOLD_ERC20_TOKEN";
bytes32 public constant CONTRACT_LP_WOOD_ERC20_TOKEN =
"CONTRACT_LP_WOOD_ERC20_TOKEN";
bytes32 public constant CONTRACT_LP_WATER_ERC20_TOKEN =
"CONTRACT_LP_WATER_ERC20_TOKEN";
bytes32 public constant CONTRACT_LP_FIRE_ERC20_TOKEN =
"CONTRACT_LP_FIRE_ERC20_TOKEN";
bytes32 public constant CONTRACT_LP_SOIL_ERC20_TOKEN =
"CONTRACT_LP_SOIL_ERC20_TOKEN";
bytes32 public constant CONTRACT_RING_ERC20_TOKEN =
"CONTRACT_RING_ERC20_TOKEN";
bytes32 public constant CONTRACT_KTON_ERC20_TOKEN =
"CONTRACT_KTON_ERC20_TOKEN";
bytes32 public constant CONTRACT_ELEMENT_TOKEN =
"CONTRACT_ELEMENT_TOKEN";
bytes32 public constant CONTRACT_GOLD_ERC20_TOKEN =
"CONTRACT_GOLD_ERC20_TOKEN";
bytes32 public constant CONTRACT_WOOD_ERC20_TOKEN =
"CONTRACT_WOOD_ERC20_TOKEN";
bytes32 public constant CONTRACT_WATER_ERC20_TOKEN =
"CONTRACT_WATER_ERC20_TOKEN";
bytes32 public constant CONTRACT_FIRE_ERC20_TOKEN =
"CONTRACT_FIRE_ERC20_TOKEN";
bytes32 public constant CONTRACT_SOIL_ERC20_TOKEN =
"CONTRACT_SOIL_ERC20_TOKEN";
pragma solidity >=0.6.7 <0.7.0;
}
| 5,295,377 | [
1,
20,
92,
8749,
2539,
25,
3247,
73,
24,
3461,
5026,
2539,
74,
9803,
3361,
25,
12648,
12648,
12648,
12648,
12648,
2787,
92,
8749,
2539,
25,
3247,
73,
24,
3461,
5026,
2539,
74,
7616,
25,
6334,
6564,
72,
25,
74,
24,
72,
7616,
24,
73,
24,
2539,
74,
24,
1105,
6564,
25,
12648,
12648,
9449,
374,
92,
24,
5026,
74,
24,
73,
6564,
25,
3247,
3461,
4763,
7950,
74,
7616,
24,
73,
25,
6334,
2539,
2947,
4763,
6334,
6564,
71,
24,
71,
24,
3600,
2947,
74,
24,
6564,
73,
24,
5026,
74,
6334,
24,
2539,
22,
9449,
374,
92,
24,
5026,
74,
24,
73,
6564,
25,
3247,
3461,
4763,
7950,
74,
24,
71,
24,
3461,
73,
6334,
25,
74,
7616,
25,
6334,
6564,
72,
25,
74,
24,
3247,
27655,
12648,
12648,
2787,
374,
92,
24,
5026,
74,
24,
73,
6564,
25,
3247,
3461,
4763,
7950,
74,
24,
3600,
3028,
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,
478,
321,
623,
5568,
2673,
288,
203,
202,
11890,
5034,
1071,
5381,
7071,
6553,
67,
43,
11846,
273,
404,
2296,
404,
31,
203,
202,
11890,
5034,
1071,
5381,
7071,
6553,
67,
59,
51,
1212,
273,
404,
2296,
576,
31,
203,
202,
11890,
5034,
1071,
5381,
7071,
6553,
67,
59,
13641,
273,
404,
2296,
890,
31,
203,
202,
11890,
5034,
1071,
5381,
7071,
6553,
67,
1653,
862,
273,
404,
2296,
1059,
31,
203,
202,
11890,
5034,
1071,
5381,
7071,
6553,
67,
3584,
2627,
273,
404,
2296,
1381,
31,
203,
203,
203,
202,
3890,
1578,
1071,
5381,
478,
8521,
6312,
67,
7215,
273,
315,
42,
8521,
6312,
67,
7215,
14432,
203,
203,
202,
3890,
1578,
1071,
5381,
478,
8521,
6312,
67,
12674,
67,
49,
3740,
67,
8090,
41,
273,
315,
42,
8521,
6312,
67,
12674,
67,
49,
3740,
67,
8090,
41,
14432,
203,
203,
202,
11890,
10392,
1071,
5381,
534,
1777,
67,
3670,
26913,
273,
1728,
636,
28,
31,
203,
203,
202,
3890,
1578,
1071,
5381,
8020,
2849,
1268,
67,
9125,
882,
21943,
985,
67,
1157,
9086,
654,
273,
203,
202,
202,
6,
6067,
2849,
1268,
67,
9125,
882,
21943,
985,
67,
1157,
9086,
654,
14432,
203,
203,
202,
3890,
1578,
1071,
5381,
8020,
2849,
1268,
67,
48,
4307,
67,
12674,
67,
21908,
273,
315,
6067,
2849,
1268,
67,
48,
4307,
67,
12674,
67,
21908,
14432,
203,
203,
202,
3890,
1578,
1071,
5381,
8020,
2849,
1268,
67,
2203,
4005,
900,
67,
12674,
67,
21908,
273,
203,
202,
202,
6,
6067,
2849,
1268,
67,
2203,
4005,
2
]
|
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "./interfaces/INodeOperatorRegistry.sol";
import "./interfaces/IValidatorFactory.sol";
import "./interfaces/IValidator.sol";
import "./interfaces/IStMATIC.sol";
/// @title NodeOperatorRegistry
/// @author 2021 ShardLabs.
/// @notice NodeOperatorRegistry is the main contract that manage validators
/// @dev NodeOperatorRegistry is the main contract that manage operators.
contract NodeOperatorRegistry is
INodeOperatorRegistry,
PausableUpgradeable,
AccessControlUpgradeable,
ReentrancyGuardUpgradeable
{
enum NodeOperatorStatus {
INACTIVE,
ACTIVE,
STOPPED,
UNSTAKED,
CLAIMED,
EXIT,
JAILED,
EJECTED
}
/// @notice The node operator struct
/// @param status node operator status(INACTIVE, ACTIVE, STOPPED, CLAIMED, UNSTAKED, EXIT, JAILED, EJECTED).
/// @param name node operator name.
/// @param rewardAddress Validator public key used for access control and receive rewards.
/// @param validatorId validator id of this node operator on the polygon stake manager.
/// @param signerPubkey public key used on heimdall.
/// @param validatorShare validator share contract used to delegate for on polygon.
/// @param validatorProxy the validator proxy, the owner of the validator.
/// @param commissionRate the commission rate applied by the operator on polygon.
/// @param maxDelegateLimit max delegation limit that StMatic contract will delegate to this operator each time delegate function is called.
struct NodeOperator {
NodeOperatorStatus status;
string name;
address rewardAddress;
bytes signerPubkey;
address validatorShare;
address validatorProxy;
uint256 validatorId;
uint256 commissionRate;
uint256 maxDelegateLimit;
}
/// @notice all the roles.
bytes32 public constant REMOVE_OPERATOR_ROLE =
keccak256("LIDO_REMOVE_OPERATOR");
bytes32 public constant PAUSE_OPERATOR_ROLE =
keccak256("LIDO_PAUSE_OPERATOR");
bytes32 public constant DAO_ROLE = keccak256("LIDO_DAO");
/// @notice contract version.
string public version;
/// @notice total node operators.
uint256 private totalNodeOperators;
/// @notice validatorFactory address.
address private validatorFactory;
/// @notice stakeManager address.
address private stakeManager;
/// @notice polygonERC20 token (Matic) address.
address private polygonERC20;
/// @notice stMATIC address.
address private stMATIC;
/// @notice keeps track of total number of operators
uint256 nodeOperatorCounter;
/// @notice min amount allowed to stake per validator.
uint256 public minAmountStake;
/// @notice min HeimdallFees allowed to stake per validator.
uint256 public minHeimdallFees;
/// @notice commision rate applied to all the operators.
uint256 public commissionRate;
/// @notice allows restake.
bool public allowsRestake;
/// @notice default max delgation limit.
uint256 public defaultMaxDelegateLimit;
/// @notice This stores the operators ids.
uint256[] private operatorIds;
/// @notice Mapping of all owners with node operator id. Mapping is used to be able to
/// extend the struct.
mapping(address => uint256) private operatorOwners;
/// @notice Mapping of all node operators. Mapping is used to be able to extend the struct.
mapping(uint256 => NodeOperator) private operators;
/// --------------------------- Modifiers-----------------------------------
/// @notice Check if the msg.sender has permission.
/// @param _role role needed to call function.
modifier userHasRole(bytes32 _role) {
checkCondition(hasRole(_role, msg.sender), "unauthorized");
_;
}
/// @notice Check if the amount is inbound.
/// @param _amount amount to stake.
modifier checkStakeAmount(uint256 _amount) {
checkCondition(_amount >= minAmountStake, "Invalid amount");
_;
}
/// @notice Check if the heimdall fee is inbound.
/// @param _heimdallFee heimdall fee.
modifier checkHeimdallFees(uint256 _heimdallFee) {
checkCondition(_heimdallFee >= minHeimdallFees, "Invalid fees");
_;
}
/// @notice Check if the maxDelegateLimit is less or equal to 10 Billion.
/// @param _maxDelegateLimit max delegate limit.
modifier checkMaxDelegationLimit(uint256 _maxDelegateLimit) {
checkCondition(
_maxDelegateLimit <= 10000000000 ether,
"Max amount <= 10B"
);
_;
}
/// @notice Check if the rewardAddress is already used.
/// @param _rewardAddress new reward address.
modifier checkIfRewardAddressIsUsed(address _rewardAddress) {
checkCondition(
operatorOwners[_rewardAddress] == 0 && _rewardAddress != address(0),
"Address used"
);
_;
}
/// -------------------------- initialize ----------------------------------
/// @notice Initialize the NodeOperator contract.
function initialize(
address _validatorFactory,
address _stakeManager,
address _polygonERC20,
address _stMATIC
) external initializer {
__Pausable_init();
__AccessControl_init();
__ReentrancyGuard_init();
validatorFactory = _validatorFactory;
stakeManager = _stakeManager;
polygonERC20 = _polygonERC20;
stMATIC = _stMATIC;
minAmountStake = 10 * 10**18;
minHeimdallFees = 20 * 10**18;
defaultMaxDelegateLimit = 10 ether;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(REMOVE_OPERATOR_ROLE, msg.sender);
_setupRole(PAUSE_OPERATOR_ROLE, msg.sender);
_setupRole(DAO_ROLE, msg.sender);
}
/// ----------------------------- API --------------------------------------
/// @notice Add a new node operator to the system.
/// @dev The operator life cycle starts when we call the addOperator
/// func allows adding a new operator. During this call, a new validatorProxy is
/// deployed by the ValidatorFactory which we can use later to interact with the
/// Polygon StakeManager. At the end of this call, the status of the operator
/// will be INACTIVE.
/// @param _name the node operator name.
/// @param _rewardAddress address used for ACL and receive rewards.
/// @param _signerPubkey public key used on heimdall len 64 bytes.
function addOperator(
string memory _name,
address _rewardAddress,
bytes memory _signerPubkey
)
external
override
whenNotPaused
userHasRole(DAO_ROLE)
checkIfRewardAddressIsUsed(_rewardAddress)
{
nodeOperatorCounter++;
address validatorProxy = IValidatorFactory(validatorFactory).create();
operators[nodeOperatorCounter] = NodeOperator({
status: NodeOperatorStatus.INACTIVE,
name: _name,
rewardAddress: _rewardAddress,
validatorId: 0,
signerPubkey: _signerPubkey,
validatorShare: address(0),
validatorProxy: validatorProxy,
commissionRate: commissionRate,
maxDelegateLimit: defaultMaxDelegateLimit
});
operatorIds.push(nodeOperatorCounter);
totalNodeOperators++;
operatorOwners[_rewardAddress] = nodeOperatorCounter;
emit AddOperator(nodeOperatorCounter);
}
/// @notice Allows to stop an operator from the system.
/// @param _operatorId the node operator id.
function stopOperator(uint256 _operatorId)
external
override
{
(, NodeOperator storage no) = getOperator(_operatorId);
require(
no.rewardAddress == msg.sender || hasRole(DAO_ROLE, msg.sender), "unauthorized"
);
NodeOperatorStatus status = getOperatorStatus(no);
checkCondition(
status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.INACTIVE ||
status == NodeOperatorStatus.JAILED
, "Invalid status");
if (status == NodeOperatorStatus.INACTIVE) {
no.status = NodeOperatorStatus.EXIT;
} else {
IStMATIC(stMATIC).withdrawTotalDelegated(no.validatorShare);
no.status = NodeOperatorStatus.STOPPED;
}
emit StopOperator(_operatorId);
}
/// @notice Allows to remove an operator from the system.when the operator status is
/// set to EXIT the GOVERNANCE can call the removeOperator func to delete the operator,
/// and the validatorProxy used to interact with the Polygon stakeManager.
/// @param _operatorId the node operator id.
function removeOperator(uint256 _operatorId)
external
override
whenNotPaused
userHasRole(REMOVE_OPERATOR_ROLE)
{
(, NodeOperator storage no) = getOperator(_operatorId);
checkCondition(no.status == NodeOperatorStatus.EXIT, "Invalid status");
// update the operatorIds array by removing the operator id.
for (uint256 idx = 0; idx < operatorIds.length - 1; idx++) {
if (_operatorId == operatorIds[idx]) {
operatorIds[idx] = operatorIds[operatorIds.length - 1];
break;
}
}
operatorIds.pop();
totalNodeOperators--;
IValidatorFactory(validatorFactory).remove(no.validatorProxy);
delete operatorOwners[no.rewardAddress];
delete operators[_operatorId];
emit RemoveOperator(_operatorId);
}
/// @notice Allows a validator that was already staked on the polygon stake manager
/// to join the PoLido protocol.
function joinOperator() external override whenNotPaused {
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
checkCondition(
getOperatorStatus(no) == NodeOperatorStatus.INACTIVE,
"Invalid status"
);
IStakeManager sm = IStakeManager(stakeManager);
uint256 validatorId = sm.getValidatorId(msg.sender);
checkCondition(validatorId != 0, "ValidatorId=0");
IStakeManager.Validator memory poValidator = sm.validators(validatorId);
checkCondition(
poValidator.contractAddress != address(0),
"Validator has no ValidatorShare"
);
checkCondition(
(poValidator.status == IStakeManager.Status.Active
) && poValidator.deactivationEpoch == 0 ,
"Validator isn't ACTIVE"
);
checkCondition(
poValidator.signer ==
address(uint160(uint256(keccak256(no.signerPubkey)))),
"Invalid Signer"
);
IValidator(no.validatorProxy).join(
validatorId,
sm.NFTContract(),
msg.sender,
no.commissionRate,
stakeManager
);
no.validatorId = validatorId;
address validatorShare = sm.getValidatorContract(validatorId);
no.validatorShare = validatorShare;
emit JoinOperator(operatorId);
}
/// ------------------------Stake Manager API-------------------------------
/// @notice Allows to stake a validator on the Polygon stakeManager contract.
/// @dev The stake func allows each operator's owner to stake, but before that,
/// the owner has to approve the amount + Heimdall fees to the ValidatorProxy.
/// At the end of this call, the status of the operator is set to ACTIVE.
/// @param _amount amount to stake.
/// @param _heimdallFee heimdall fees.
function stake(uint256 _amount, uint256 _heimdallFee)
external
override
whenNotPaused
checkStakeAmount(_amount)
checkHeimdallFees(_heimdallFee)
{
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
checkCondition(
getOperatorStatus(no) == NodeOperatorStatus.INACTIVE,
"Invalid status"
);
(uint256 validatorId, address validatorShare) = IValidator(
no.validatorProxy
).stake(
msg.sender,
_amount,
_heimdallFee,
true,
no.signerPubkey,
no.commissionRate,
stakeManager,
polygonERC20
);
no.validatorId = validatorId;
no.validatorShare = validatorShare;
emit StakeOperator(operatorId, _amount, _heimdallFee);
}
/// @notice Allows to restake Matics to Polygon stakeManager
/// @dev restake allows an operator's owner to increase the total staked amount
/// on Polygon. The owner has to approve the amount to the ValidatorProxy then make
/// a call.
/// @param _amount amount to stake.
function restake(uint256 _amount, bool _restakeRewards)
external
override
whenNotPaused
{
checkCondition(allowsRestake, "Restake is disabled");
if (_amount == 0) {
revert("Amount is ZERO");
}
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
checkCondition(
getOperatorStatus(no) == NodeOperatorStatus.ACTIVE,
"Invalid status"
);
IValidator(no.validatorProxy).restake(
msg.sender,
no.validatorId,
_amount,
_restakeRewards,
stakeManager,
polygonERC20
);
emit RestakeOperator(operatorId, _amount, _restakeRewards);
}
/// @notice Unstake a validator from the Polygon stakeManager contract.
/// @dev when the operators's owner wants to quite the PoLido protocol he can call
/// the unstake func, in this case, the operator status is set to UNSTAKED.
function unstake() external override whenNotPaused {
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
NodeOperatorStatus status = getOperatorStatus(no);
checkCondition(
status == NodeOperatorStatus.ACTIVE ||
status == NodeOperatorStatus.JAILED ||
status == NodeOperatorStatus.EJECTED,
"Invalid status"
);
if (status == NodeOperatorStatus.ACTIVE) {
IValidator(no.validatorProxy).unstake(no.validatorId, stakeManager);
}
_unstake(operatorId, no);
}
/// @notice The DAO unstake the operator if it was unstaked by the stakeManager.
/// @dev when the operator was unstaked by the stage Manager the DAO can use this
/// function to update the operator status and also withdraw the delegated tokens,
/// without waiting for the owner to call the unstake function
/// @param _operatorId operator id.
function unstake(uint256 _operatorId) external userHasRole(DAO_ROLE) {
NodeOperator storage no = operators[_operatorId];
NodeOperatorStatus status = getOperatorStatus(no);
checkCondition(status == NodeOperatorStatus.EJECTED, "Invalid status");
_unstake(_operatorId, no);
}
function _unstake(uint256 _operatorId, NodeOperator storage no)
private
whenNotPaused
{
IStMATIC(stMATIC).withdrawTotalDelegated(no.validatorShare);
no.status = NodeOperatorStatus.UNSTAKED;
emit UnstakeOperator(_operatorId);
}
/// @notice Allows the operator's owner to migrate the validator ownership to rewardAddress.
/// This can be done only in the case where this operator was stopped by the DAO.
function migrate() external override nonReentrant {
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
checkCondition(no.status == NodeOperatorStatus.STOPPED, "Invalid status");
IValidator(no.validatorProxy).migrate(
no.validatorId,
IStakeManager(stakeManager).NFTContract(),
no.rewardAddress
);
no.status = NodeOperatorStatus.EXIT;
emit MigrateOperator(operatorId);
}
/// @notice Allows to unjail the validator and turn his status from UNSTAKED to ACTIVE.
/// @dev when an operator is JAILED the owner can switch back and stake the
/// operator by calling the unjail func, in this case, the operator status is set
/// to back ACTIVE.
function unjail() external override whenNotPaused {
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
checkCondition(
getOperatorStatus(no) == NodeOperatorStatus.JAILED,
"Invalid status"
);
IValidator(no.validatorProxy).unjail(no.validatorId, stakeManager);
emit Unjail(operatorId);
}
/// @notice Allows to top up heimdall fees.
/// @dev the operator's owner can topUp the heimdall fees by calling the
/// topUpForFee, but before that node operator needs to approve the amount of heimdall
/// fees to his validatorProxy.
/// @param _heimdallFee amount
function topUpForFee(uint256 _heimdallFee)
external
override
whenNotPaused
checkHeimdallFees(_heimdallFee)
{
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
checkCondition(
getOperatorStatus(no) == NodeOperatorStatus.ACTIVE,
"Invalid status"
);
IValidator(no.validatorProxy).topUpForFee(
msg.sender,
_heimdallFee,
stakeManager,
polygonERC20
);
emit TopUpHeimdallFees(operatorId, _heimdallFee);
}
/// @notice Allows to unstake staked tokens after withdraw delay.
/// @dev after the unstake the operator and waiting for the Polygon withdraw_delay
/// the owner can transfer back his staked balance by calling
/// unsttakeClaim, after that the operator status is set to CLAIMED
function unstakeClaim() external override whenNotPaused {
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
checkCondition(
getOperatorStatus(no) == NodeOperatorStatus.UNSTAKED,
"Invalid status"
);
uint256 amount = IValidator(no.validatorProxy).unstakeClaim(
no.validatorId,
msg.sender,
stakeManager,
polygonERC20
);
no.status = NodeOperatorStatus.CLAIMED;
emit UnstakeClaim(operatorId, amount);
}
/// @notice Allows withdraw heimdall fees
/// @dev the operator's owner can claim the heimdall fees.
/// func, after that the operator status is set to EXIT.
/// @param _accumFeeAmount accumulated heimdall fees
/// @param _index index
/// @param _proof proof
function claimFee(
uint256 _accumFeeAmount,
uint256 _index,
bytes memory _proof
) external override whenNotPaused {
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
checkCondition(
no.status == NodeOperatorStatus.CLAIMED,
"Invalid status"
);
IValidator(no.validatorProxy).claimFee(
_accumFeeAmount,
_index,
_proof,
no.rewardAddress,
stakeManager,
polygonERC20
);
no.status = NodeOperatorStatus.EXIT;
emit ClaimFee(operatorId);
}
/// @notice Allows the operator's owner to withdraw rewards.
function withdrawRewards() external override whenNotPaused {
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
checkCondition(
getOperatorStatus(no) == NodeOperatorStatus.ACTIVE,
"Invalid status"
);
address rewardAddress = no.rewardAddress;
uint256 rewards = IValidator(no.validatorProxy).withdrawRewards(
no.validatorId,
rewardAddress,
stakeManager,
polygonERC20
);
emit WithdrawRewards(operatorId, rewardAddress, rewards);
}
/// @notice Allows the operator's owner to update signer publickey.
/// @param _signerPubkey new signer publickey
function updateSigner(bytes memory _signerPubkey)
external
override
whenNotPaused
{
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
NodeOperatorStatus status = getOperatorStatus(no);
checkCondition(
status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.INACTIVE,
"Invalid status"
);
if (no.status == NodeOperatorStatus.ACTIVE) {
IValidator(no.validatorProxy).updateSigner(
no.validatorId,
_signerPubkey,
stakeManager
);
}
no.signerPubkey = _signerPubkey;
emit UpdateSignerPubkey(operatorId);
}
/// @notice Allows the operator owner to update the name.
/// @param _name new operator name.
function setOperatorName(string memory _name)
external
override
whenNotPaused
{
// uint256 operatorId = getOperatorId(msg.sender);
// NodeOperator storage no = operators[operatorId];
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
NodeOperatorStatus status = getOperatorStatus(no);
checkCondition(
status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.INACTIVE,
"Invalid status"
);
no.name = _name;
emit NewName(operatorId, _name);
}
/// @notice Allows the operator owner to update the rewardAddress.
/// @param _rewardAddress new reward address.
function setOperatorRewardAddress(address _rewardAddress)
external
override
whenNotPaused
checkIfRewardAddressIsUsed(_rewardAddress)
{
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
no.rewardAddress = _rewardAddress;
operatorOwners[_rewardAddress] = operatorId;
delete operatorOwners[msg.sender];
emit NewRewardAddress(operatorId, _rewardAddress);
}
/// -------------------------------DAO--------------------------------------
/// @notice Allows the DAO to set the operator defaultMaxDelegateLimit.
/// @param _defaultMaxDelegateLimit default max delegation amount.
function setDefaultMaxDelegateLimit(uint256 _defaultMaxDelegateLimit)
external
override
userHasRole(DAO_ROLE)
checkMaxDelegationLimit(_defaultMaxDelegateLimit)
{
defaultMaxDelegateLimit = _defaultMaxDelegateLimit;
}
/// @notice Allows the DAO to set the operator maxDelegateLimit.
/// @param _operatorId operator id.
/// @param _maxDelegateLimit max amount to delegate .
function setMaxDelegateLimit(uint256 _operatorId, uint256 _maxDelegateLimit)
external
override
userHasRole(DAO_ROLE)
checkMaxDelegationLimit(_maxDelegateLimit)
{
(, NodeOperator storage no) = getOperator(_operatorId);
no.maxDelegateLimit = _maxDelegateLimit;
}
/// @notice Allows to set the commission rate used.
function setCommissionRate(uint256 _commissionRate)
external
override
userHasRole(DAO_ROLE)
{
commissionRate = _commissionRate;
}
/// @notice Allows the dao to update commission rate for an operator.
/// @param _operatorId id of the operator
/// @param _newCommissionRate new commission rate
function updateOperatorCommissionRate(
uint256 _operatorId,
uint256 _newCommissionRate
) external override userHasRole(DAO_ROLE) {
(, NodeOperator storage no) = getOperator(_operatorId);
checkCondition(
no.rewardAddress != address(0) ||
no.status == NodeOperatorStatus.ACTIVE,
"Invalid status"
);
if (no.status == NodeOperatorStatus.ACTIVE) {
IValidator(no.validatorProxy).updateCommissionRate(
no.validatorId,
_newCommissionRate,
stakeManager
);
}
no.commissionRate = _newCommissionRate;
emit UpdateCommissionRate(_operatorId, _newCommissionRate);
}
/// @notice Allows to update the stake amount and heimdall fees
/// @param _minAmountStake min amount to stake
/// @param _minHeimdallFees min amount of heimdall fees
function setStakeAmountAndFees(
uint256 _minAmountStake,
uint256 _minHeimdallFees
)
external
override
userHasRole(DAO_ROLE)
checkStakeAmount(_minAmountStake)
checkHeimdallFees(_minHeimdallFees)
{
minAmountStake = _minAmountStake;
minHeimdallFees = _minHeimdallFees;
}
/// @notice Allows to pause the contract.
function togglePause() external override userHasRole(PAUSE_OPERATOR_ROLE) {
paused() ? _unpause() : _pause();
}
/// @notice Allows to toggle restake.
function setRestake(bool _restake) external override userHasRole(DAO_ROLE) {
allowsRestake = _restake;
}
/// @notice Allows to set the StMATIC contract address.
function setStMATIC(address _stMATIC)
external
override
userHasRole(DAO_ROLE)
{
stMATIC = _stMATIC;
}
/// @notice Allows to set the validator factory contract address.
function setValidatorFactory(address _validatorFactory)
external
override
userHasRole(DAO_ROLE)
{
validatorFactory = _validatorFactory;
}
/// @notice Allows to set the stake manager contract address.
function setStakeManager(address _stakeManager)
external
override
userHasRole(DAO_ROLE)
{
stakeManager = _stakeManager;
}
/// @notice Allows to set the contract version.
/// @param _version contract version
function setVersion(string memory _version)
external
override
userHasRole(DEFAULT_ADMIN_ROLE)
{
version = _version;
}
/// @notice Allows to get a node operator by msg.sender.
/// @param _owner a valid address of an operator owner, if not set msg.sender will be used.
/// @return op returns a node operator.
function getNodeOperator(address _owner)
external
view
returns (NodeOperator memory)
{
uint256 operatorId = operatorOwners[_owner];
return _getNodeOperator(operatorId);
}
/// @notice Allows to get a node operator by _operatorId.
/// @param _operatorId the id of the operator.
/// @return op returns a node operator.
function getNodeOperator(uint256 _operatorId)
external
view
returns (NodeOperator memory)
{
return _getNodeOperator(_operatorId);
}
function _getNodeOperator(uint256 _operatorId)
private
view
returns (NodeOperator memory)
{
(, NodeOperator memory nodeOperator) = getOperator(_operatorId);
nodeOperator.status = getOperatorStatus(nodeOperator);
return nodeOperator;
}
function getOperatorStatus(NodeOperator memory _op)
private
view
returns (NodeOperatorStatus res)
{
if (_op.status == NodeOperatorStatus.STOPPED) {
res = NodeOperatorStatus.STOPPED;
} else if (_op.status == NodeOperatorStatus.CLAIMED) {
res = NodeOperatorStatus.CLAIMED;
} else if (_op.status == NodeOperatorStatus.EXIT) {
res = NodeOperatorStatus.EXIT;
} else if (_op.status == NodeOperatorStatus.UNSTAKED) {
res = NodeOperatorStatus.UNSTAKED;
} else {
IStakeManager.Validator memory v = IStakeManager(stakeManager)
.validators(_op.validatorId);
if (
v.status == IStakeManager.Status.Active &&
v.deactivationEpoch == 0
) {
res = NodeOperatorStatus.ACTIVE;
} else if (
(
v.status == IStakeManager.Status.Active ||
v.status == IStakeManager.Status.Locked
) &&
v.deactivationEpoch != 0
) {
res = NodeOperatorStatus.EJECTED;
} else if (
v.status == IStakeManager.Status.Locked &&
v.deactivationEpoch == 0
) {
res = NodeOperatorStatus.JAILED;
} else {
res = NodeOperatorStatus.INACTIVE;
}
}
}
/// @notice Allows to get a validator share address.
/// @param _operatorId the id of the operator.
/// @return va returns a stake manager validator.
function getValidatorShare(uint256 _operatorId)
external
view
returns (address)
{
(, NodeOperator memory op) = getOperator(_operatorId);
return op.validatorShare;
}
/// @notice Allows to get a validator from stake manager.
/// @param _operatorId the id of the operator.
/// @return va returns a stake manager validator.
function getValidator(uint256 _operatorId)
external
view
returns (IStakeManager.Validator memory va)
{
(, NodeOperator memory op) = getOperator(_operatorId);
va = IStakeManager(stakeManager).validators(op.validatorId);
}
/// @notice Allows to get a validator from stake manager.
/// @param _owner user address.
/// @return va returns a stake manager validator.
function getValidator(address _owner)
external
view
returns (IStakeManager.Validator memory va)
{
(, NodeOperator memory op) = getOperator(operatorOwners[_owner]);
va = IStakeManager(stakeManager).validators(op.validatorId);
}
/// @notice Get the stMATIC contract addresses
function getContracts()
external
view
override
returns (
address _validatorFactory,
address _stakeManager,
address _polygonERC20,
address _stMATIC
)
{
_validatorFactory = validatorFactory;
_stakeManager = stakeManager;
_polygonERC20 = polygonERC20;
_stMATIC = stMATIC;
}
/// @notice Get the global state
function getState()
external
view
override
returns (
uint256 _totalNodeOperator,
uint256 _totalInactiveNodeOperator,
uint256 _totalActiveNodeOperator,
uint256 _totalStoppedNodeOperator,
uint256 _totalUnstakedNodeOperator,
uint256 _totalClaimedNodeOperator,
uint256 _totalExitNodeOperator,
uint256 _totalJailedNodeOperator,
uint256 _totalEjectedNodeOperator
)
{
uint256 operatorIdsLength = operatorIds.length;
_totalNodeOperator = operatorIdsLength;
for (uint256 idx = 0; idx < operatorIdsLength; idx++) {
uint256 operatorId = operatorIds[idx];
NodeOperator memory op = operators[operatorId];
NodeOperatorStatus status = getOperatorStatus(op);
if (status == NodeOperatorStatus.INACTIVE) {
_totalInactiveNodeOperator++;
} else if (status == NodeOperatorStatus.ACTIVE) {
_totalActiveNodeOperator++;
} else if (status == NodeOperatorStatus.STOPPED) {
_totalStoppedNodeOperator++;
} else if (status == NodeOperatorStatus.UNSTAKED) {
_totalUnstakedNodeOperator++;
} else if (status == NodeOperatorStatus.CLAIMED) {
_totalClaimedNodeOperator++;
} else if (status == NodeOperatorStatus.JAILED) {
_totalJailedNodeOperator++;
} else if (status == NodeOperatorStatus.EJECTED) {
_totalEjectedNodeOperator++;
} else {
_totalExitNodeOperator++;
}
}
}
/// @notice Get operatorIds.
function getOperatorIds()
external
view
override
returns (uint256[] memory)
{
return operatorIds;
}
/// @notice Returns an operatorInfo list.
/// @param _allWithStake if true return all operators with ACTIVE, EJECTED, JAILED.
/// @param _delegation if true return all operators that delegation is set to true.
/// @return Returns a list of operatorInfo.
function getOperatorInfos(
bool _delegation,
bool _allWithStake
) external view override returns (Operator.OperatorInfo[] memory) {
Operator.OperatorInfo[]
memory operatorInfos = new Operator.OperatorInfo[](
totalNodeOperators
);
uint256 length = operatorIds.length;
uint256 index;
for (uint256 idx = 0; idx < length; idx++) {
uint256 operatorId = operatorIds[idx];
NodeOperator storage no = operators[operatorId];
NodeOperatorStatus status = getOperatorStatus(no);
// if operator status is not ACTIVE we continue. But, if _allWithStake is true
// we include EJECTED and JAILED operators.
if (
status != NodeOperatorStatus.ACTIVE &&
!(_allWithStake &&
(status == NodeOperatorStatus.EJECTED ||
status == NodeOperatorStatus.JAILED))
) continue;
// if true we check if the operator delegation is true.
if (_delegation) {
if (!IValidatorShare(no.validatorShare).delegation()) continue;
}
operatorInfos[index] = Operator.OperatorInfo({
operatorId: operatorId,
validatorShare: no.validatorShare,
maxDelegateLimit: no.maxDelegateLimit,
rewardAddress: no.rewardAddress
});
index++;
}
if (index != totalNodeOperators) {
Operator.OperatorInfo[]
memory operatorInfosOut = new Operator.OperatorInfo[](index);
for (uint256 i = 0; i < index; i++) {
operatorInfosOut[i] = operatorInfos[i];
}
return operatorInfosOut;
}
return operatorInfos;
}
/// @notice Checks condition and displays the message
/// @param _condition a condition
/// @param _message message to display
function checkCondition(bool _condition, string memory _message)
private
pure
{
require(_condition, _message);
}
/// @notice Retrieve the operator struct based on the operatorId
/// @param _operatorId id of the operator
/// @return NodeOperator structure
function getOperator(uint256 _operatorId)
private
view
returns (uint256, NodeOperator storage)
{
if (_operatorId == 0) {
_operatorId = getOperatorId(msg.sender);
}
NodeOperator storage no = operators[_operatorId];
require(no.rewardAddress != address(0), "Operator not found");
return (_operatorId, no);
}
/// @notice Retrieve the operator struct based on the operator owner address
/// @param _user address of the operator owner
/// @return NodeOperator structure
function getOperatorId(address _user) private view returns (uint256) {
uint256 operatorId = operatorOwners[_user];
checkCondition(operatorId != 0, "Operator not found");
return operatorId;
}
/// -------------------------------Events-----------------------------------
/// @notice A new node operator was added.
/// @param operatorId node operator id.
event AddOperator(uint256 operatorId);
/// @notice A new node operator joined.
/// @param operatorId node operator id.
event JoinOperator(uint256 operatorId);
/// @notice A node operator was removed.
/// @param operatorId node operator id.
event RemoveOperator(uint256 operatorId);
/// @param operatorId node operator id.
event StopOperator(uint256 operatorId);
/// @param operatorId node operator id.
event MigrateOperator(uint256 operatorId);
/// @notice A node operator was staked.
/// @param operatorId node operator id.
event StakeOperator(
uint256 operatorId,
uint256 amount,
uint256 heimdallFees
);
/// @notice A node operator restaked.
/// @param operatorId node operator id.
/// @param amount amount to restake.
/// @param restakeRewards restake rewards.
event RestakeOperator(
uint256 operatorId,
uint256 amount,
bool restakeRewards
);
/// @notice A node operator was unstaked.
/// @param operatorId node operator id.
event UnstakeOperator(uint256 operatorId);
/// @notice TopUp heimadall fees.
/// @param operatorId node operator id.
/// @param amount amount.
event TopUpHeimdallFees(uint256 operatorId, uint256 amount);
/// @notice Withdraw rewards.
/// @param operatorId node operator id.
/// @param rewardAddress reward address.
/// @param amount amount.
event WithdrawRewards(
uint256 operatorId,
address rewardAddress,
uint256 amount
);
/// @notice claims unstake.
/// @param operatorId node operator id.
/// @param amount amount.
event UnstakeClaim(uint256 operatorId, uint256 amount);
/// @notice update signer publickey.
/// @param operatorId node operator id.
event UpdateSignerPubkey(uint256 operatorId);
/// @notice claim herimdall fee.
/// @param operatorId node operator id.
event ClaimFee(uint256 operatorId);
/// @notice update commission rate.
event UpdateCommissionRate(uint256 operatorId, uint256 newCommissionRate);
/// @notice Unjail a validator.
event Unjail(uint256 operatorId);
/// @notice update operator name.
event NewName(uint256 operatorId, string name);
/// @notice update operator name.
event NewRewardAddress(uint256 operatorId, address rewardAddress);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/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 onlyInitializing {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_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
// OpenZeppelin Contracts v4.4.1 (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 {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
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 override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been 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());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/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 onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_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;
}
uint256[49] private __gap;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "../lib/Operator.sol";
/// @title INodeOperatorRegistry
/// @author 2021 ShardLabs
/// @notice Node operator registry interface
interface INodeOperatorRegistry {
/// @notice Allows to add a new node operator to the system.
/// @param _name the node operator name.
/// @param _rewardAddress public address used for ACL and receive rewards.
/// @param _signerPubkey public key used on heimdall len 64 bytes.
function addOperator(
string memory _name,
address _rewardAddress,
bytes memory _signerPubkey
) external;
/// @notice Allows to stop a node operator.
/// @param _operatorId node operator id.
function stopOperator(uint256 _operatorId) external;
/// @notice Allows to remove a node operator from the system.
/// @param _operatorId node operator id.
function removeOperator(uint256 _operatorId) external;
/// @notice Allows a staked validator to join the system.
function joinOperator() external;
/// @notice Allows to stake an operator on the Polygon stakeManager.
/// This function calls Polygon transferFrom so the totalAmount(_amount + _heimdallFee)
/// has to be approved first.
/// @param _amount amount to stake.
/// @param _heimdallFee heimdallFee to stake.
function stake(uint256 _amount, uint256 _heimdallFee) external;
/// @notice Restake Matics for a validator on polygon stake manager.
/// @param _amount amount to stake.
/// @param _restakeRewards restake rewards.
function restake(uint256 _amount, bool _restakeRewards) external;
/// @notice Allows the operator's owner to migrate the NFT. This can be done only
/// if the DAO stopped the operator.
function migrate() external;
/// @notice Allows to unstake an operator from the stakeManager. After the withdraw_delay
/// the operator owner can call claimStake func to withdraw the staked tokens.
function unstake() external;
/// @notice Allows to topup heimdall fees on polygon stakeManager.
/// @param _heimdallFee amount to topup.
function topUpForFee(uint256 _heimdallFee) external;
/// @notice Allows to claim staked tokens on the stake Manager after the end of the
/// withdraw delay
function unstakeClaim() external;
/// @notice Allows an owner to withdraw rewards from the stakeManager.
function withdrawRewards() external;
/// @notice Allows to update the signer pubkey
/// @param _signerPubkey update signer public key
function updateSigner(bytes memory _signerPubkey) external;
/// @notice Allows to claim the heimdall fees staked by the owner of the operator
/// @param _accumFeeAmount accumulated fees amount
/// @param _index index
/// @param _proof proof
function claimFee(
uint256 _accumFeeAmount,
uint256 _index,
bytes memory _proof
) external;
/// @notice Allows to unjail a validator and switch from UNSTAKE status to STAKED
function unjail() external;
/// @notice Allows an operator's owner to set the operator name.
function setOperatorName(string memory _name) external;
/// @notice Allows an operator's owner to set the operator rewardAddress.
function setOperatorRewardAddress(address _rewardAddress) external;
/// @notice Allows the DAO to set _defaultMaxDelegateLimit.
function setDefaultMaxDelegateLimit(uint256 _defaultMaxDelegateLimit)
external;
/// @notice Allows the DAO to set _maxDelegateLimit for an operator.
function setMaxDelegateLimit(uint256 _operatorId, uint256 _maxDelegateLimit)
external;
/// @notice Allows the DAO to set _commissionRate.
function setCommissionRate(uint256 _commissionRate) external;
/// @notice Allows the DAO to set _commissionRate for an operator.
/// @param _operatorId id of the operator
/// @param _newCommissionRate new commission rate
function updateOperatorCommissionRate(
uint256 _operatorId,
uint256 _newCommissionRate
) external;
/// @notice Allows the DAO to set _minAmountStake and _minHeimdallFees.
function setStakeAmountAndFees(
uint256 _minAmountStake,
uint256 _minHeimdallFees
) external;
/// @notice Allows to pause/unpause the node operator contract.
function togglePause() external;
/// @notice Allows the DAO to enable/disable restake.
function setRestake(bool _restake) external;
/// @notice Allows the DAO to set stMATIC contract.
function setStMATIC(address _stMATIC) external;
/// @notice Allows the DAO to set validator factory contract.
function setValidatorFactory(address _validatorFactory) external;
/// @notice Allows the DAO to set stake manager contract.
function setStakeManager(address _stakeManager) external;
/// @notice Allows to set contract version.
function setVersion(string memory _version) external;
/// @notice Get the stMATIC contract addresses
function getContracts()
external
view
returns (
address _validatorFactory,
address _stakeManager,
address _polygonERC20,
address _stMATIC
);
/// @notice Allows to get stats.
function getState()
external
view
returns (
uint256 _totalNodeOperator,
uint256 _totalInactiveNodeOperator,
uint256 _totalActiveNodeOperator,
uint256 _totalStoppedNodeOperator,
uint256 _totalUnstakedNodeOperator,
uint256 _totalClaimedNodeOperator,
uint256 _totalExitNodeOperator,
uint256 _totalSlashedNodeOperator,
uint256 _totalEjectedNodeOperator
);
/// @notice Allows to get a list of operatorInfo.
function getOperatorInfos(bool _delegation, bool _allActive)
external
view
returns (Operator.OperatorInfo[] memory);
/// @notice Allows to get all the operator ids.
function getOperatorIds() external view returns (uint256[] memory);
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "../Validator.sol";
/// @title IValidatorFactory.
/// @author 2021 ShardLabs
interface IValidatorFactory {
/// @notice Deploy a new validator proxy contract.
/// @return return the address of the deployed contract.
function create() external returns (address);
/// @notice Remove a validator proxy from the validators.
function remove(address _validatorProxy) external;
/// @notice Set the node operator contract address.
function setOperator(address _operator) external;
/// @notice Set validator implementation contract address.
function setValidatorImplementation(address _validatorImplementation)
external;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "../Validator.sol";
/// @title IValidator.
/// @author 2021 ShardLabs
/// @notice Validator interface.
interface IValidator {
/// @notice Allows to stake a validator on the Polygon stakeManager contract.
/// @dev Stake a validator on the Polygon stakeManager contract.
/// @param _sender msg.sender.
/// @param _amount amount to stake.
/// @param _heimdallFee herimdall fees.
/// @param _acceptDelegation accept delegation.
/// @param _signerPubkey signer public key used on the heimdall.
/// @param _commisionRate commision rate of a validator
function stake(
address _sender,
uint256 _amount,
uint256 _heimdallFee,
bool _acceptDelegation,
bytes memory _signerPubkey,
uint256 _commisionRate,
address stakeManager,
address polygonERC20
) external returns (uint256, address);
/// @notice Restake Matics for a validator on polygon stake manager.
/// @param sender operator owner which approved tokens to the validato contract.
/// @param validatorId validator id.
/// @param amount amount to stake.
/// @param stakeRewards restake rewards.
/// @param stakeManager stake manager address
/// @param polygonERC20 address of the MATIC token
function restake(
address sender,
uint256 validatorId,
uint256 amount,
bool stakeRewards,
address stakeManager,
address polygonERC20
) external;
/// @notice Unstake a validator from the Polygon stakeManager contract.
/// @dev Unstake a validator from the Polygon stakeManager contract by passing the validatorId
/// @param _validatorId validatorId.
/// @param _stakeManager address of the stake manager
function unstake(uint256 _validatorId, address _stakeManager) external;
/// @notice Allows to top up heimdall fees.
/// @param _heimdallFee amount
/// @param _sender msg.sender
/// @param _stakeManager stake manager address
/// @param _polygonERC20 address of the MATIC token
function topUpForFee(
address _sender,
uint256 _heimdallFee,
address _stakeManager,
address _polygonERC20
) external;
/// @notice Allows to withdraw rewards from the validator.
/// @dev Allows to withdraw rewards from the validator using the _validatorId. Only the
/// owner can request withdraw in this the owner is this contract.
/// @param _validatorId validator id.
/// @param _rewardAddress user address used to transfer the staked tokens.
/// @param _stakeManager stake manager address
/// @param _polygonERC20 address of the MATIC token
/// @return Returns the amount transfered to the user.
function withdrawRewards(
uint256 _validatorId,
address _rewardAddress,
address _stakeManager,
address _polygonERC20
) external returns (uint256);
/// @notice Allows to claim staked tokens on the stake Manager after the end of the
/// withdraw delay
/// @param _validatorId validator id.
/// @param _rewardAddress user address used to transfer the staked tokens.
/// @return Returns the amount transfered to the user.
function unstakeClaim(
uint256 _validatorId,
address _rewardAddress,
address _stakeManager,
address _polygonERC20
) external returns (uint256);
/// @notice Allows to update the signer pubkey
/// @param _validatorId validator id
/// @param _signerPubkey update signer public key
/// @param _stakeManager stake manager address
function updateSigner(
uint256 _validatorId,
bytes memory _signerPubkey,
address _stakeManager
) external;
/// @notice Allows to claim the heimdall fees.
/// @param _accumFeeAmount accumulated fees amount
/// @param _index index
/// @param _proof proof
/// @param _ownerRecipient owner recipient
/// @param _stakeManager stake manager address
/// @param _polygonERC20 address of the MATIC token
function claimFee(
uint256 _accumFeeAmount,
uint256 _index,
bytes memory _proof,
address _ownerRecipient,
address _stakeManager,
address _polygonERC20
) external;
/// @notice Allows to update the commision rate of a validator
/// @param _validatorId operator id
/// @param _newCommissionRate commission rate
/// @param _stakeManager stake manager address
function updateCommissionRate(
uint256 _validatorId,
uint256 _newCommissionRate,
address _stakeManager
) external;
/// @notice Allows to unjail a validator.
/// @param _validatorId operator id
function unjail(uint256 _validatorId, address _stakeManager) external;
/// @notice Allows to migrate the ownership to an other user.
/// @param _validatorId operator id.
/// @param _stakeManagerNFT stake manager nft contract.
/// @param _rewardAddress reward address.
function migrate(
uint256 _validatorId,
address _stakeManagerNFT,
address _rewardAddress
) external;
/// @notice Allows a validator that was already staked on the polygon stake manager
/// to join the PoLido protocol.
/// @param _validatorId validator id
/// @param _stakeManagerNFT address of the staking NFT
/// @param _rewardAddress address that will receive the rewards from staking
/// @param _newCommissionRate commission rate
/// @param _stakeManager address of the stake manager
function join(
uint256 _validatorId,
address _stakeManagerNFT,
address _rewardAddress,
uint256 _newCommissionRate,
address _stakeManager
) external;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./IValidatorShare.sol";
import "./INodeOperatorRegistry.sol";
import "./INodeOperatorRegistry.sol";
import "./IStakeManager.sol";
import "./IPoLidoNFT.sol";
import "./IFxStateRootTunnel.sol";
/// @title StMATIC interface.
/// @author 2021 ShardLabs
interface IStMATIC is IERC20Upgradeable {
struct RequestWithdraw {
uint256 amount2WithdrawFromStMATIC;
uint256 validatorNonce;
uint256 requestEpoch;
address validatorAddress;
}
struct FeeDistribution {
uint8 dao;
uint8 operators;
uint8 insurance;
}
function withdrawTotalDelegated(address _validatorShare) external;
function nodeOperatorRegistry() external returns (INodeOperatorRegistry);
function entityFees()
external
returns (
uint8,
uint8,
uint8
);
function getMaticFromTokenId(uint256 _tokenId)
external
view
returns (uint256);
function stakeManager() external view returns (IStakeManager);
function poLidoNFT() external view returns (IPoLidoNFT);
function fxStateRootTunnel() external view returns (IFxStateRootTunnel);
function version() external view returns (string memory);
function dao() external view returns (address);
function insurance() external view returns (address);
function token() external view returns (address);
function lastWithdrawnValidatorId() external view returns (uint256);
function totalBuffered() external view returns (uint256);
function delegationLowerBound() external view returns (uint256);
function rewardDistributionLowerBound() external view returns (uint256);
function reservedFunds() external view returns (uint256);
function submitThreshold() external view returns (uint256);
function submitHandler() external view returns (bool);
function getMinValidatorBalance() external view returns (uint256);
function token2WithdrawRequest(uint256 _requestId)
external
view
returns (
uint256,
uint256,
uint256,
address
);
function DAO() external view returns (bytes32);
function initialize(
address _nodeOperatorRegistry,
address _token,
address _dao,
address _insurance,
address _stakeManager,
address _poLidoNFT,
address _fxStateRootTunnel,
uint256 _submitThreshold
) external;
function submit(uint256 _amount) external returns (uint256);
function requestWithdraw(uint256 _amount) external;
function delegate() external;
function claimTokens(uint256 _tokenId) external;
function distributeRewards() external;
function claimTokens2StMatic(uint256 _tokenId) external;
function togglePause() external;
function getTotalStake(IValidatorShare _validatorShare)
external
view
returns (uint256, uint256);
function getLiquidRewards(IValidatorShare _validatorShare)
external
view
returns (uint256);
function getTotalStakeAcrossAllValidators() external view returns (uint256);
function getTotalPooledMatic() external view returns (uint256);
function convertStMaticToMatic(uint256 _balance)
external
view
returns (
uint256,
uint256,
uint256
);
function convertMaticToStMatic(uint256 _balance)
external
view
returns (
uint256,
uint256,
uint256
);
function setFees(
uint8 _daoFee,
uint8 _operatorsFee,
uint8 _insuranceFee
) external;
function setDaoAddress(address _address) external;
function setInsuranceAddress(address _address) external;
function setNodeOperatorRegistryAddress(address _address) external;
function setDelegationLowerBound(uint256 _delegationLowerBound) external;
function setRewardDistributionLowerBound(
uint256 _rewardDistributionLowerBound
) external;
function setPoLidoNFT(address _poLidoNFT) external;
function setFxStateRootTunnel(address _fxStateRootTunnel) external;
function setSubmitThreshold(uint256 _submitThreshold) external;
function flipSubmitHandler() external;
function setVersion(string calldata _version) external;
}
// 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 {
__Context_init_unchained();
}
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;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^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;
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 Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface 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 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 {
__ERC165_init_unchained();
}
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;
}
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-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
library Operator {
struct OperatorInfo {
uint256 operatorId;
address validatorShare;
uint256 maxDelegateLimit;
address rewardAddress;
}
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "./interfaces/IStakeManager.sol";
import "./interfaces/IValidator.sol";
import "./interfaces/INodeOperatorRegistry.sol";
/// @title ValidatorImplementation
/// @author 2021 ShardLabs.
/// @notice The validator contract is a simple implementation of the stakeManager API, the
/// ValidatorProxies use this contract to interact with the stakeManager.
/// When a ValidatorProxy calls this implementation the state is copied
/// (owner, implementation, operatorRegistry), then they are used to check if the msg-sender is the
/// node operator contract, and if the validatorProxy implementation match with the current
/// validator contract.
contract Validator is IERC721Receiver, IValidator {
using SafeERC20 for IERC20;
address private implementation;
address private operatorRegistry;
address private validatorFactory;
/// @notice Check if the operator contract is the msg.sender.
modifier isOperatorRegistry() {
require(
msg.sender == operatorRegistry,
"Caller should be the operator contract"
);
_;
}
/// @notice Allows to stake on the Polygon stakeManager contract by
/// calling stakeFor function and set the user as the equal to this validator proxy
/// address.
/// @param _sender the address of the operator-owner that approved Matics.
/// @param _amount the amount to stake with.
/// @param _heimdallFee the heimdall fees.
/// @param _acceptDelegation accept delegation.
/// @param _signerPubkey signer public key used on the heimdall node.
/// @param _commissionRate validator commision rate
/// @return Returns the validatorId and the validatorShare contract address.
function stake(
address _sender,
uint256 _amount,
uint256 _heimdallFee,
bool _acceptDelegation,
bytes memory _signerPubkey,
uint256 _commissionRate,
address _stakeManager,
address _polygonERC20
) external override isOperatorRegistry returns (uint256, address) {
IStakeManager stakeManager = IStakeManager(_stakeManager);
IERC20 polygonERC20 = IERC20(_polygonERC20);
uint256 totalAmount = _amount + _heimdallFee;
polygonERC20.safeTransferFrom(_sender, address(this), totalAmount);
polygonERC20.safeApprove(address(stakeManager), totalAmount);
stakeManager.stakeFor(
address(this),
_amount,
_heimdallFee,
_acceptDelegation,
_signerPubkey
);
uint256 validatorId = stakeManager.getValidatorId(address(this));
address validatorShare = stakeManager.getValidatorContract(validatorId);
if (_commissionRate > 0) {
stakeManager.updateCommissionRate(validatorId, _commissionRate);
}
return (validatorId, validatorShare);
}
/// @notice Restake validator rewards or new Matics validator on stake manager.
/// @param _sender operator's owner that approved tokens to the validator contract.
/// @param _validatorId validator id.
/// @param _amount amount to stake.
/// @param _stakeRewards restake rewards.
/// @param _stakeManager stake manager address
/// @param _polygonERC20 address of the MATIC token
function restake(
address _sender,
uint256 _validatorId,
uint256 _amount,
bool _stakeRewards,
address _stakeManager,
address _polygonERC20
) external override isOperatorRegistry {
if (_amount > 0) {
IERC20 polygonERC20 = IERC20(_polygonERC20);
polygonERC20.safeTransferFrom(_sender, address(this), _amount);
polygonERC20.safeApprove(address(_stakeManager), _amount);
}
IStakeManager(_stakeManager).restake(_validatorId, _amount, _stakeRewards);
}
/// @notice Unstake a validator from the Polygon stakeManager contract.
/// @param _validatorId validatorId.
/// @param _stakeManager address of the stake manager
function unstake(uint256 _validatorId, address _stakeManager)
external
override
isOperatorRegistry
{
// stakeManager
IStakeManager(_stakeManager).unstake(_validatorId);
}
/// @notice Allows a validator to top-up the heimdall fees.
/// @param _sender address that approved the _heimdallFee amount.
/// @param _heimdallFee amount.
/// @param _stakeManager stake manager address
/// @param _polygonERC20 address of the MATIC token
function topUpForFee(
address _sender,
uint256 _heimdallFee,
address _stakeManager,
address _polygonERC20
) external override isOperatorRegistry {
IStakeManager stakeManager = IStakeManager(_stakeManager);
IERC20 polygonERC20 = IERC20(_polygonERC20);
polygonERC20.safeTransferFrom(_sender, address(this), _heimdallFee);
polygonERC20.safeApprove(address(stakeManager), _heimdallFee);
stakeManager.topUpForFee(address(this), _heimdallFee);
}
/// @notice Allows to withdraw rewards from the validator using the _validatorId. Only the
/// owner can request withdraw. The rewards are transfered to the _rewardAddress.
/// @param _validatorId validator id.
/// @param _rewardAddress reward address.
/// @param _stakeManager stake manager address
/// @param _polygonERC20 address of the MATIC token
function withdrawRewards(
uint256 _validatorId,
address _rewardAddress,
address _stakeManager,
address _polygonERC20
) external override isOperatorRegistry returns (uint256) {
IStakeManager(_stakeManager).withdrawRewards(_validatorId);
IERC20 polygonERC20 = IERC20(_polygonERC20);
uint256 balance = polygonERC20.balanceOf(address(this));
polygonERC20.safeTransfer(_rewardAddress, balance);
return balance;
}
/// @notice Allows to unstake the staked tokens (+rewards) and transfer them
/// to the owner rewardAddress.
/// @param _validatorId validator id.
/// @param _rewardAddress rewardAddress address.
/// @param _stakeManager stake manager address
/// @param _polygonERC20 address of the MATIC token
function unstakeClaim(
uint256 _validatorId,
address _rewardAddress,
address _stakeManager,
address _polygonERC20
) external override isOperatorRegistry returns (uint256) {
IStakeManager stakeManager = IStakeManager(_stakeManager);
stakeManager.unstakeClaim(_validatorId);
// polygonERC20
// stakeManager
IERC20 polygonERC20 = IERC20(_polygonERC20);
uint256 balance = polygonERC20.balanceOf(address(this));
polygonERC20.safeTransfer(_rewardAddress, balance);
return balance;
}
/// @notice Allows to update signer publickey.
/// @param _validatorId validator id.
/// @param _signerPubkey new publickey.
/// @param _stakeManager stake manager address
function updateSigner(
uint256 _validatorId,
bytes memory _signerPubkey,
address _stakeManager
) external override isOperatorRegistry {
IStakeManager(_stakeManager).updateSigner(_validatorId, _signerPubkey);
}
/// @notice Allows withdraw heimdall fees.
/// @param _accumFeeAmount accumulated heimdall fees.
/// @param _index index.
/// @param _proof proof.
function claimFee(
uint256 _accumFeeAmount,
uint256 _index,
bytes memory _proof,
address _rewardAddress,
address _stakeManager,
address _polygonERC20
) external override isOperatorRegistry {
IStakeManager stakeManager = IStakeManager(_stakeManager);
stakeManager.claimFee(_accumFeeAmount, _index, _proof);
IERC20 polygonERC20 = IERC20(_polygonERC20);
uint256 balance = polygonERC20.balanceOf(address(this));
polygonERC20.safeTransfer(_rewardAddress, balance);
}
/// @notice Allows to update commission rate of a validator.
/// @param _validatorId validator id.
/// @param _newCommissionRate new commission rate.
/// @param _stakeManager stake manager address
function updateCommissionRate(
uint256 _validatorId,
uint256 _newCommissionRate,
address _stakeManager
) public override isOperatorRegistry {
IStakeManager(_stakeManager).updateCommissionRate(
_validatorId,
_newCommissionRate
);
}
/// @notice Allows to unjail a validator.
/// @param _validatorId validator id
function unjail(uint256 _validatorId, address _stakeManager)
external
override
isOperatorRegistry
{
IStakeManager(_stakeManager).unjail(_validatorId);
}
/// @notice Allows to transfer the validator nft token to the reward address a validator.
/// @param _validatorId operator id.
/// @param _stakeManagerNFT stake manager nft contract.
/// @param _rewardAddress reward address.
function migrate(
uint256 _validatorId,
address _stakeManagerNFT,
address _rewardAddress
) external override isOperatorRegistry {
IERC721 erc721 = IERC721(_stakeManagerNFT);
erc721.approve(_rewardAddress, _validatorId);
erc721.safeTransferFrom(address(this), _rewardAddress, _validatorId);
}
/// @notice Allows a validator that was already staked on the polygon stake manager
/// to join the PoLido protocol.
/// @param _validatorId validator id
/// @param _stakeManagerNFT address of the staking NFT
/// @param _rewardAddress address that will receive the rewards from staking
/// @param _newCommissionRate commission rate
/// @param _stakeManager address of the stake manager
function join(
uint256 _validatorId,
address _stakeManagerNFT,
address _rewardAddress,
uint256 _newCommissionRate,
address _stakeManager
) external override isOperatorRegistry {
IERC721 erc721 = IERC721(_stakeManagerNFT);
erc721.safeTransferFrom(_rewardAddress, address(this), _validatorId);
updateCommissionRate(_validatorId, _newCommissionRate, _stakeManager);
}
/// @notice Allows to get the version of the validator implementation.
/// @return Returns the version.
function version() external pure returns (string memory) {
return "1.0.0";
}
/// @notice Implement @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol interface.
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure override returns (bytes4) {
return
bytes4(
keccak256("onERC721Received(address,address,uint256,bytes)")
);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
/// @title polygon stake manager interface.
/// @author 2021 ShardLabs
/// @notice User to interact with the polygon stake manager.
interface IStakeManager {
/// @notice Stake a validator on polygon stake manager.
/// @param user user that own the validator in our case the validator contract.
/// @param amount amount to stake.
/// @param heimdallFee heimdall fees.
/// @param acceptDelegation accept delegation.
/// @param signerPubkey signer publickey used in heimdall node.
function stakeFor(
address user,
uint256 amount,
uint256 heimdallFee,
bool acceptDelegation,
bytes memory signerPubkey
) external;
/// @notice Restake Matics for a validator on polygon stake manager.
/// @param validatorId validator id.
/// @param amount amount to stake.
/// @param stakeRewards restake rewards.
function restake(
uint256 validatorId,
uint256 amount,
bool stakeRewards
) external;
/// @notice Request unstake a validator.
/// @param validatorId validator id.
function unstake(uint256 validatorId) external;
/// @notice Increase the heimdall fees.
/// @param user user that own the validator in our case the validator contract.
/// @param heimdallFee heimdall fees.
function topUpForFee(address user, uint256 heimdallFee) external;
/// @notice Get the validator id using the user address.
/// @param user user that own the validator in our case the validator contract.
/// @return return the validator id
function getValidatorId(address user) external view returns (uint256);
/// @notice get the validator contract used for delegation.
/// @param validatorId validator id.
/// @return return the address of the validator contract.
function getValidatorContract(uint256 validatorId)
external
view
returns (address);
/// @notice Withdraw accumulated rewards
/// @param validatorId validator id.
function withdrawRewards(uint256 validatorId) external;
/// @notice Get validator total staked.
/// @param validatorId validator id.
function validatorStake(uint256 validatorId)
external
view
returns (uint256);
/// @notice Allows to unstake the staked tokens on the stakeManager.
/// @param validatorId validator id.
function unstakeClaim(uint256 validatorId) external;
/// @notice Allows to update the signer pubkey
/// @param _validatorId validator id
/// @param _signerPubkey update signer public key
function updateSigner(uint256 _validatorId, bytes memory _signerPubkey)
external;
/// @notice Allows to claim the heimdall fees.
/// @param _accumFeeAmount accumulated fees amount
/// @param _index index
/// @param _proof proof
function claimFee(
uint256 _accumFeeAmount,
uint256 _index,
bytes memory _proof
) external;
/// @notice Allows to update the commision rate of a validator
/// @param _validatorId operator id
/// @param _newCommissionRate commission rate
function updateCommissionRate(
uint256 _validatorId,
uint256 _newCommissionRate
) external;
/// @notice Allows to unjail a validator.
/// @param _validatorId id of the validator that is to be unjailed
function unjail(uint256 _validatorId) external;
/// @notice Returns a withdrawal delay.
function withdrawalDelay() external view returns (uint256);
/// @notice Transfers amount from delegator
function delegationDeposit(
uint256 validatorId,
uint256 amount,
address delegator
) external returns (bool);
function epoch() external view returns (uint256);
enum Status {
Inactive,
Active,
Locked,
Unstaked
}
struct Validator {
uint256 amount;
uint256 reward;
uint256 activationEpoch;
uint256 deactivationEpoch;
uint256 jailTime;
address signer;
address contractAddress;
Status status;
uint256 commissionRate;
uint256 lastCommissionUpdate;
uint256 delegatorsReward;
uint256 delegatedAmount;
uint256 initialRewardPerStake;
}
function validators(uint256 _index)
external
view
returns (Validator memory);
/// @notice Returns the address of the nft contract
function NFTContract() external view returns (address);
/// @notice Returns the validator accumulated rewards on stake manager.
function validatorReward(uint256 validatorId)
external
view
returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^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-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
interface IValidatorShare {
struct DelegatorUnbond {
uint256 shares;
uint256 withdrawEpoch;
}
function unbondNonces(address _address) external view returns (uint256);
function activeAmount() external view returns (uint256);
function validatorId() external view returns (uint256);
function withdrawExchangeRate() external view returns (uint256);
function withdrawRewards() external;
function unstakeClaimTokens() external;
function minAmount() external view returns (uint256);
function getLiquidRewards(address user) external view returns (uint256);
function delegation() external view returns (bool);
function updateDelegation(bool _delegation) external;
function buyVoucher(uint256 _amount, uint256 _minSharesToMint)
external
returns (uint256);
function sellVoucher_new(uint256 claimAmount, uint256 maximumSharesToBurn)
external;
function unstakeClaimTokens_new(uint256 unbondNonce) external;
function unbonds_new(address _address, uint256 _unbondNonce)
external
view
returns (DelegatorUnbond memory);
function getTotalStake(address user)
external
view
returns (uint256, uint256);
function owner() external view returns (address);
function restake() external returns (uint256, uint256);
function unlock() external;
function lock() external;
function drain(
address token,
address payable destination,
uint256 amount
) external;
function slash(uint256 _amount) external;
function migrateOut(address user, uint256 amount) external;
function migrateIn(address user, uint256 amount) external;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
/// @title PoLidoNFT interface.
/// @author 2021 ShardLabs
interface IPoLidoNFT is IERC721Upgradeable {
function mint(address _to) external returns (uint256);
function burn(uint256 _tokenId) external;
function isApprovedOrOwner(address _spender, uint256 _tokenId)
external
view
returns (bool);
function setStMATIC(address _stMATIC) external;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
interface IFxStateRootTunnel {
function latestData() external view returns (bytes memory);
function setFxChildTunnel(address _fxChildTunnel) external;
function sendMessageToChild(bytes memory message) external;
function setStMATIC(address _stMATIC) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} | @notice Allows the DAO to set the operator defaultMaxDelegateLimit. @param _defaultMaxDelegateLimit default max delegation amount. | function setDefaultMaxDelegateLimit(uint256 _defaultMaxDelegateLimit)
external
override
userHasRole(DAO_ROLE)
checkMaxDelegationLimit(_defaultMaxDelegateLimit)
{
defaultMaxDelegateLimit = _defaultMaxDelegateLimit;
}
| 6,084,895 | [
1,
19132,
326,
463,
20463,
358,
444,
326,
3726,
805,
2747,
9586,
3039,
18,
225,
389,
1886,
2747,
9586,
3039,
805,
943,
23595,
3844,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
9277,
2747,
9586,
3039,
12,
11890,
5034,
389,
1886,
2747,
9586,
3039,
13,
203,
3639,
3903,
203,
3639,
3849,
203,
3639,
729,
5582,
2996,
12,
18485,
67,
16256,
13,
203,
3639,
866,
2747,
26945,
3039,
24899,
1886,
2747,
9586,
3039,
13,
203,
565,
288,
203,
3639,
805,
2747,
9586,
3039,
273,
389,
1886,
2747,
9586,
3039,
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
]
|
./full_match/1313161554/0x51e20134b7c11D9e868E0EE227BAbc429CA1c2e8/sources/contracts/facets/bridges/cbridge/RangoCBridgeMiddleware.sol | @dev fetch local storage solhint-disable-next-line no-inline-assembly | function getRangoCBridgeMiddlewareStorage() private pure returns (RangoCBridgeMiddlewareStorage storage s) {
bytes32 namespace = CBIRDGE_MIDDLEWARE_NAMESPACE;
assembly {
s.slot := namespace
}
}
| 13,230,108 | [
1,
5754,
1191,
2502,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4170,
6399,
8876,
5404,
9410,
3245,
1435,
3238,
16618,
1135,
261,
54,
6399,
8876,
5404,
9410,
3245,
2502,
272,
13,
288,
203,
3639,
1731,
1578,
1981,
273,
21262,
7937,
40,
7113,
67,
49,
25578,
28499,
67,
11368,
31,
203,
3639,
19931,
288,
203,
5411,
272,
18,
14194,
519,
1981,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/137/0x65DFf67B62652DAB94a8Be6a5c1B3df993525Fcc/sources/project_/contracts/v6.3/GToken.sol | Distributes a reward evenly to all stakers of the vault | function distributeReward(uint assets) external {
address sender = _msgSender();
SafeERC20Upgradeable.safeTransferFrom(_assetIERC20(), sender, address(this), assets);
accRewardsPerToken += assets * PRECISION / totalSupply();
updateShareToAssetsPrice();
totalRewards += assets;
emit RewardDistributed(sender, assets);
}
| 3,744,183 | [
1,
1669,
1141,
279,
19890,
5456,
715,
358,
777,
384,
581,
414,
434,
326,
9229,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
25722,
17631,
1060,
12,
11890,
7176,
13,
3903,
288,
203,
3639,
1758,
5793,
273,
389,
3576,
12021,
5621,
203,
3639,
14060,
654,
39,
3462,
10784,
429,
18,
4626,
5912,
1265,
24899,
9406,
45,
654,
39,
3462,
9334,
5793,
16,
1758,
12,
2211,
3631,
7176,
1769,
203,
540,
203,
3639,
4078,
17631,
14727,
2173,
1345,
1011,
7176,
380,
7071,
26913,
342,
2078,
3088,
1283,
5621,
203,
3639,
1089,
9535,
774,
10726,
5147,
5621,
203,
203,
3639,
2078,
17631,
14727,
1011,
7176,
31,
203,
3639,
3626,
534,
359,
1060,
1669,
11050,
12,
15330,
16,
7176,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.4;
contract Trade {
uint256 public value;
address public exporter;
address public importer;
enum State {Created, Locked, Inactive}
State public state;
function Trade(address _importer, uint256 _value) {
exporter = msg.sender;
importer = _importer;
value = _value;
//msg.value = _value;
//value = msg.value / 2;
//if(2 * value != msg.value) throw;
}
function getValue() returns (uint256) {
return value;
}
function getMsgValue() returns (uint256) {
return msg.value;
}
function getImporter() returns (address) {
return importer;
}
function getImporterBalance() returns (uint) {
return importer.balance;
}
function getExporterBalance() returns (uint) {
return msg.sender.balance;
}
function getContractBalance() returns (uint) {
return this.balance;
}
function setImporter(address _importer) public {
importer = _importer;
}
function transfer(address _importer) payable public {
this.transfer(value);
}
function() payable {
throw;
}
modifier require(bool _condition) {
if(!_condition) throw;
_;
}
modifier onlyImporter() {
if(msg.sender != importer) throw;
_;
}
modifier onlyExporter() {
if(msg.sender != exporter) throw;
_;
}
modifier inState(State _state) {
if(state != _state) throw;
_;
}
event aborted();
event tradeConfirmed();
event goodReceived();
function abort()
onlyExporter
inState(State.Created)
{
aborted();
//exporter.sender(this.balance);
importer.send(value);
state = State.Inactive;
}
function confirmTrade()
inState(State.Created)
require(msg.value == value)
{
tradeConfirmed();
importer = msg.sender;
state = State.Locked;
}
function confirmReceived()
onlyImporter
inState(State.Locked)
{
goodReceived();
//importer.send(value);
exporter.send(value);
//msg.sender.transfer(value);
state = State.Inactive;
}
}
| importer.send(value);msg.sender.transfer(value); | function confirmReceived()
onlyImporter
inState(State.Locked)
{
goodReceived();
exporter.send(value);
state = State.Inactive;
}
| 2,510,600 | [
1,
381,
7988,
18,
4661,
12,
1132,
1769,
3576,
18,
15330,
18,
13866,
12,
1132,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
6932,
8872,
1435,
203,
565,
1338,
21927,
203,
565,
316,
1119,
12,
1119,
18,
8966,
13,
203,
225,
288,
203,
565,
7494,
8872,
5621,
203,
565,
16204,
18,
4661,
12,
1132,
1769,
203,
565,
919,
273,
3287,
18,
24384,
31,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
/// @title ERC-165 Standard Interface Detection
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
interface ERC165 {
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
contract ERC721 is ERC165 {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) external view returns (uint256);
function ownerOf(uint256 _tokenId) external view returns (address);
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public payable;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public payable;
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
function approve(address _approved, uint256 _tokenId) external payable;
function setApprovalForAll(address _operator, bool _approved) external;
function getApproved(uint256 _tokenId) external view returns (address);
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
/// @title ERC-721 Non-Fungible Token Standard
interface ERC721TokenReceiver {
function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4);
}
/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
interface ERC721Metadata /* is ERC721 */ {
function name() external pure returns (string _name);
function symbol() external pure returns (string _symbol);
function tokenURI(uint256 _tokenId) external view returns (string);
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
interface ERC721Enumerable /* is ERC721 */ {
function totalSupply() external view returns (uint256);
function tokenByIndex(uint256 _index) external view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
/// @title A reusable contract to comply with ERC-165
/// @author William Entriken (https://phor.net)
contract PublishInterfaces is ERC165 {
/// @dev Every interface that we support
mapping(bytes4 => bool) internal supportedInterfaces;
function PublishInterfaces() internal {
supportedInterfaces[0x01ffc9a7] = true; // 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) {
return supportedInterfaces[interfaceID] && (interfaceID != 0xffffffff);
}
}
/// @title The external contract that is responsible for generating metadata for GanTokens,
/// it has one function that will return the data as bytes.
contract Metadata {
/// @dev Given a token Id, returns a string with metadata
function getMetadata(uint256 _tokenId, string) public pure returns (bytes32[4] buffer, uint256 count) {
if (_tokenId == 1) {
buffer[0] = "Hello World! :D";
count = 15;
} else if (_tokenId == 2) {
buffer[0] = "I would definitely choose a medi";
buffer[1] = "um length string.";
count = 49;
} else if (_tokenId == 3) {
buffer[0] = "Lorem ipsum dolor sit amet, mi e";
buffer[1] = "st accumsan dapibus augue lorem,";
buffer[2] = " tristique vestibulum id, libero";
buffer[3] = " suscipit varius sapien aliquam.";
count = 128;
}
}
}
contract GanNFT is ERC165, ERC721, ERC721Enumerable, PublishInterfaces, Ownable {
function GanNFT() internal {
supportedInterfaces[0x80ac58cd] = true; // ERC721
supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata
supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable
supportedInterfaces[0x8153916a] = true; // ERC721 + 165 (not needed)
}
bytes4 private constant ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,uint256,bytes)"));
// @dev claim price taken for each new GanToken
// generating a new token will be free in the beinging and later changed
uint256 public claimPrice = 0;
// @dev max supply for token
uint256 public maxSupply = 300;
// The contract that will return tokens metadata
Metadata public erc721Metadata;
/// @dev list of all owned token ids
uint256[] public tokenIds;
/// @dev a mpping for all tokens
mapping(uint256 => address) public tokenIdToOwner;
/// @dev mapping to keep owner balances
mapping(address => uint256) public ownershipCounts;
/// @dev mapping to owners to an array of tokens that they own
mapping(address => uint256[]) public ownerBank;
/// @dev mapping to approved ids
mapping(uint256 => address) public tokenApprovals;
/// @dev The authorized operators for each address
mapping (address => mapping (address => bool)) internal operatorApprovals;
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external pure returns (string) {
return "GanToken";
}
/// @notice An abbreviated name for NFTs in this contract
function symbol() external pure returns (string) {
return "GT";
}
/// @dev Set the address of the sibling contract that tracks metadata.
/// Only the contract creater can call this.
/// @param _contractAddress The location of the contract with meta data
function setMetadataAddress(address _contractAddress) public onlyOwner {
erc721Metadata = Metadata(_contractAddress);
}
modifier canTransfer(uint256 _tokenId, address _from, address _to) {
address owner = tokenIdToOwner[_tokenId];
require(tokenApprovals[_tokenId] == _to || owner == _from || operatorApprovals[_to][_to]);
_;
}
/// @notice checks to see if a sender owns a _tokenId
/// @param _tokenId The identifier for an NFT
modifier owns(uint256 _tokenId) {
require(tokenIdToOwner[_tokenId] == msg.sender);
_;
}
/// @dev This emits any time the ownership of a GanToken changes.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/// @dev This emits when the approved addresses for a GanToken is changed or reaffirmed.
/// The zero address indicates there is no owner and it get reset on a transfer
event Approval(address indexed _owner, address indexed _approved, uint256 _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 allow the owner to set the supply max
function setMaxSupply(uint max) external payable onlyOwner {
require(max > tokenIds.length);
maxSupply = max;
}
/// @notice allow the owner to set a new fee for creating a GanToken
function setClaimPrice(uint256 price) external payable onlyOwner {
claimPrice = price;
}
/// @dev Required for ERC-721 compliance.
function balanceOf(address _owner) external view returns (uint256 balance) {
balance = ownershipCounts[_owner];
}
/// @notice Gets the onwner of a an NFT
/// @param _tokenId The identifier for an NFT
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId) external view returns (address owner) {
owner = tokenIdToOwner[_tokenId];
}
/// @notice returns all owners' tokens will return an empty array
/// if the address has no tokens
/// @param _owner The address of the owner in question
function tokensOfOwner(address _owner) external view returns (uint256[]) {
uint256 tokenCount = ownershipCounts[_owner];
if (tokenCount == 0) {
return new uint256[](0);
}
uint256[] memory result = new uint256[](tokenCount);
for (uint256 i = 0; i < tokenCount; i++) {
result[i] = ownerBank[_owner][i];
}
return result;
}
/// @dev creates a list of all the tokenIds
function getAllTokenIds() external view returns (uint256[]) {
uint256[] memory result = new uint256[](tokenIds.length);
for (uint i = 0; i < result.length; i++) {
result[i] = tokenIds[i];
}
return result;
}
/// @notice Create a new GanToken with a id and attaches an owner
/// @param _noise The id of the token that's being created
function newGanToken(uint256 _noise) external payable {
require(msg.sender != address(0));
require(tokenIdToOwner[_noise] == 0x0);
require(tokenIds.length < maxSupply);
require(msg.value >= claimPrice);
tokenIds.push(_noise);
ownerBank[msg.sender].push(_noise);
tokenIdToOwner[_noise] = msg.sender;
ownershipCounts[msg.sender]++;
emit Transfer(address(0), msg.sender, 0);
}
/// @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,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 data) public payable
{
_safeTransferFrom(_from, _to, _tokenId, data);
}
/// @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) public payable
{
_safeTransferFrom(_from, _to, _tokenId, "");
}
/// @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 {
require(_to != 0x0);
require(_to != address(this));
require(tokenApprovals[_tokenId] == msg.sender);
require(tokenIdToOwner[_tokenId] == _from);
_transfer(_tokenId, _to);
}
/// @notice Grant another address the right to transfer a specific token via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @dev The zero address indicates there is no approved address.
/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @dev Required for ERC-721 compliance.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds.
function approve(address _to, uint256 _tokenId) external owns(_tokenId) payable {
// Register the approval (replacing any previous approval).
tokenApprovals[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all your asset.
/// @dev Emits the ApprovalForAll event
/// @param _operator Address to add to the set of authorized operators.
/// @param _approved True if the operators is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external {
operatorApprovals[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/// @notice Get the approved address for a single 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) {
return tokenApprovals[_tokenId];
}
/// @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) {
return operatorApprovals[_owner][_operator];
}
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
/// @dev Required for ERC-721 compliance.
function totalSupply() external view returns (uint256) {
return tokenIds.length;
}
/// @notice Enumerate valid NFTs
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for index the `_index`th NFT 0 if it doesn't exist,
function tokenByIndex(uint256 _index) external view returns (uint256) {
return tokenIds[_index];
}
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId) {
require(_owner != address(0));
require(_index < ownerBank[_owner].length);
_tokenId = ownerBank[_owner][_index];
}
function _transfer(uint256 _tokenId, address _to) internal {
require(_to != address(0));
address from = tokenIdToOwner[_tokenId];
uint256 tokenCount = ownershipCounts[from];
// remove from ownerBank and replace the deleted token id
for (uint256 i = 0; i < tokenCount; i++) {
uint256 ownedId = ownerBank[from][i];
if (_tokenId == ownedId) {
delete ownerBank[from][i];
if (i != tokenCount) {
ownerBank[from][i] = ownerBank[from][tokenCount - 1];
}
break;
}
}
ownershipCounts[from]--;
ownershipCounts[_to]++;
ownerBank[_to].push(_tokenId);
tokenIdToOwner[_tokenId] = _to;
tokenApprovals[_tokenId] = address(0);
emit Transfer(from, _to, 1);
}
/// @dev Actually perform the safeTransferFrom
function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data)
private
canTransfer(_tokenId, _from, _to)
{
address owner = tokenIdToOwner[_tokenId];
require(owner == _from);
require(_to != address(0));
require(_to != address(this));
_transfer(_tokenId, _to);
// Do the callback after everything is done to avoid reentrancy attack
uint256 codeSize;
assembly { codeSize := extcodesize(_to) }
if (codeSize == 0) {
return;
}
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, data);
require(retval == ERC721_RECEIVED);
}
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5b4a7b4b6bdbbbcb195bbbaa1b1baa1fbbbb0a1">[email protected]</a>>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
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
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
/// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1d0c3d0d2d9dfd8d5f1dfdec5d5dec59fdfd4c5">[email protected]</a>>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private pure returns (string) {
string memory outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the GanToken whose metadata should be returned.
function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
require(erc721Metadata != address(0));
uint256 count;
bytes32[4] memory buffer;
(buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
return _toString(buffer, count);
}
}
contract GanTokenMain is GanNFT {
struct Offer {
bool isForSale;
uint256 tokenId;
address seller;
uint value; // in ether
address onlySellTo; // specify to sell only to a specific person
}
struct Bid {
bool hasBid;
uint256 tokenId;
address bidder;
uint value;
}
/// @dev mapping of balances for address
mapping(address => uint256) public pendingWithdrawals;
/// @dev mapping of tokenId to to an offer
mapping(uint256 => Offer) public ganTokenOfferedForSale;
/// @dev mapping bids to tokenIds
mapping(uint256 => Bid) public tokenBids;
event BidForGanTokenOffered(uint256 tokenId, uint256 value, address sender);
event BidWithdrawn(uint256 tokenId, uint256 value, address bidder);
event GanTokenOfferedForSale(uint256 tokenId, uint256 minSalePriceInWei, address onlySellTo);
event GanTokenNoLongerForSale(uint256 tokenId);
/// @notice Allow a token owner to pull sale
/// @param tokenId The id of the token that's created
function ganTokenNoLongerForSale(uint256 tokenId) public payable owns(tokenId) {
ganTokenOfferedForSale[tokenId] = Offer(false, tokenId, msg.sender, 0, 0x0);
emit GanTokenNoLongerForSale(tokenId);
}
/// @notice Put a token up for sale
/// @param tokenId The id of the token that's created
/// @param minSalePriceInWei desired price of token
function offerGanTokenForSale(uint tokenId, uint256 minSalePriceInWei) external payable owns(tokenId) {
ganTokenOfferedForSale[tokenId] = Offer(true, tokenId, msg.sender, minSalePriceInWei, 0x0);
emit GanTokenOfferedForSale(tokenId, minSalePriceInWei, 0x0);
}
/// @notice Create a new GanToken with a id and attaches an owner
/// @param tokenId The id of the token that's being created
function offerGanTokenForSaleToAddress(uint tokenId, address sendTo, uint256 minSalePriceInWei) external payable {
require(tokenIdToOwner[tokenId] == msg.sender);
ganTokenOfferedForSale[tokenId] = Offer(true, tokenId, msg.sender, minSalePriceInWei, sendTo);
emit GanTokenOfferedForSale(tokenId, minSalePriceInWei, sendTo);
}
/// @notice Allows an account to buy a NFT gan token that is up for offer
/// the token owner must set onlySellTo to the sender
/// @param id the id of the token
function buyGanToken(uint256 id) public payable {
Offer memory offer = ganTokenOfferedForSale[id];
require(offer.isForSale);
require(offer.onlySellTo == msg.sender && offer.onlySellTo != 0x0);
require(msg.value == offer.value);
require(tokenIdToOwner[id] == offer.seller);
safeTransferFrom(offer.seller, offer.onlySellTo, id);
ganTokenOfferedForSale[id] = Offer(false, id, offer.seller, 0, 0x0);
pendingWithdrawals[offer.seller] += msg.value;
}
/// @notice Allows an account to enter a higher bid on a toekn
/// @param tokenId the id of the token
function enterBidForGanToken(uint256 tokenId) external payable {
Bid memory existing = tokenBids[tokenId];
require(tokenIdToOwner[tokenId] != msg.sender);
require(tokenIdToOwner[tokenId] != 0x0);
require(msg.value > existing.value);
if (existing.value > 0) {
// Refund the failing bid
pendingWithdrawals[existing.bidder] += existing.value;
}
tokenBids[tokenId] = Bid(true, tokenId, msg.sender, msg.value);
emit BidForGanTokenOffered(tokenId, msg.value, msg.sender);
}
/// @notice Allows the owner of a token to accept an outstanding bid for that token
/// @param tokenId The id of the token that's being created
/// @param price The desired price of token in wei
function acceptBid(uint256 tokenId, uint256 price) external payable {
require(tokenIdToOwner[tokenId] == msg.sender);
Bid memory bid = tokenBids[tokenId];
require(bid.value != 0);
require(bid.value == price);
safeTransferFrom(msg.sender, bid.bidder, tokenId);
tokenBids[tokenId] = Bid(false, tokenId, address(0), 0);
pendingWithdrawals[msg.sender] += bid.value;
}
/// @notice Check is a given id is on sale
/// @param tokenId The id of the token in question
/// @return a bool whether of not the token is on sale
function isOnSale(uint256 tokenId) external view returns (bool) {
return ganTokenOfferedForSale[tokenId].isForSale;
}
/// @notice Gets all the sale data related to a token
/// @param tokenId The id of the token
/// @return sale information
function getSaleData(uint256 tokenId) public view returns (bool isForSale, address seller, uint value, address onlySellTo) {
Offer memory offer = ganTokenOfferedForSale[tokenId];
isForSale = offer.isForSale;
seller = offer.seller;
value = offer.value;
onlySellTo = offer.onlySellTo;
}
/// @notice Gets all the bid data related to a token
/// @param tokenId The id of the token
/// @return bid information
function getBidData(uint256 tokenId) view public returns (bool hasBid, address bidder, uint value) {
Bid memory bid = tokenBids[tokenId];
hasBid = bid.hasBid;
bidder = bid.bidder;
value = bid.value;
}
/// @notice Allows a bidder to withdraw their bid
/// @param tokenId The id of the token
function withdrawBid(uint256 tokenId) external payable {
Bid memory bid = tokenBids[tokenId];
require(tokenIdToOwner[tokenId] != msg.sender);
require(tokenIdToOwner[tokenId] != 0x0);
require(bid.bidder == msg.sender);
emit BidWithdrawn(tokenId, bid.value, msg.sender);
uint amount = bid.value;
tokenBids[tokenId] = Bid(false, tokenId, 0x0, 0);
// Refund the bid money
msg.sender.transfer(amount);
}
/// @notice Allows a sender to withdraw any amount in the contrat
function withdraw() external {
uint256 amount = pendingWithdrawals[msg.sender];
// Remember to zero the pending refund before
// sending to prevent re-entrancy attacks
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
}
} | remove from ownerBank and replace the deleted token id | function _transfer(uint256 _tokenId, address _to) internal {
require(_to != address(0));
address from = tokenIdToOwner[_tokenId];
uint256 tokenCount = ownershipCounts[from];
for (uint256 i = 0; i < tokenCount; i++) {
uint256 ownedId = ownerBank[from][i];
if (_tokenId == ownedId) {
delete ownerBank[from][i];
if (i != tokenCount) {
ownerBank[from][i] = ownerBank[from][tokenCount - 1];
}
break;
}
}
ownershipCounts[from]--;
ownershipCounts[_to]++;
ownerBank[_to].push(_tokenId);
tokenIdToOwner[_tokenId] = _to;
tokenApprovals[_tokenId] = address(0);
emit Transfer(from, _to, 1);
}
| 7,691,922 | [
1,
4479,
628,
3410,
16040,
471,
1453,
326,
4282,
1147,
612,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
11890,
5034,
389,
2316,
548,
16,
1758,
389,
869,
13,
2713,
288,
203,
565,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
203,
565,
1758,
628,
273,
1147,
28803,
5541,
63,
67,
2316,
548,
15533,
203,
565,
2254,
5034,
1147,
1380,
273,
23178,
9211,
63,
2080,
15533,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
1147,
1380,
31,
277,
27245,
288,
203,
1377,
2254,
5034,
16199,
548,
273,
3410,
16040,
63,
2080,
6362,
77,
15533,
203,
1377,
309,
261,
67,
2316,
548,
422,
16199,
548,
13,
288,
203,
3639,
1430,
3410,
16040,
63,
2080,
6362,
77,
15533,
203,
3639,
309,
261,
77,
480,
1147,
1380,
13,
288,
203,
1850,
3410,
16040,
63,
2080,
6362,
77,
65,
273,
3410,
16040,
63,
2080,
6362,
2316,
1380,
300,
404,
15533,
203,
3639,
289,
203,
3639,
898,
31,
203,
1377,
289,
203,
565,
289,
203,
203,
565,
23178,
9211,
63,
2080,
65,
413,
31,
203,
565,
23178,
9211,
63,
67,
869,
3737,
15,
31,
203,
565,
3410,
16040,
63,
67,
869,
8009,
6206,
24899,
2316,
548,
1769,
203,
203,
565,
1147,
28803,
5541,
63,
67,
2316,
548,
65,
273,
389,
869,
31,
203,
565,
1147,
12053,
4524,
63,
67,
2316,
548,
65,
273,
1758,
12,
20,
1769,
203,
565,
3626,
12279,
12,
2080,
16,
389,
869,
16,
404,
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
]
|
./full_match/1/0xA648f6155e8Fe76b26F45364e067193183dFDc9B/sources/contracts/V3/ViseToken.sol | @dev Initializes the contract with the given parameters. | ) ERC20("VISE", "VISE") {
_mint(_owner, INITIAL_TOTAL_SUPPLY);
_transferOwnership(_owner);
whitelist[_owner] = true;
}
| 16,562,619 | [
1,
9685,
326,
6835,
598,
326,
864,
1472,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4232,
39,
3462,
2932,
4136,
1090,
3113,
315,
4136,
1090,
7923,
288,
203,
3639,
389,
81,
474,
24899,
8443,
16,
28226,
67,
28624,
67,
13272,
23893,
1769,
203,
3639,
389,
13866,
5460,
12565,
24899,
8443,
1769,
203,
3639,
10734,
63,
67,
8443,
65,
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
]
|
pragma solidity ^0.4.11;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant 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 constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Token {
using SafeMath for uint256;
string public symbol = "LPN";
string public name = "Litepool";
uint8 public constant decimals = 18;
uint256 _totalSupply = 35000000;
uint256 buyPrice = 769230769230769;
address owner = 0x5367B63897eDE5076cD7A970a0fd85750e27F745;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Debug(string message, uint number);
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
function Token() public {
balances[owner] = _totalSupply * 10 ** 18;
}
function changeBuyPrice(uint price)
{
if (msg.sender == owner){
buyPrice = price * 10 ** 18;
}
}
function totalSupply() constant returns (uint256 totalSupply) {
return _totalSupply;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner].div(10 ** uint256(decimals));
}
function transfer(address _to, uint256 _amount) internal returns (bool success) {
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
function transferFrom(
address _from,
address _to,
uint256 _amount
) internal returns (bool success) {
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
function approve(address _spender, uint256 _amount) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// fallback function can be used to buy tokens
function () public payable {
// require(msg.sender != owner); //owner should not be buying any tokens
buy(msg.sender);
}
function buy(address beneficiary) payable public returns (uint amount) {
amount = msg.value.div(buyPrice); // calculates the amount
amount = amount * 10 ** 18;
require(balances[owner] >= amount); // checks if it has enough to sell
balances[beneficiary] = balances[beneficiary].add(amount); // adds the amount to buyer's balance
balances[owner] = balances[owner].sub(amount); // subtracts amount from seller's balance
owner.transfer(msg.value);
Transfer(owner, msg.sender, amount); // execute an event reflecting the change
return amount; // ends function and returns
}
} | execute an event reflecting the change
| Transfer(owner, msg.sender, amount); | 1,010,908 | [
1,
8837,
392,
871,
3037,
310,
326,
2549,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
12279,
12,
8443,
16,
1234,
18,
15330,
16,
3844,
1769,
7734,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
contract CPost is ERC721 {
uint256 public totalSupply = 0; // total count of token
mapping(uint256 => string) public _token_hash; // ipfs hash for token[id] content
mapping(string => bool) _hash_exists; // for checking duplication
mapping(uint256 => address) public _token_contributor; // for receiving rewards
mapping(uint256 => uint256) _reward_sum; // total reward received for token[id]
uint256 public _ratified_block_height; // the last block height being ratified and consolidated
mapping(uint256 => bool) public _isReviewed; // if token[id] is Reviewed
mapping(uint256 => bool) public _isRatified; // if token[id] is Ratified
mapping(address => bool) public _isReviewer; // if address is Reviewer
mapping(address => bool) public _isRatifier; // if address is Ratifier
modifier onlyReviewer {
require(_isReviewer[msg.sender], "not reviewer");
_;
}
modifier onlyRatifier {
require(_isRatifier[msg.sender], "not ratifier");
_;
}
function changeReviewer(address person, bool x) public onlyRatifier {
_isReviewer[person] = x;
}
function changeRatifier(address person, bool x) public onlyRatifier {
_isRatifier[person] = x;
}
constructor() ERC721("CPost NFT", "CPost") {
// the deployer will be reviewer and ratifier by default
_isReviewer[msg.sender] = true;
_isRatifier[msg.sender] = true;
}
// everyone can contribute a new post with the hash of its content
function contribute(string memory hash) public returns (uint256) {
require(_hash_exists[hash] == false, "already minted");
_hash_exists[hash] = true;
uint256 id = totalSupply;
totalSupply += 1;
_token_contributor[id] = msg.sender;
_token_hash[id] = hash;
_safeMint(msg.sender, id);
return id;
}
// reviewer can pick content
function pick(uint256 id, bool x) public onlyReviewer {
require(_isReviewer[msg.sender], "not reviewer");
_isReviewed[id] = x;
}
// ratifier can ratify
function ratify(uint256 id, bool x) public onlyRatifier {
require(_isRatifier[msg.sender], "not ratifier");
_isRatified[id] = x;
}
// everyone can reward the contributor of a post
function reward(uint256 id) public payable {
require(_token_contributor[id] != address(0), "non-existent contributor");
_reward_sum[id] += msg.value;
Address.sendValue(payable(_token_contributor[id]), msg.value);
}
}
| the last block height being ratified and consolidated
| uint256 public _ratified_block_height; | 12,923,991 | [
1,
5787,
1142,
1203,
2072,
3832,
15183,
939,
471,
21785,
690,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
1071,
389,
17048,
939,
67,
2629,
67,
4210,
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.5.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @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 private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract ERC1820Registry {
function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external;
function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address);
function setManager(address _addr, address _newManager) external;
function getManager(address _addr) public view returns (address);
}
/// Base client to interact with the registry.
contract ERC1820Client {
ERC1820Registry constant ERC1820REGISTRY = ERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
function setInterfaceImplementation(string memory _interfaceLabel, address _implementation) internal {
bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel));
ERC1820REGISTRY.setInterfaceImplementer(address(this), interfaceHash, _implementation);
}
function interfaceAddr(address addr, string memory _interfaceLabel) internal view returns(address) {
bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel));
return ERC1820REGISTRY.getInterfaceImplementer(addr, interfaceHash);
}
function delegateManagement(address _newManager) internal {
ERC1820REGISTRY.setManager(address(this), _newManager);
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
contract ERC1820Implementer {
bytes32 constant ERC1820_ACCEPT_MAGIC = keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC"));
mapping(bytes32 => bool) internal _interfaceHashes;
function canImplementInterfaceForAddress(bytes32 interfaceHash, address /*addr*/) // Comments to avoid compilation warnings for unused variables.
external
view
returns(bytes32)
{
if(_interfaceHashes[interfaceHash]) {
return ERC1820_ACCEPT_MAGIC;
} else {
return "";
}
}
function _setInterface(string memory interfaceLabel) internal {
_interfaceHashes[keccak256(abi.encodePacked(interfaceLabel))] = true;
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title MinterRole
* @dev Minters are responsible for minting new tokens.
*/
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function removeMinter(address account) public onlyMinter {
_removeMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title IERC1400 security token standard
* @dev See https://github.com/SecurityTokenStandard/EIP-Spec/blob/master/eip/eip-1400.md
*/
interface IERC1400 /*is IERC20*/ { // Interfaces can currently not inherit interfaces, but IERC1400 shall include IERC20
// ****************** Document Management *******************
function getDocument(bytes32 name) external view returns (string memory, bytes32);
function setDocument(bytes32 name, string calldata uri, bytes32 documentHash) external;
// ******************* Token Information ********************
function balanceOfByPartition(bytes32 partition, address tokenHolder) external view returns (uint256);
function partitionsOf(address tokenHolder) external view returns (bytes32[] memory);
// *********************** Transfers ************************
function transferWithData(address to, uint256 value, bytes calldata data) external;
function transferFromWithData(address from, address to, uint256 value, bytes calldata data) external;
// *************** Partition Token Transfers ****************
function transferByPartition(bytes32 partition, address to, uint256 value, bytes calldata data) external returns (bytes32);
function operatorTransferByPartition(bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external returns (bytes32);
// ****************** Controller Operation ******************
function isControllable() external view returns (bool);
// function controllerTransfer(address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external; // removed because same action can be achieved with "operatorTransferByPartition"
// function controllerRedeem(address tokenHolder, uint256 value, bytes calldata data, bytes calldata operatorData) external; // removed because same action can be achieved with "operatorRedeemByPartition"
// ****************** Operator Management *******************
function authorizeOperator(address operator) external;
function revokeOperator(address operator) external;
function authorizeOperatorByPartition(bytes32 partition, address operator) external;
function revokeOperatorByPartition(bytes32 partition, address operator) external;
// ****************** Operator Information ******************
function isOperator(address operator, address tokenHolder) external view returns (bool);
function isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) external view returns (bool);
// ********************* Token Issuance *********************
function isIssuable() external view returns (bool);
function issue(address tokenHolder, uint256 value, bytes calldata data) external;
function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data) external;
// ******************** Token Redemption ********************
function redeem(uint256 value, bytes calldata data) external;
function redeemFrom(address tokenHolder, uint256 value, bytes calldata data) external;
function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data) external;
function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata operatorData) external;
// ******************* Transfer Validity ********************
// We use different transfer validity functions because those described in the interface don't allow to verify the certificate's validity.
// Indeed, verifying the ecrtificate's validity requires to keeps the function's arguments in the exact same order as the transfer function.
//
// function canTransfer(address to, uint256 value, bytes calldata data) external view returns (byte, bytes32);
// function canTransferFrom(address from, address to, uint256 value, bytes calldata data) external view returns (byte, bytes32);
// function canTransferByPartition(address from, address to, bytes32 partition, uint256 value, bytes calldata data) external view returns (byte, bytes32, bytes32);
// ******************* Controller Events ********************
// We don't use this event as we don't use "controllerTransfer"
// event ControllerTransfer(
// address controller,
// address indexed from,
// address indexed to,
// uint256 value,
// bytes data,
// bytes operatorData
// );
//
// We don't use this event as we don't use "controllerRedeem"
// event ControllerRedemption(
// address controller,
// address indexed tokenHolder,
// uint256 value,
// bytes data,
// bytes operatorData
// );
// ******************** Document Events *********************
event Document(bytes32 indexed name, string uri, bytes32 documentHash);
// ******************** Transfer Events *********************
event TransferByPartition(
bytes32 indexed fromPartition,
address operator,
address indexed from,
address indexed to,
uint256 value,
bytes data,
bytes operatorData
);
event ChangedPartition(
bytes32 indexed fromPartition,
bytes32 indexed toPartition,
uint256 value
);
// ******************** Operator Events *********************
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
event AuthorizedOperatorByPartition(bytes32 indexed partition, address indexed operator, address indexed tokenHolder);
event RevokedOperatorByPartition(bytes32 indexed partition, address indexed operator, address indexed tokenHolder);
// ************** Issuance / Redemption Events **************
event Issued(address indexed operator, address indexed to, uint256 value, bytes data);
event Redeemed(address indexed operator, address indexed from, uint256 value, bytes data);
event IssuedByPartition(bytes32 indexed partition, address indexed operator, address indexed to, uint256 value, bytes data, bytes operatorData);
event RedeemedByPartition(bytes32 indexed partition, address indexed operator, address indexed from, uint256 value, bytes operatorData);
}
/**
* Reason codes - ERC-1066
*
* To improve the token holder experience, canTransfer MUST return a reason byte code
* on success or failure based on the ERC-1066 application-specific status codes specified below.
* An implementation can also return arbitrary data as a bytes32 to provide additional
* information not captured by the reason code.
*
* Code Reason
* 0x50 transfer failure
* 0x51 transfer success
* 0x52 insufficient balance
* 0x53 insufficient allowance
* 0x54 transfers halted (contract paused)
* 0x55 funds locked (lockup period)
* 0x56 invalid sender
* 0x57 invalid receiver
* 0x58 invalid operator (transfer agent)
* 0x59
* 0x5a
* 0x5b
* 0x5a
* 0x5b
* 0x5c
* 0x5d
* 0x5e
* 0x5f token meta or info
*
* These codes are being discussed at: https://ethereum-magicians.org/t/erc-1066-ethereum-status-codes-esc/283/24
*/
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title IERC1400TokensValidator
* @dev ERC1400TokensValidator interface
*/
interface IERC1400TokensValidator {
function canValidate(
address token,
bytes calldata payload,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) external view returns(bool);
function tokensToValidate(
bytes calldata payload,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) external;
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title IERC1400TokensChecker
* @dev IERC1400TokensChecker interface
*/
interface IERC1400TokensChecker {
// function canTransfer(
// bytes calldata payload,
// address operator,
// address from,
// address to,
// uint256 value,
// bytes calldata data,
// bytes calldata operatorData
// ) external view returns (byte, bytes32);
function canTransferByPartition(
bytes calldata payload,
bytes32 partition,
address operator,
address from,
address to,
uint256 value,
bytes calldata data,
bytes calldata operatorData
) external view returns (byte, bytes32, bytes32);
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title IERC1400TokensSender
* @dev ERC1400TokensSender interface
*/
interface IERC1400TokensSender {
function canTransfer(
bytes calldata payload,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) external view returns(bool);
function tokensToTransfer(
bytes calldata payload,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) external;
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title IERC1400TokensRecipient
* @dev ERC1400TokensRecipient interface
*/
interface IERC1400TokensRecipient {
function canReceive(
bytes calldata payload,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) external view returns(bool);
function tokensReceived(
bytes calldata payload,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) external;
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
// Extensions
/**
* @title ERC1400
* @dev ERC1400 logic
*/
contract ERC1400 is IERC20, IERC1400, Ownable, ERC1820Client, ERC1820Implementer, MinterRole {
using SafeMath for uint256;
// Token
string constant internal ERC1400_INTERFACE_NAME = "ERC1400Token";
string constant internal ERC20_INTERFACE_NAME = "ERC20Token";
// Token extensions
string constant internal ERC1400_TOKENS_CHECKER = "ERC1400TokensChecker";
string constant internal ERC1400_TOKENS_VALIDATOR = "ERC1400TokensValidator";
// User extensions
string constant internal ERC1400_TOKENS_SENDER = "ERC1400TokensSender";
string constant internal ERC1400_TOKENS_RECIPIENT = "ERC1400TokensRecipient";
/************************************* Token description ****************************************/
string internal _name;
string internal _symbol;
uint256 internal _granularity;
uint256 internal _totalSupply;
bool internal _migrated;
/************************************************************************************************/
/**************************************** Token behaviours **************************************/
// Indicate whether the token can still be controlled by operators or not anymore.
bool internal _isControllable;
// Indicate whether the token can still be issued by the issuer or not anymore.
bool internal _isIssuable;
/************************************************************************************************/
/********************************** ERC20 Token mappings ****************************************/
// Mapping from tokenHolder to balance.
mapping(address => uint256) internal _balances;
// Mapping from (tokenHolder, spender) to allowed value.
mapping (address => mapping (address => uint256)) internal _allowed;
/************************************************************************************************/
/**************************************** Documents *********************************************/
struct Doc {
string docURI;
bytes32 docHash;
}
// Mapping for token URIs.
mapping(bytes32 => Doc) internal _documents;
/************************************************************************************************/
/*********************************** Partitions mappings ***************************************/
// List of partitions.
bytes32[] internal _totalPartitions;
// Mapping from partition to their index.
mapping (bytes32 => uint256) internal _indexOfTotalPartitions;
// Mapping from partition to global balance of corresponding partition.
mapping (bytes32 => uint256) internal _totalSupplyByPartition;
// Mapping from tokenHolder to their partitions.
mapping (address => bytes32[]) internal _partitionsOf;
// Mapping from (tokenHolder, partition) to their index.
mapping (address => mapping (bytes32 => uint256)) internal _indexOfPartitionsOf;
// Mapping from (tokenHolder, partition) to balance of corresponding partition.
mapping (address => mapping (bytes32 => uint256)) internal _balanceOfByPartition;
// List of token default partitions (for ERC20 compatibility).
bytes32[] internal _defaultPartitions;
/************************************************************************************************/
/********************************* Global operators mappings ************************************/
// Mapping from (operator, tokenHolder) to authorized status. [TOKEN-HOLDER-SPECIFIC]
mapping(address => mapping(address => bool)) internal _authorizedOperator;
// Array of controllers. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC]
address[] internal _controllers;
// Mapping from operator to controller status. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC]
mapping(address => bool) internal _isController;
/************************************************************************************************/
/******************************** Partition operators mappings **********************************/
// Mapping from (partition, tokenHolder, spender) to allowed value. [TOKEN-HOLDER-SPECIFIC]
mapping(bytes32 => mapping (address => mapping (address => uint256))) internal _allowedByPartition;
// Mapping from (tokenHolder, partition, operator) to 'approved for partition' status. [TOKEN-HOLDER-SPECIFIC]
mapping (address => mapping (bytes32 => mapping (address => bool))) internal _authorizedOperatorByPartition;
// Mapping from partition to controllers for the partition. [NOT TOKEN-HOLDER-SPECIFIC]
mapping (bytes32 => address[]) internal _controllersByPartition;
// Mapping from (partition, operator) to PartitionController status. [NOT TOKEN-HOLDER-SPECIFIC]
mapping (bytes32 => mapping (address => bool)) internal _isControllerByPartition;
/************************************************************************************************/
/***************************************** Modifiers ********************************************/
/**
* @dev Modifier to verify if token is issuable.
*/
modifier isIssuableToken() {
require(_isIssuable, "55"); // 0x55 funds locked (lockup period)
_;
}
/**
* @dev Modifier to make a function callable only when the contract is not migrated.
*/
modifier isNotMigratedToken() {
require(!_migrated, "54"); // 0x54 transfers halted (contract paused)
_;
}
/**
* @dev Modifier to verifiy if sender is a minter.
*/
modifier onlyMinter() {
require(isMinter(msg.sender) || isOwner());
_;
}
/************************************************************************************************/
/**************************** Events (additional - not mandatory) *******************************/
event ApprovalByPartition(bytes32 indexed partition, address indexed owner, address indexed spender, uint256 value);
/************************************************************************************************/
/**
* @dev Initialize ERC1400 + 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 defaultPartitions Partitions chosen by default, when partition is
* not specified, like the case ERC20 tranfers.
*/
constructor(
string memory name,
string memory symbol,
uint256 granularity,
address[] memory controllers,
bytes32[] memory defaultPartitions
)
public
{
_name = name;
_symbol = symbol;
_totalSupply = 0;
require(granularity >= 1); // Constructor Blocked - Token granularity can not be lower than 1
_granularity = granularity;
_setControllers(controllers);
_defaultPartitions = defaultPartitions;
_isControllable = true;
_isIssuable = true;
// Register contract in ERC1820 registry
ERC1820Client.setInterfaceImplementation(ERC1400_INTERFACE_NAME, address(this));
ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, address(this));
// Indicate token verifies ERC1400 and ERC20 interfaces
ERC1820Implementer._setInterface(ERC1400_INTERFACE_NAME); // For migration
ERC1820Implementer._setInterface(ERC20_INTERFACE_NAME); // For migration
}
/************************************************************************************************/
/****************************** EXTERNAL FUNCTIONS (ERC20 INTERFACE) ****************************/
/************************************************************************************************/
/**
* @dev Get the total number of issued tokens.
* @return Total supply of tokens currently in circulation.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @dev Get the balance of the account with address 'tokenHolder'.
* @param tokenHolder Address for which the balance is returned.
* @return Amount of token held by 'tokenHolder' in the token contract.
*/
function balanceOf(address tokenHolder) external view returns (uint256) {
return _balances[tokenHolder];
}
/**
* @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 returns (bool) {
_transferByDefaultPartitions(msg.sender, msg.sender, to, value, "");
return true;
}
/**
* @dev Check the value 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 value of tokens still available for the spender.
*/
function allowance(address owner, address spender) external view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of 'msg.sender'.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean that indicates if the operation was successful.
*/
function approve(address spender, uint256 value) external returns (bool) {
require(spender != address(0), "56"); // 0x56 invalid sender
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address which you want to transfer 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) external returns (bool) {
require( _isOperator(msg.sender, from)
|| (value <= _allowed[from][msg.sender]), "53"); // 0x53 insufficient allowance
if(_allowed[from][msg.sender] >= value) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
} else {
_allowed[from][msg.sender] = 0;
}
_transferByDefaultPartitions(msg.sender, from, to, value, "");
return true;
}
/************************************************************************************************/
/****************************** EXTERNAL FUNCTIONS (ERC1400 INTERFACE) **************************/
/************************************************************************************************/
/************************************* Document Management **************************************/
/**
* @dev Access a document associated with the token.
* @param name Short name (represented as a bytes32) associated to the document.
* @return Requested document + document hash.
*/
function getDocument(bytes32 name) external view returns (string memory, bytes32) {
require(bytes(_documents[name].docURI).length != 0); // Action Blocked - Empty document
return (
_documents[name].docURI,
_documents[name].docHash
);
}
/**
* @dev Associate a document with the token.
* @param name Short name (represented as a bytes32) associated to the document.
* @param uri Document content.
* @param documentHash Hash of the document [optional parameter].
*/
function setDocument(bytes32 name, string calldata uri, bytes32 documentHash) external {
require(_isController[msg.sender]);
_documents[name] = Doc({
docURI: uri,
docHash: documentHash
});
emit Document(name, uri, documentHash);
}
/************************************************************************************************/
/************************************** Token Information ***************************************/
/**
* @dev Get balance of a tokenholder for a specific partition.
* @param partition Name of the partition.
* @param tokenHolder Address for which the balance is returned.
* @return Amount of token of partition 'partition' held by 'tokenHolder' in the token contract.
*/
function balanceOfByPartition(bytes32 partition, address tokenHolder) external view returns (uint256) {
return _balanceOfByPartition[tokenHolder][partition];
}
/**
* @dev Get partitions index of a tokenholder.
* @param tokenHolder Address for which the partitions index are returned.
* @return Array of partitions index of 'tokenHolder'.
*/
function partitionsOf(address tokenHolder) external view returns (bytes32[] memory) {
return _partitionsOf[tokenHolder];
}
/************************************************************************************************/
/****************************************** Transfers *******************************************/
/**
* @dev Transfer the amount of tokens from the address 'msg.sender' to the address 'to'.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer, by the token holder.
*/
function transferWithData(address to, uint256 value, bytes calldata data) external {
_transferByDefaultPartitions(msg.sender, msg.sender, to, value, data);
}
/**
* @dev Transfer the amount of tokens on behalf of the address 'from' to the address 'to'.
* @param from Token holder (or 'address(0)' to set from to 'msg.sender').
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer, and intended for the token holder ('from').
*/
function transferFromWithData(address from, address to, uint256 value, bytes calldata data) external {
require(_isOperator(msg.sender, from), "58"); // 0x58 invalid operator (transfer agent)
_transferByDefaultPartitions(msg.sender, from, to, value, data);
}
/************************************************************************************************/
/********************************** Partition Token Transfers ***********************************/
/**
* @dev Transfer tokens from a specific partition.
* @param partition Name of the partition.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer, by the token holder.
* @return Destination partition.
*/
function transferByPartition(
bytes32 partition,
address to,
uint256 value,
bytes calldata data
)
external
returns (bytes32)
{
return _transferByPartition(partition, msg.sender, msg.sender, to, value, data, "");
}
/**
* @dev Transfer tokens from a specific partition through an operator.
* @param partition Name of the partition.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @param operatorData Information attached to the transfer, by the operator.
* @return Destination partition.
*/
function operatorTransferByPartition(
bytes32 partition,
address from,
address to,
uint256 value,
bytes calldata data,
bytes calldata operatorData
)
external
returns (bytes32)
{
require(_isOperatorForPartition(partition, msg.sender, from)
|| (value <= _allowedByPartition[partition][from][msg.sender]), "53"); // 0x53 insufficient allowance
if(_allowedByPartition[partition][from][msg.sender] >= value) {
_allowedByPartition[partition][from][msg.sender] = _allowedByPartition[partition][from][msg.sender].sub(value);
} else {
_allowedByPartition[partition][from][msg.sender] = 0;
}
return _transferByPartition(partition, msg.sender, from, to, value, data, operatorData);
}
/************************************************************************************************/
/************************************* Controller Operation *************************************/
/**
* @dev Know if the token can be controlled by operators.
* If a token returns 'false' for 'isControllable()'' then it MUST always return 'false' in the future.
* @return bool 'true' if the token can still be controlled by operators, 'false' if it can't anymore.
*/
function isControllable() external view returns (bool) {
return _isControllable;
}
/************************************************************************************************/
/************************************* Operator Management **************************************/
/**
* @dev Set a third party operator address as an operator of 'msg.sender' to transfer
* and redeem tokens on its behalf.
* @param operator Address to set as an operator for 'msg.sender'.
*/
function authorizeOperator(address operator) external {
require(operator != msg.sender);
_authorizedOperator[operator][msg.sender] = true;
emit AuthorizedOperator(operator, msg.sender);
}
/**
* @dev Remove the right of the operator address to be an operator for 'msg.sender'
* and to transfer and redeem tokens on its behalf.
* @param operator Address to rescind as an operator for 'msg.sender'.
*/
function revokeOperator(address operator) external {
require(operator != msg.sender);
_authorizedOperator[operator][msg.sender] = false;
emit RevokedOperator(operator, msg.sender);
}
/**
* @dev Set 'operator' as an operator for 'msg.sender' for a given partition.
* @param partition Name of the partition.
* @param operator Address to set as an operator for 'msg.sender'.
*/
function authorizeOperatorByPartition(bytes32 partition, address operator) external {
_authorizedOperatorByPartition[msg.sender][partition][operator] = true;
emit AuthorizedOperatorByPartition(partition, operator, msg.sender);
}
/**
* @dev Remove the right of the operator address to be an operator on a given
* partition for 'msg.sender' and to transfer and redeem tokens on its behalf.
* @param partition Name of the partition.
* @param operator Address to rescind as an operator on given partition for 'msg.sender'.
*/
function revokeOperatorByPartition(bytes32 partition, address operator) external {
_authorizedOperatorByPartition[msg.sender][partition][operator] = false;
emit RevokedOperatorByPartition(partition, operator, msg.sender);
}
/************************************************************************************************/
/************************************* Operator Information *************************************/
/**
* @dev Indicate whether the operator address is an operator of the tokenHolder address.
* @param operator Address which may be an operator of tokenHolder.
* @param tokenHolder Address of a token holder which may have the operator address as an operator.
* @return 'true' if operator is an operator of 'tokenHolder' and 'false' otherwise.
*/
function isOperator(address operator, address tokenHolder) external view returns (bool) {
return _isOperator(operator, tokenHolder);
}
/**
* @dev Indicate whether the operator address is an operator of the tokenHolder
* address for the given partition.
* @param partition Name of the partition.
* @param operator Address which may be an operator of tokenHolder for the given partition.
* @param tokenHolder Address of a token holder which may have the operator address as an operator for the given partition.
* @return 'true' if 'operator' is an operator of 'tokenHolder' for partition 'partition' and 'false' otherwise.
*/
function isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) external view returns (bool) {
return _isOperatorForPartition(partition, operator, tokenHolder);
}
/************************************************************************************************/
/**************************************** Token Issuance ****************************************/
/**
* @dev Know if new tokens can be issued in the future.
* @return bool 'true' if tokens can still be issued by the issuer, 'false' if they can't anymore.
*/
function isIssuable() external view returns (bool) {
return _isIssuable;
}
/**
* @dev Issue tokens from default partition.
* @param tokenHolder Address for which we want to issue tokens.
* @param value Number of tokens issued.
* @param data Information attached to the issuance, by the issuer.
*/
function issue(address tokenHolder, uint256 value, bytes calldata data)
external
onlyMinter
isIssuableToken
{
require(_defaultPartitions.length != 0, "55"); // 0x55 funds locked (lockup period)
_issueByPartition(_defaultPartitions[0], msg.sender, tokenHolder, value, data);
}
/**
* @dev Issue tokens from a specific partition.
* @param partition Name of the partition.
* @param tokenHolder Address for which we want to issue tokens.
* @param value Number of tokens issued.
* @param data Information attached to the issuance, by the issuer.
*/
function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data)
external
onlyMinter
isIssuableToken
{
_issueByPartition(partition, msg.sender, tokenHolder, value, data);
}
/************************************************************************************************/
/*************************************** Token Redemption ***************************************/
/**
* @dev Redeem the amount of tokens from the address 'msg.sender'.
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption, by the token holder.
*/
function redeem(uint256 value, bytes calldata data)
external
{
_redeemByDefaultPartitions(msg.sender, msg.sender, value, data);
}
/**
* @dev Redeem the amount of tokens on behalf of the address from.
* @param from Token holder whose tokens will be redeemed (or address(0) to set from to msg.sender).
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption.
*/
function redeemFrom(address from, uint256 value, bytes calldata data)
external
{
require(_isOperator(msg.sender, from), "58"); // 0x58 invalid operator (transfer agent)
_redeemByDefaultPartitions(msg.sender, from, value, data);
}
/**
* @dev Redeem tokens of a specific partition.
* @param partition Name of the partition.
* @param value Number of tokens redeemed.
* @param data Information attached to the redemption, by the redeemer.
*/
function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data)
external
{
_redeemByPartition(partition, msg.sender, msg.sender, value, data, "");
}
/**
* @dev Redeem tokens of a specific partition.
* @param partition Name of the partition.
* @param tokenHolder Address for which we want to redeem tokens.
* @param value Number of tokens redeemed
* @param operatorData Information attached to the redemption, by the operator.
*/
function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata operatorData)
external
{
require(_isOperatorForPartition(partition, msg.sender, tokenHolder), "58"); // 0x58 invalid operator (transfer agent)
_redeemByPartition(partition, msg.sender, tokenHolder, value, "", operatorData);
}
/************************************************************************************************/
/************************************************************************************************/
/************************ EXTERNAL FUNCTIONS (ADDITIONAL - NOT MANDATORY) ***********************/
/************************************************************************************************/
/************************************ Token description *****************************************/
/**
* @dev Get the name of the token, e.g., "MyToken".
* @return Name of the token.
*/
function name() external view returns(string memory) {
return _name;
}
/**
* @dev Get the symbol of the token, e.g., "MYT".
* @return Symbol of the token.
*/
function symbol() external view returns(string memory) {
return _symbol;
}
/**
* @dev Get the number of decimals of the token.
* @return The number of decimals of the token. For retrocompatibility, decimals are forced to 18 in ERC1400.
*/
function decimals() external pure returns(uint8) {
return uint8(18);
}
/**
* @dev Get the smallest part of the token that’s not divisible.
* @return The smallest non-divisible part of the token.
*/
function granularity() external view returns(uint256) {
return _granularity;
}
/**
* @dev Get list of existing partitions.
* @return Array of all exisiting partitions.
*/
function totalPartitions() external view returns (bytes32[] memory) {
return _totalPartitions;
}
/**
* @dev Get the total number of issued tokens for a given partition.
* @param partition Name of the partition.
* @return Total supply of tokens currently in circulation, for a given partition.
*/
function totalSupplyByPartition(bytes32 partition) external view returns (uint256) {
return _totalSupplyByPartition[partition];
}
/************************************************************************************************/
/**************************************** Token behaviours **************************************/
/**
* @dev Definitely renounce the possibility to control tokens on behalf of tokenHolders.
* Once set to false, '_isControllable' can never be set to 'true' again.
*/
function renounceControl() external onlyOwner {
_isControllable = false;
}
/**
* @dev Definitely renounce the possibility to issue new tokens.
* Once set to false, '_isIssuable' can never be set to 'true' again.
*/
function renounceIssuance() external onlyOwner {
_isIssuable = false;
}
/************************************************************************************************/
/************************************ Token controllers *****************************************/
/**
* @dev Get the list of controllers as defined by the token contract.
* @return List of addresses of all the controllers.
*/
function controllers() external view returns (address[] memory) {
return _controllers;
}
/**
* @dev Get controllers for a given partition.
* @param partition Name of the partition.
* @return Array of controllers for partition.
*/
function controllersByPartition(bytes32 partition) external view returns (address[] memory) {
return _controllersByPartition[partition];
}
/**
* @dev Set list of token controllers.
* @param operators Controller addresses.
*/
function setControllers(address[] calldata operators) external onlyOwner {
_setControllers(operators);
}
/**
* @dev Set list of token partition controllers.
* @param partition Name of the partition.
* @param operators Controller addresses.
*/
function setPartitionControllers(bytes32 partition, address[] calldata operators) external onlyOwner {
_setPartitionControllers(partition, operators);
}
/************************************************************************************************/
/********************************* Token default partitions *************************************/
/**
* @dev Get default partitions to transfer from.
* Function used for ERC20 retrocompatibility.
* For example, a security token may return the bytes32("unrestricted").
* @return Array of default partitions.
*/
function getDefaultPartitions() external view returns (bytes32[] memory) {
return _defaultPartitions;
}
/**
* @dev Set default partitions to transfer from.
* Function used for ERC20 retrocompatibility.
* @param partitions partitions to use by default when not specified.
*/
function setDefaultPartitions(bytes32[] calldata partitions) external onlyOwner {
_defaultPartitions = partitions;
}
/************************************************************************************************/
/******************************** Partition Token Allowances ************************************/
/**
* @dev Check the value of tokens that an owner allowed to a spender.
* @param partition Name of the partition.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the value of tokens still available for the spender.
*/
function allowanceByPartition(bytes32 partition, address owner, address spender) external view returns (uint256) {
return _allowedByPartition[partition][owner][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of 'msg.sender'.
* @param partition Name of the partition.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean that indicates if the operation was successful.
*/
function approveByPartition(bytes32 partition, address spender, uint256 value) external returns (bool) {
require(spender != address(0), "56"); // 0x56 invalid sender
_allowedByPartition[partition][msg.sender][spender] = value;
emit ApprovalByPartition(partition, msg.sender, spender, value);
return true;
}
/************************************************************************************************/
/************************************** Token extension *****************************************/
/**
* @dev Set token extension contract address.
* The extension contract can for example verify "ERC1400TokensValidator" or "ERC1400TokensChecker" interfaces.
* If the extension is an "ERC1400TokensValidator", it will be called everytime a transfer is executed.
* @param extension Address of the extension contract.
* @param interfaceLabel Interface label of extension contract.
* @param removeOldExtensionRoles If set to 'true', the roles of the old extension(minter, controller) will be removed extension.
* @param addMinterRoleForExtension If set to 'true', the extension contract will be added as minter.
* @param addControllerRoleForExtension If set to 'true', the extension contract will be added as controller.
*/
function setTokenExtension(address extension, string calldata interfaceLabel, bool removeOldExtensionRoles, bool addMinterRoleForExtension, bool addControllerRoleForExtension) external onlyOwner {
_setTokenExtension(extension, interfaceLabel, removeOldExtensionRoles, addMinterRoleForExtension, addControllerRoleForExtension);
}
/************************************************************************************************/
/************************************* Token migration ******************************************/
/**
* @dev Migrate contract.
*
* ===> CAUTION: DEFINITIVE ACTION
*
* This function shall be called once a new version of the smart contract has been created.
* Once this function is called:
* - The address of the new smart contract is set in ERC1820 registry
* - If the choice is definitive, the current smart contract is turned off and can never be used again
*
* @param newContractAddress Address of the new version of the smart contract.
* @param definitive If set to 'true' the contract is turned off definitely.
*/
function migrate(address newContractAddress, bool definitive) external onlyOwner {
_migrate(newContractAddress, definitive);
}
/************************************************************************************************/
/************************************************************************************************/
/************************************* INTERNAL FUNCTIONS ***************************************/
/************************************************************************************************/
/**************************************** Token Transfers ***************************************/
/**
* @dev Perform the transfer of tokens.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
*/
function _transferWithData(
address from,
address to,
uint256 value
)
internal
isNotMigratedToken
{
require(_isMultiple(value), "50"); // 0x50 transfer failure
require(to != address(0), "57"); // 0x57 invalid receiver
require(_balances[from] >= value, "52"); // 0x52 insufficient balance
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value); // ERC20 retrocompatibility
}
/**
* @dev Transfer tokens from a specific partition.
* @param fromPartition Partition of the tokens to transfer.
* @param operator The address performing the transfer.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @param operatorData Information attached to the transfer, by the operator (if any).
* @return Destination partition.
*/
function _transferByPartition(
bytes32 fromPartition,
address operator,
address from,
address to,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
returns (bytes32)
{
require(_balanceOfByPartition[from][fromPartition] >= value, "52"); // 0x52 insufficient balance
bytes32 toPartition = fromPartition;
if(operatorData.length != 0 && data.length >= 64) {
toPartition = _getDestinationPartition(fromPartition, data);
}
_callSenderExtension(fromPartition, operator, from, to, value, data, operatorData);
_callTokenExtension(fromPartition, operator, from, to, value, data, operatorData);
_removeTokenFromPartition(from, fromPartition, value);
_transferWithData(from, to, value);
_addTokenToPartition(to, toPartition, value);
_callRecipientExtension(toPartition, operator, from, to, value, data, operatorData);
emit TransferByPartition(fromPartition, operator, from, to, value, data, operatorData);
if(toPartition != fromPartition) {
emit ChangedPartition(fromPartition, toPartition, value);
}
return toPartition;
}
/**
* @dev Transfer tokens from default partitions.
* Function used for ERC20 retrocompatibility.
* @param operator The address performing the transfer.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer, and intended for the token holder ('from') [CAN CONTAIN THE DESTINATION PARTITION].
*/
function _transferByDefaultPartitions(
address operator,
address from,
address to,
uint256 value,
bytes memory data
)
internal
{
require(_defaultPartitions.length != 0, "55"); // // 0x55 funds locked (lockup period)
uint256 _remainingValue = value;
uint256 _localBalance;
for (uint i = 0; i < _defaultPartitions.length; i++) {
_localBalance = _balanceOfByPartition[from][_defaultPartitions[i]];
if(_remainingValue <= _localBalance) {
_transferByPartition(_defaultPartitions[i], operator, from, to, _remainingValue, data, "");
_remainingValue = 0;
break;
} else if (_localBalance != 0) {
_transferByPartition(_defaultPartitions[i], operator, from, to, _localBalance, data, "");
_remainingValue = _remainingValue - _localBalance;
}
}
require(_remainingValue == 0, "52"); // 0x52 insufficient balance
}
/**
* @dev Retrieve the destination partition from the 'data' field.
* By convention, a partition change is requested ONLY when 'data' starts
* with the flag: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
* When the flag is detected, the destination tranche is extracted from the
* 32 bytes following the flag.
* @param fromPartition Partition of the tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @return Destination partition.
*/
function _getDestinationPartition(bytes32 fromPartition, bytes memory data) internal pure returns(bytes32 toPartition) {
bytes32 changePartitionFlag = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
bytes32 flag;
assembly {
flag := mload(add(data, 32))
}
if(flag == changePartitionFlag) {
assembly {
toPartition := mload(add(data, 64))
}
} else {
toPartition = fromPartition;
}
}
/**
* @dev Remove a token from a specific partition.
* @param from Token holder.
* @param partition Name of the partition.
* @param value Number of tokens to transfer.
*/
function _removeTokenFromPartition(address from, bytes32 partition, uint256 value) internal {
_balanceOfByPartition[from][partition] = _balanceOfByPartition[from][partition].sub(value);
_totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].sub(value);
// If the total supply is zero, finds and deletes the partition.
if(_totalSupplyByPartition[partition] == 0) {
uint256 index1 = _indexOfTotalPartitions[partition];
require(index1 > 0, "50"); // 0x50 transfer failure
// move the last item into the index being vacated
bytes32 lastValue = _totalPartitions[_totalPartitions.length - 1];
_totalPartitions[index1 - 1] = lastValue; // adjust for 1-based indexing
_indexOfTotalPartitions[lastValue] = index1;
_totalPartitions.length -= 1;
_indexOfTotalPartitions[partition] = 0;
}
// If the balance of the TokenHolder's partition is zero, finds and deletes the partition.
if(_balanceOfByPartition[from][partition] == 0) {
uint256 index2 = _indexOfPartitionsOf[from][partition];
require(index2 > 0, "50"); // 0x50 transfer failure
// move the last item into the index being vacated
bytes32 lastValue = _partitionsOf[from][_partitionsOf[from].length - 1];
_partitionsOf[from][index2 - 1] = lastValue; // adjust for 1-based indexing
_indexOfPartitionsOf[from][lastValue] = index2;
_partitionsOf[from].length -= 1;
_indexOfPartitionsOf[from][partition] = 0;
}
}
/**
* @dev Add a token to a specific partition.
* @param to Token recipient.
* @param partition Name of the partition.
* @param value Number of tokens to transfer.
*/
function _addTokenToPartition(address to, bytes32 partition, uint256 value) internal {
if(value != 0) {
if (_indexOfPartitionsOf[to][partition] == 0) {
_partitionsOf[to].push(partition);
_indexOfPartitionsOf[to][partition] = _partitionsOf[to].length;
}
_balanceOfByPartition[to][partition] = _balanceOfByPartition[to][partition].add(value);
if (_indexOfTotalPartitions[partition] == 0) {
_totalPartitions.push(partition);
_indexOfTotalPartitions[partition] = _totalPartitions.length;
}
_totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].add(value);
}
}
/**
* @dev Check if 'value' is multiple of the granularity.
* @param value The quantity that want's to be checked.
* @return 'true' if 'value' is a multiple of the granularity.
*/
function _isMultiple(uint256 value) internal view returns(bool) {
return(value.div(_granularity).mul(_granularity) == value);
}
/************************************************************************************************/
/****************************************** Hooks ***********************************************/
/**
* @dev Check for 'ERC1400TokensSender' user extension in ERC1820 registry and call it.
* @param partition Name of the partition (bytes32 to be left empty for transfers where partition is not specified).
* @param operator Address which triggered the balance decrease (through transfer or redemption).
* @param from Token holder.
* @param to Token recipient for a transfer and 0x for a redemption.
* @param value Number of tokens the token holder balance is decreased by.
* @param data Extra information.
* @param operatorData Extra information, attached by the operator (if any).
*/
function _callSenderExtension(
bytes32 partition,
address operator,
address from,
address to,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
{
address senderImplementation;
senderImplementation = interfaceAddr(from, ERC1400_TOKENS_SENDER);
if (senderImplementation != address(0)) {
IERC1400TokensSender(senderImplementation).tokensToTransfer(msg.data, partition, operator, from, to, value, data, operatorData);
}
}
/**
* @dev Check for 'ERC1400TokensValidator' token extension in ERC1820 registry and call it.
* @param partition Name of the partition (bytes32 to be left empty for transfers where partition is not specified).
* @param operator Address which triggered the balance decrease (through transfer or redemption).
* @param from Token holder.
* @param to Token recipient for a transfer and 0x for a redemption.
* @param value Number of tokens the token holder balance is decreased by.
* @param data Extra information.
* @param operatorData Extra information, attached by the operator (if any).
*/
function _callTokenExtension(
bytes32 partition,
address operator,
address from,
address to,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
{
address validatorImplementation;
validatorImplementation = interfaceAddr(address(this), ERC1400_TOKENS_VALIDATOR);
if (validatorImplementation != address(0)) {
IERC1400TokensValidator(validatorImplementation).tokensToValidate(msg.data, partition, operator, from, to, value, data, operatorData);
}
}
/**
* @dev Check for 'ERC1400TokensRecipient' user extension in ERC1820 registry and call it.
* @param partition Name of the partition (bytes32 to be left empty for transfers where partition is not specified).
* @param operator Address which triggered the balance increase (through transfer or issuance).
* @param from Token holder for a transfer and 0x for an issuance.
* @param to Token recipient.
* @param value Number of tokens the recipient balance is increased by.
* @param data Extra information, intended for the token holder ('from').
* @param operatorData Extra information attached by the operator (if any).
*/
function _callRecipientExtension(
bytes32 partition,
address operator,
address from,
address to,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
{
address recipientImplementation;
recipientImplementation = interfaceAddr(to, ERC1400_TOKENS_RECIPIENT);
if (recipientImplementation != address(0)) {
IERC1400TokensRecipient(recipientImplementation).tokensReceived(msg.data, partition, operator, from, to, value, data, operatorData);
}
}
/************************************************************************************************/
/************************************* Operator Information *************************************/
/**
* @dev Indicate whether the operator address is an operator of the tokenHolder address.
* @param operator Address which may be an operator of 'tokenHolder'.
* @param tokenHolder Address of a token holder which may have the 'operator' address as an operator.
* @return 'true' if 'operator' is an operator of 'tokenHolder' and 'false' otherwise.
*/
function _isOperator(address operator, address tokenHolder) internal view returns (bool) {
return (operator == tokenHolder
|| _authorizedOperator[operator][tokenHolder]
|| (_isControllable && _isController[operator])
);
}
/**
* @dev Indicate whether the operator address is an operator of the tokenHolder
* address for the given partition.
* @param partition Name of the partition.
* @param operator Address which may be an operator of tokenHolder for the given partition.
* @param tokenHolder Address of a token holder which may have the operator address as an operator for the given partition.
* @return 'true' if 'operator' is an operator of 'tokenHolder' for partition 'partition' and 'false' otherwise.
*/
function _isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) internal view returns (bool) {
return (_isOperator(operator, tokenHolder)
|| _authorizedOperatorByPartition[tokenHolder][partition][operator]
|| (_isControllable && _isControllerByPartition[partition][operator])
);
}
/************************************************************************************************/
/**************************************** Token Issuance ****************************************/
/**
* @dev Perform the issuance of tokens.
* @param operator Address which triggered the issuance.
* @param to Token recipient.
* @param value Number of tokens issued.
* @param data Information attached to the issuance, and intended for the recipient (to).
*/
function _issue(address operator, address to, uint256 value, bytes memory data)
internal
isNotMigratedToken
{
require(_isMultiple(value), "50"); // 0x50 transfer failure
require(to != address(0), "57"); // 0x57 invalid receiver
_totalSupply = _totalSupply.add(value);
_balances[to] = _balances[to].add(value);
emit Issued(operator, to, value, data);
emit Transfer(address(0), to, value); // ERC20 retrocompatibility
}
/**
* @dev Issue tokens from a specific partition.
* @param toPartition Name of the partition.
* @param operator The address performing the issuance.
* @param to Token recipient.
* @param value Number of tokens to issue.
* @param data Information attached to the issuance.
*/
function _issueByPartition(
bytes32 toPartition,
address operator,
address to,
uint256 value,
bytes memory data
)
internal
{
_callTokenExtension(toPartition, operator, address(0), to, value, data, "");
_issue(operator, to, value, data);
_addTokenToPartition(to, toPartition, value);
_callRecipientExtension(toPartition, operator, address(0), to, value, data, "");
emit IssuedByPartition(toPartition, operator, to, value, data, "");
}
/************************************************************************************************/
/*************************************** Token Redemption ***************************************/
/**
* @dev Perform the token redemption.
* @param operator The address performing the redemption.
* @param from Token holder whose tokens will be redeemed.
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption.
*/
function _redeem(address operator, address from, uint256 value, bytes memory data)
internal
isNotMigratedToken
{
require(_isMultiple(value), "50"); // 0x50 transfer failure
require(from != address(0), "56"); // 0x56 invalid sender
require(_balances[from] >= value, "52"); // 0x52 insufficient balance
_balances[from] = _balances[from].sub(value);
_totalSupply = _totalSupply.sub(value);
emit Redeemed(operator, from, value, data);
emit Transfer(from, address(0), value); // ERC20 retrocompatibility
}
/**
* @dev Redeem tokens of a specific partition.
* @param fromPartition Name of the partition.
* @param operator The address performing the redemption.
* @param from Token holder whose tokens will be redeemed.
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption.
* @param operatorData Information attached to the redemption, by the operator (if any).
*/
function _redeemByPartition(
bytes32 fromPartition,
address operator,
address from,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
{
require(_balanceOfByPartition[from][fromPartition] >= value, "52"); // 0x52 insufficient balance
_callSenderExtension(fromPartition, operator, from, address(0), value, data, operatorData);
_callTokenExtension(fromPartition, operator, from, address(0), value, data, operatorData);
_removeTokenFromPartition(from, fromPartition, value);
_redeem(operator, from, value, data);
emit RedeemedByPartition(fromPartition, operator, from, value, operatorData);
}
/**
* @dev Redeem tokens from a default partitions.
* @param operator The address performing the redeem.
* @param from Token holder.
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption.
*/
function _redeemByDefaultPartitions(
address operator,
address from,
uint256 value,
bytes memory data
)
internal
{
require(_defaultPartitions.length != 0, "55"); // 0x55 funds locked (lockup period)
uint256 _remainingValue = value;
uint256 _localBalance;
for (uint i = 0; i < _defaultPartitions.length; i++) {
_localBalance = _balanceOfByPartition[from][_defaultPartitions[i]];
if(_remainingValue <= _localBalance) {
_redeemByPartition(_defaultPartitions[i], operator, from, _remainingValue, data, "");
_remainingValue = 0;
break;
} else {
_redeemByPartition(_defaultPartitions[i], operator, from, _localBalance, data, "");
_remainingValue = _remainingValue - _localBalance;
}
}
require(_remainingValue == 0, "52"); // 0x52 insufficient balance
}
/************************************************************************************************/
/************************************** Transfer Validity ***************************************/
/**
* @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes.
* @param payload Payload of the initial transaction.
* @param partition Name of the partition.
* @param operator The address performing the transfer.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @param operatorData Information attached to the transfer, by the operator (if any).
* @return ESC (Ethereum Status Code) following the EIP-1066 standard.
* @return Additional bytes32 parameter that can be used to define
* application specific reason codes with additional details (for example the
* transfer restriction rule responsible for making the transfer operation invalid).
* @return Destination partition.
*/
function _canTransfer(bytes memory payload, bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData)
internal
view
returns (byte, bytes32, bytes32)
{
address checksImplementation = interfaceAddr(address(this), ERC1400_TOKENS_CHECKER);
if((checksImplementation != address(0))) {
return IERC1400TokensChecker(checksImplementation).canTransferByPartition(payload, partition, operator, from, to, value, data, operatorData);
}
else {
return(hex"00", "", partition);
}
}
/************************************************************************************************/
/************************************************************************************************/
/************************ INTERNAL FUNCTIONS (ADDITIONAL - NOT MANDATORY) ***********************/
/************************************************************************************************/
/************************************ Token controllers *****************************************/
/**
* @dev Set list of token controllers.
* @param operators Controller addresses.
*/
function _setControllers(address[] memory operators) internal {
for (uint i = 0; i<_controllers.length; i++){
_isController[_controllers[i]] = false;
}
for (uint j = 0; j<operators.length; j++){
_isController[operators[j]] = true;
}
_controllers = operators;
}
/**
* @dev Set list of token partition controllers.
* @param partition Name of the partition.
* @param operators Controller addresses.
*/
function _setPartitionControllers(bytes32 partition, address[] memory operators) internal {
for (uint i = 0; i<_controllersByPartition[partition].length; i++){
_isControllerByPartition[partition][_controllersByPartition[partition][i]] = false;
}
for (uint j = 0; j<operators.length; j++){
_isControllerByPartition[partition][operators[j]] = true;
}
_controllersByPartition[partition] = operators;
}
/************************************************************************************************/
/************************************** Token extension *****************************************/
/**
* @dev Set token extension contract address.
* The extension contract can for example verify "ERC1400TokensValidator" or "ERC1400TokensChecker" interfaces.
* If the extension is an "ERC1400TokensValidator", it will be called everytime a transfer is executed.
* @param extension Address of the extension contract.
* @param interfaceLabel Interface label of extension contract.
* @param removeOldExtensionRoles If set to 'true', the roles of the old extension(minter, controller) will be removed extension.
* @param addMinterRoleForExtension If set to 'true', the extension contract will be added as minter.
* @param addControllerRoleForExtension If set to 'true', the extension contract will be added as controller.
*/
function _setTokenExtension(address extension, string memory interfaceLabel, bool removeOldExtensionRoles, bool addMinterRoleForExtension, bool addControllerRoleForExtension) internal {
address oldExtension = interfaceAddr(address(this), interfaceLabel);
if (oldExtension != address(0) && removeOldExtensionRoles) {
if(isMinter(oldExtension)) {
_removeMinter(oldExtension);
}
_isController[oldExtension] = false;
}
ERC1820Client.setInterfaceImplementation(interfaceLabel, extension);
if(addMinterRoleForExtension && !isMinter(extension)) {
_addMinter(extension);
}
if (addControllerRoleForExtension) {
_isController[extension] = true;
}
}
/************************************************************************************************/
/************************************* Token migration ******************************************/
/**
* @dev Migrate contract.
*
* ===> CAUTION: DEFINITIVE ACTION
*
* This function shall be called once a new version of the smart contract has been created.
* Once this function is called:
* - The address of the new smart contract is set in ERC1820 registry
* - If the choice is definitive, the current smart contract is turned off and can never be used again
*
* @param newContractAddress Address of the new version of the smart contract.
* @param definitive If set to 'true' the contract is turned off definitely.
*/
function _migrate(address newContractAddress, bool definitive) internal {
ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, newContractAddress);
ERC1820Client.setInterfaceImplementation(ERC1400_INTERFACE_NAME, newContractAddress);
if(definitive) {
_migrated = true;
}
}
/************************************************************************************************/
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @notice Interface to the extension types
*/
interface IExtensionTypes {
enum CertificateValidation {
None,
NonceBased,
SaltBased
}
}
/**
* @notice Interface to the extension contract
*/
contract Extension is IExtensionTypes {
function registerTokenSetup(
address token,
CertificateValidation certificateActivated,
bool allowlistActivated,
bool blocklistActivated,
bool granularityByPartitionActivated,
bool holdsActivated,
address[] calldata operators
) external;
function addCertificateSigner(
address token,
address account
) external;
}
/**
* @title ERC1400HoldableCertificateNonceToken
* @dev Holdable ERC1400 with nonce-based certificate controller logic
*/
contract ERC1400HoldableCertificateToken is ERC1400, IExtensionTypes {
string constant internal ERC1400_TOKENS_VALIDATOR = "ERC1400TokensValidator";
/**
* @dev Initialize ERC1400 + initialize certificate controller.
* @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 defaultPartitions Partitions chosen by default, when partition is
* not specified, like the case ERC20 tranfers.
* @param extension Address of token extension.
* @param newOwner Address whom contract ownership shall be transferred to.
* @param certificateSigner Address of the off-chain service which signs the
* conditional ownership certificates required for token transfers, issuance,
* redemption (Cf. CertificateController.sol).
* @param certificateActivated If set to 'true', the certificate controller
* is activated at contract creation.
*/
constructor(
string memory name,
string memory symbol,
uint256 granularity,
address[] memory controllers,
bytes32[] memory defaultPartitions,
address extension,
address newOwner,
address certificateSigner,
CertificateValidation certificateActivated
)
public
ERC1400(name, symbol, granularity, controllers, defaultPartitions)
{
if(extension != address(0)) {
Extension(extension).registerTokenSetup(
address(this), // token
certificateActivated, // certificateActivated
true, // allowlistActivated
true, // blocklistActivated
true, // granularityByPartitionActivated
true, // holdsActivated
controllers // token controllers
);
if(certificateSigner != address(0)) {
Extension(extension).addCertificateSigner(address(this), certificateSigner);
}
_setTokenExtension(extension, ERC1400_TOKENS_VALIDATOR, true, true, true);
}
if(newOwner != address(0)) {
_transferOwnership(newOwner);
}
}
/************************************** Transfer Validity ***************************************/
/**
* @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes.
* @param partition Name of the partition.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE]
* @return ESC (Ethereum Status Code) following the EIP-1066 standard.
* @return Additional bytes32 parameter that can be used to define
* application specific reason codes with additional details (for example the
* transfer restriction rule responsible for making the transfer operation invalid).
* @return Destination partition.
*/
function canTransferByPartition(bytes32 partition, address to, uint256 value, bytes calldata data)
external
view
returns (byte, bytes32, bytes32)
{
return ERC1400._canTransfer(
_replaceFunctionSelector(this.transferByPartition.selector, msg.data), // 0xf3d490db: 4 first bytes of keccak256(transferByPartition(bytes32,address,uint256,bytes))
partition,
msg.sender,
msg.sender,
to,
value,
data,
""
);
}
/**
* @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes.
* @param partition Name of the partition.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @param operatorData Information attached to the transfer, by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE]
* @return ESC (Ethereum Status Code) following the EIP-1066 standard.
* @return Additional bytes32 parameter that can be used to define
* application specific reason codes with additional details (for example the
* transfer restriction rule responsible for making the transfer operation invalid).
* @return Destination partition.
*/
function canOperatorTransferByPartition(bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData)
external
view
returns (byte, bytes32, bytes32)
{
return ERC1400._canTransfer(
_replaceFunctionSelector(this.operatorTransferByPartition.selector, msg.data), // 0x8c0dee9c: 4 first bytes of keccak256(operatorTransferByPartition(bytes32,address,address,uint256,bytes,bytes))
partition,
msg.sender,
from,
to,
value,
data,
operatorData
);
}
/**
* @dev Replace function selector
* @param functionSig Replacement function selector.
* @param payload Payload, where function selector needs to be replaced.
*/
function _replaceFunctionSelector(bytes4 functionSig, bytes memory payload) internal pure returns(bytes memory) {
bytes memory updatedPayload = new bytes(payload.length);
for (uint i = 0; i<4; i++){
updatedPayload[i] = functionSig[i];
}
for (uint j = 4; j<payload.length; j++){
updatedPayload[j] = payload[j];
}
return updatedPayload;
}
/************************************************************************************************/
} | * @dev Modifier to verifiy if sender is a minter./ | modifier onlyMinter() {
require(isMinter(msg.sender) || isOwner());
_;
}
string memory name,
string memory symbol,
uint256 granularity,
address[] memory controllers,
bytes32[] memory defaultPartitions
)
public
| 10,075,019 | [
1,
9829,
358,
1924,
704,
93,
309,
5793,
353,
279,
1131,
387,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
9606,
1338,
49,
2761,
1435,
288,
203,
1377,
2583,
12,
291,
49,
2761,
12,
3576,
18,
15330,
13,
747,
353,
5541,
10663,
203,
1377,
389,
31,
203,
225,
289,
203,
203,
203,
565,
533,
3778,
508,
16,
203,
565,
533,
3778,
3273,
16,
203,
565,
2254,
5034,
25380,
16,
203,
565,
1758,
8526,
3778,
12403,
16,
203,
565,
1731,
1578,
8526,
3778,
805,
13738,
203,
225,
262,
203,
565,
1071,
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
]
|
pragma solidity ^0.4.24;
/*Interface to ProductEngine library */
library IProductEngine {
//Purchase information
struct Purchase {
uint256 id; //purchase id
address buyer; //who made a purchase
string clientId; //product-specific client id
uint256 price; //unit price at the moment of purchase
uint256 paidUnits; //how many units
bool delivered; //true if Product was delivered
bool badRating; //true if user changed rating to 'bad'
}
/**@dev
Storage data of product
1. A couple of words on 'denominator'. It shows how many smallest units can 1 unit be splitted into.
'price' field still represents price per one unit. One unit = 'denominator' * smallest unit.
'maxUnits', 'soldUnits' and 'paidUnits' show number of smallest units.
For simple products which can't be fractioned 'denominator' should equal 1.
For example: denominator = 1,000, 'price' = 100,000.
a. If user pays for one product (100,000), his 'paidUnits' field will be 1000.
b. If 'buy' function receives 50,000, that means user is going to buy
a half of the product, and 'paidUnits' will be calculated as 500.
c.If 'buy' function receives 100, that means user wants to buy the smallest unit possible
and 'paidUnits' will be 1;
Therefore 'paidUnits' = 'weiReceived' * 'denominator' / 'price'
*/
struct ProductData {
address owner; //VendorBase - product's owner
string name; //Name of the product
uint256 price; //Price of one product unit
uint256 maxUnits; //Max quantity of limited product units, or 0 if unlimited
bool isActive; //True if it is possible to buy a product
uint256 soldUnits; //How many units already sold
uint256 denominator; //This shows how many decimal digits the smallest unit fraction can hold
mapping (address => uint256) pendingWithdrawals; //List of overpays to withdraw
Purchase[] purchases; //Array of purchase information
mapping (address => uint256) userRating; //index of first-purchase structure in Purchase[] array. Starts with 1 so you need to subtract 1 to get actual!
}
/**@dev
Calculates and returns payment details: how many units are bought,
what part of ether should be paid and what part should be returned to buyer */
function calculatePaymentDetails(IProductEngine.ProductData storage self, uint256 weiAmount, bool acceptLessUnits)
public
view
returns(uint256 unitsToBuy, uint256 etherToPay, uint256 etherToReturn)
{
self; unitsToBuy; etherToPay; etherToReturn; weiAmount; acceptLessUnits;
}
/**@dev
Buy product. Send ether with this function in amount equal to desirable product quantity total price
* clientId - Buyer's product-specific information.
* acceptLessUnits - 'true' if buyer doesn't care of buying the exact amount of limited products.
If N units left and buyer sends payment for N+1 units then settings this flag to 'true' will result in
buying N units, while 'false' will simply decline transaction
* currentPrice - current product price as shown in 'price' property.
Used for security reasons to compare actual price with the price at the moment of transaction.
If they are not equal, transaction is declined */
function buy(IProductEngine.ProductData storage self, string clientId, bool acceptLessUnits, uint256 currentPrice) public;
/**@dev
Call this to return all previous overpays */
function withdrawOverpay(IProductEngine.ProductData storage self) public;
/**@dev
Marks purchase with given id as delivered or not */
function markAsDelivered(IProductEngine.ProductData storage self, uint256 purchaseId, bool state) public;
/**@dev
Changes parameters of product */
function setParams(
IProductEngine.ProductData storage self,
string newName,
uint256 newPrice,
uint256 newMaxUnits,
bool newIsActive
) public;
/**@dev Changes rating of product */
function changeRating(IProductEngine.ProductData storage self, bool newLikeState) public;
}
| true if user changed rating to 'bad'
| bool badRating; | 2,567,565 | [
1,
3767,
309,
729,
3550,
13953,
358,
296,
8759,
11,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
1426,
5570,
20388,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-09-29
*/
pragma solidity >=0.5.10 <0.6.0;
/**
Total 20m (20.000.000)
IVT
Investicoin
decimals 5
*/
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) {
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;
}
}
/**
* @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);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
*/
contract ERC20Token is IERC20 {
using SafeMath for uint256;
string public symbol;
string public name;
uint256 public decimals;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
constructor() public {
symbol = "IVT"; // define token symbol here
name = "Investicoin"; // define token name here
decimals = 5; // define decimals here
_totalSupply = 20000000*10**decimals; // define total supply here with decimals
_balances[msg.sender] = _totalSupply; // set supply owner here
emit Transfer(address(0), msg.sender, _totalSupply); // set supply owner here
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () external payable {
revert("Don't receive ether");
}
} | set supply owner here
| _balances[msg.sender] = _totalSupply; | 2,065,269 | [
1,
542,
14467,
3410,
2674,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
389,
70,
26488,
63,
3576,
18,
15330,
65,
273,
389,
4963,
3088,
1283,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
// Deployed at 0x06af8345c1266ee172ee66a31e2be65bf9aa7b46 on Ropsten!
contract SecretEventOrg{
address public organizer; // Address of organizer
string public encryption_key; // Linnia encryption_key of event organizer
struct Member { // Member infromation type
address addr;
uint provenance;
address initiator;
uint referrals_remaining;
string public_key;
}
struct SecretEvent { // Event information
string eventName;
string describe;
uint capacity;
uint deposit;
uint start_time;
uint duration;
uint totalAttending; // Total member who are attending event
string location; // = "SECRET : Will be disclosed to members";
string details; // = "SECRET : Will be disclosed to members";
}
address[] public innerCircle; // Address of members
uint numEvents = 0; // Total events successful so far
uint MAX_REFERRALS = 5;
mapping (address => Member) memberInfo; // Mapping from member address to member information
mapping (address => address) referralInfo; // Refered friend to member mapping
mapping (bytes32 => SecretEvent) public eventInfo; // Information on events created by this organizer
bytes32 public currentEventHash;
// Constructor
constructor(string public_key) public {
organizer = msg.sender;
encryption_key = public_key;
memberInfo[organizer] = Member(organizer, 0, 0, MAX_REFERRALS, public_key);
}
// Organizer only
modifier _onlyOrganizer(address _caller) {
require(_caller == organizer, "Unauthorized request, organizer only");
_;
}
// Member only
modifier _onlyMember(address _caller) {
require(_caller == memberInfo[_caller].addr, "Members only");
_;
}
// Check if current event expired
modifier _eventNotExpired(bytes32 id) {
require(eventInfo[id].start_time != 0 && now < eventInfo[id].start_time, "can't create a new event");
_;
}
// Check if maximum event capacity reached
modifier _maxEventCap(bytes32 id) {
require(eventInfo[id].capacity > 0, "Maximum capacity reached");
_;
}
// Check if member is allowed to refer more friends
modifier _referralsAllowed(address caller) {
require(memberInfo[caller].referrals_remaining > 0, "Cant refer more people");
_;
}
// Check if friend is already referred by other member
modifier _notAlreadyReferred(address addr) {
require(referralInfo[addr] == 0, "Someone already referred your friend");
_;
}
// Check if friend is already referred by other member
modifier _alreadyReferred(address addr) {
require(referralInfo[addr] != 0, "Referral by a Member is required");
_;
}
modifier _eventDoesntExists(bytes32 id) {
require(eventInfo[id].start_time == 0, "Event already exists, cant add");
_;
}
modifier _ifDepositEnough(bytes32 id, uint val) {
require(val >= eventInfo[id].deposit, "Not enough money" );
_;
}
// Member refers a friend
function referFriend(address _addr) public _onlyMember(msg.sender) _referralsAllowed(msg.sender) _notAlreadyReferred(_addr) {
referralInfo[_addr] = msg.sender;
memberInfo[msg.sender].referrals_remaining--;
}
// Referred friend applies for membership
function applyMembership(string public_key) public payable _alreadyReferred(msg.sender) {
memberInfo[msg.sender] = Member(msg.sender, memberInfo[referralInfo[msg.sender]].provenance+1, referralInfo[msg.sender], MAX_REFERRALS, public_key);
referralInfo[msg.sender] = 0;
innerCircle.push(msg.sender);
}
// Add Event
function addEvent(bytes32 id, string name, string describe, uint capacity, uint deposit, uint start_time, uint duration) public _onlyOrganizer(msg.sender) _eventDoesntExists(id){
eventInfo[id] = SecretEvent(name, describe, capacity, deposit, now+start_time, duration, 0, "SECRET: revealed to members", "SECRET: revealed to members");
numEvents++;
currentEventHash = id;
}
// Attend Event
function attendEvent(bytes32 id) public payable _onlyMember(msg.sender) _eventNotExpired(id) _maxEventCap(id) _ifDepositEnough(id, msg.value){
if (msg.value > eventInfo[id].deposit){
uint balance = msg.value - eventInfo[id].deposit;
msg.sender.transfer(balance);
}
eventInfo[id].totalAttending++;
}
// Returns event info
function getEventInfo(bytes32 _recordHash) public view returns(string eventName, string describe, uint capacity, uint deposit, uint start_time, uint duration, uint totalAttending){
return (eventInfo[_recordHash].eventName, eventInfo[_recordHash].describe, eventInfo[_recordHash].capacity, eventInfo[_recordHash].deposit, eventInfo[_recordHash].start_time, eventInfo[_recordHash].duration, eventInfo[_recordHash].totalAttending);
}
// Returns member info
function getMemberInfo(address _addr) public view returns(uint provenance, address initiator, uint referrals_remaining, string public_key){
return (memberInfo[_addr].provenance, memberInfo[_addr].initiator, memberInfo[_addr].referrals_remaining, memberInfo[_addr].public_key);
}
// Checks if address was referred.
function checkIfReferred(address addr) public view returns(bool) {
return referralInfo[addr] != 0;
}
// Checks if address is a member.
function checkIfMember(address addr) public view returns(bool) {
return memberInfo[addr].addr != 0;
}
// organizer adds members
function addMember(address newMember, string memberPublicKey) public _onlyOrganizer(msg.sender) {
memberInfo[newMember] = Member(newMember, 1, organizer, MAX_REFERRALS, memberPublicKey);
innerCircle.push(newMember);
}
} | Referred friend applies for membership | function applyMembership(string public_key) public payable _alreadyReferred(msg.sender) {
memberInfo[msg.sender] = Member(msg.sender, memberInfo[referralInfo[msg.sender]].provenance+1, referralInfo[msg.sender], MAX_REFERRALS, public_key);
referralInfo[msg.sender] = 0;
innerCircle.push(msg.sender);
}
| 5,413,108 | [
1,
426,
4193,
24271,
10294,
364,
12459,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2230,
13447,
12,
1080,
1071,
67,
856,
13,
1071,
8843,
429,
389,
17583,
426,
4193,
12,
3576,
18,
15330,
13,
288,
203,
3639,
3140,
966,
63,
3576,
18,
15330,
65,
273,
8596,
12,
3576,
18,
15330,
16,
3140,
966,
63,
1734,
29084,
966,
63,
3576,
18,
15330,
65,
8009,
25630,
15,
21,
16,
1278,
29084,
966,
63,
3576,
18,
15330,
6487,
4552,
67,
30269,
54,
1013,
55,
16,
1071,
67,
856,
1769,
203,
3639,
1278,
29084,
966,
63,
3576,
18,
15330,
65,
273,
374,
31,
203,
3639,
3443,
19490,
18,
6206,
12,
3576,
18,
15330,
1769,
203,
565,
289,
7010,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/71402/0xfcDBe55aB9969745c16D223d0703620B5bFB3383/sources/contracts/protocol/libraries/logic/ValidationLogic.sol | validate interest rate modeadd the current already borrowed amount to the amount requested to calculate the total collateral needed.* Following conditions need to be met if the user is borrowing at a stable rate: 1. Reserve must be enabled for stable rate borrowing 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency they are borrowing, to prevent abuses. 3. Users will be able to borrow only a portion of the total available liquidity/check if the borrow mode is stable and if stable rate borrowing is enabled on this reservecalculate the max available loan size in stable rate mode as a percentage of theavailable liquidity | function validateBorrow(
address asset,
DataTypes.ReserveData storage reserve,
address userAddress,
uint256 amount,
uint256 amountInETH,
uint256 interestRateMode,
uint256 maxStableLoanPercent,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap storage userConfig,
mapping(uint256 => address) storage reserves,
uint256 reservesCount,
address oracle
) external view {
ValidateBorrowLocalVars memory vars;
vars.availableLiquidity = IERC20(asset).balanceOf(reserve.aTokenAddress);
require(
amount <= vars.availableLiquidity,
Errors.VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH
);
(vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled) = reserve
.configuration
.getFlags();
require(vars.isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(!vars.isFrozen, Errors.VL_RESERVE_FROZEN);
require(amount != 0, Errors.VL_INVALID_AMOUNT);
require(vars.borrowingEnabled, Errors.VL_BORROWING_NOT_ENABLED);
require(
uint256(DataTypes.InterestRateMode.VARIABLE) == interestRateMode ||
uint256(DataTypes.InterestRateMode.STABLE) == interestRateMode,
Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED
);
(
vars.userCollateralBalanceETH,
vars.userBorrowBalanceETH,
vars.currentLtv,
vars.currentLiquidationThreshold,
vars.healthFactor
) = GenericLogic.calculateUserAccountData(
userAddress,
reservesData,
userConfig,
reserves,
reservesCount,
oracle
);
require(vars.userCollateralBalanceETH > 0, Errors.VL_COLLATERAL_BALANCE_IS_0);
require(
vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD,
Errors.VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD
);
vars.amountOfCollateralNeededETH = vars.userBorrowBalanceETH.add(amountInETH).percentDiv(
vars.currentLtv
require(
vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH,
Errors.VL_COLLATERAL_CANNOT_COVER_NEW_BORROW
);
if (interestRateMode == uint256(DataTypes.InterestRateMode.STABLE)) {
require(vars.stableRateBorrowingEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED);
require(
!userConfig.isUsingAsCollateral(reserve.id) ||
reserve.configuration.getLtv() == 0 ||
amount > IERC20(reserve.aTokenAddress).balanceOf(userAddress),
Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY
);
uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(maxStableLoanPercent);
require(amount <= maxLoanSizeStable, Errors.VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE);
}
}
| 7,092,392 | [
1,
5662,
16513,
4993,
1965,
1289,
326,
783,
1818,
29759,
329,
3844,
358,
326,
3844,
3764,
358,
4604,
326,
2078,
4508,
2045,
287,
3577,
18,
16093,
310,
4636,
1608,
358,
506,
5100,
309,
326,
729,
353,
29759,
310,
622,
279,
14114,
4993,
30,
404,
18,
1124,
6527,
1297,
506,
3696,
364,
14114,
4993,
29759,
310,
576,
18,
12109,
2780,
29759,
628,
326,
20501,
309,
3675,
4508,
2045,
287,
353,
261,
10329,
715,
13,
326,
1967,
5462,
565,
2898,
854,
29759,
310,
16,
358,
5309,
1223,
6117,
18,
890,
18,
12109,
903,
506,
7752,
358,
29759,
1338,
279,
14769,
434,
326,
2078,
2319,
4501,
372,
24237,
19,
1893,
309,
326,
29759,
1965,
353,
14114,
471,
309,
14114,
4993,
29759,
310,
353,
3696,
603,
333,
20501,
11162,
326,
943,
2319,
28183,
963,
316,
14114,
4993,
1965,
487,
279,
11622,
434,
326,
5699,
4501,
372,
24237,
2,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
1954,
38,
15318,
12,
203,
565,
1758,
3310,
16,
203,
565,
1910,
2016,
18,
607,
6527,
751,
2502,
20501,
16,
203,
565,
1758,
729,
1887,
16,
203,
565,
2254,
5034,
3844,
16,
203,
565,
2254,
5034,
3844,
382,
1584,
44,
16,
203,
565,
2254,
5034,
16513,
4727,
2309,
16,
203,
565,
2254,
5034,
943,
30915,
1504,
304,
8410,
16,
203,
565,
2874,
12,
2867,
516,
1910,
2016,
18,
607,
6527,
751,
13,
2502,
400,
264,
3324,
751,
16,
203,
565,
1910,
2016,
18,
1299,
1750,
863,
2502,
729,
809,
16,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
2502,
400,
264,
3324,
16,
203,
565,
2254,
5034,
400,
264,
3324,
1380,
16,
203,
565,
1758,
20865,
203,
225,
262,
3903,
1476,
288,
203,
565,
3554,
38,
15318,
2042,
5555,
3778,
4153,
31,
203,
203,
565,
4153,
18,
5699,
48,
18988,
24237,
273,
467,
654,
39,
3462,
12,
9406,
2934,
12296,
951,
12,
455,
6527,
18,
69,
1345,
1887,
1769,
203,
203,
565,
2583,
12,
203,
1377,
3844,
1648,
4153,
18,
5699,
48,
18988,
24237,
16,
203,
1377,
9372,
18,
58,
48,
67,
15487,
67,
23222,
67,
2053,
53,
3060,
4107,
67,
4400,
67,
1157,
26556,
16715,
203,
565,
11272,
203,
203,
565,
261,
4699,
18,
291,
3896,
16,
4153,
18,
291,
42,
9808,
16,
4153,
18,
70,
15318,
310,
1526,
16,
4153,
18,
15021,
4727,
38,
15318,
310,
1526,
13,
273,
20501,
203,
1377,
263,
7025,
203,
1377,
263,
588,
5094,
5621,
203,
203,
565,
2583,
12,
4699,
18,
291,
3896,
2
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.