file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
./full_match/5/0x63e7d8F73B95511B9EeE2792b133F9B5587c959e/sources/PupeV2.sol
burns the total amount lost, then mints 50% of that to the message sender
function adopt(address _ownerAddress) public nonReentrant { require(block.timestamp > abandonTime(_ownerAddress), "address not abandoned"); uint256 adoptAmount = balanceOf(_ownerAddress); _burn(_ownerAddress, adoptAmount); _mint(msg.sender, adoptAmount / 2); emit Adopted(_ownerAddress, msg.sender, adoptAmount/2); }
1,896,758
[ 1, 70, 321, 87, 326, 2078, 3844, 13557, 16, 1508, 312, 28142, 6437, 9, 434, 716, 358, 326, 883, 5793, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1261, 3838, 12, 2867, 389, 8443, 1887, 13, 1071, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 12, 2629, 18, 5508, 405, 1223, 464, 265, 950, 24899, 8443, 1887, 3631, 315, 2867, 486, 1223, 29807, 8863, 203, 203, 3639, 2254, 5034, 1261, 3838, 6275, 273, 11013, 951, 24899, 8443, 1887, 1769, 203, 3639, 389, 70, 321, 24899, 8443, 1887, 16, 1261, 3838, 6275, 1769, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 1261, 3838, 6275, 342, 576, 1769, 203, 3639, 3626, 432, 2896, 337, 329, 24899, 8443, 1887, 16, 1234, 18, 15330, 16, 1261, 3838, 6275, 19, 22, 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 ]
./partial_match/1/0x5Dc58f812b2e244DABA2fabd33f399cD699D7Ddc/sources/GammaFarm.sol
Swap "malBurnPct"% of received WETH for MAL (via WETH/MAL/3000):
uint256 wethAmountToBuyMal = wethAmountOut * malBurnPct / 10000;
2,686,375
[ 1, 12521, 315, 81, 287, 38, 321, 52, 299, 28385, 434, 5079, 678, 1584, 44, 364, 490, 1013, 261, 21985, 678, 1584, 44, 19, 49, 1013, 19, 23, 3784, 4672, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 2254, 5034, 341, 546, 6275, 774, 38, 9835, 49, 287, 273, 341, 546, 6275, 1182, 380, 27431, 38, 321, 52, 299, 342, 12619, 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 ]
pragma solidity 0.6.1; pragma experimental ABIEncoderV2; contract productContract { Product[] public supplyChain; //stores all of the products created. mapping(string => Transaction) public transactionDetail; // uses the trackingID as the key to view current custodian and their address. mapping(string => string) public miscellaneous; // use the trackingID as the key to view miscellaneous messages. mapping(string => string[]) public counterparties; // counterparties stores the current custodian plus the previous participants address manufacturer; // stores the account address of the where this contract is deployed on in a variable called manufacturer. modifier onlyManufacturer() { // only manufacturer can call the addProduct function. require(msg.sender == manufacturer); _; } uint256 public totalProductsCreated = 0; struct Product{ string productName; string health; bool sold; bool recalled; string custodian; //who currently owns the product string trackingID; string lastScannedAt; } struct Transaction{ //stores current information of the product uint256 timestamp; string containerID; string custodian; address custodianAddress; string lastScannedAt; } event productAdded (string ID); event sendArray(Product[] array); constructor() public{ manufacturer = msg.sender; } // The addProduct will create a new product only if they are the manufacturer. Sold and Recall values are set to false and containerID is "" when a product is created. function addProduct(string memory _productName, string memory _health, string memory _misc, string memory _trackingID, string memory _lastScannedAt) public onlyManufacturer{ uint256 _timestamp = block.timestamp; bool _sold = false; bool _recalled = false; string memory _containerID = ""; string memory _custodian = "manufacturer"; transactionDetail[_trackingID] = (Transaction(_timestamp, _containerID, _custodian, manufacturer,_lastScannedAt)); // uses trackingID to get the timestamp, containerID, custodian and custodian_Address. supplyChain.push(Product(_productName,_health,_sold,_recalled,_custodian,_trackingID,_lastScannedAt)); // pushes the new product to the array miscellaneous[_trackingID] = _misc; // use trackingID as the key to view string value. addCounterParties(_trackingID,_custodian);//calls an internal function and appends the custodian to the product using the trackingID emit productAdded(_trackingID); totalProductsCreated += 1; } //addCounterParties is a private method that updates the custodian of the product using the trackingID function addCounterParties(string memory _trackingID, string memory _custodian) internal{ counterparties[_trackingID].push(_custodian); } //The updateCustodian method updates custodian when custodianship changes function updateCustodian(string memory _trackingID, string memory longLatsCoordinates ) public { if(msg.sender != manufacturer){ // if the account calling this function is not the manufacturer, the following will be performed: address _custodianAddress = msg.sender; string memory _custodian = 'store'; uint256 _timestamp = block.timestamp; transactionDetail[_trackingID].timestamp = _timestamp; transactionDetail[_trackingID].lastScannedAt = longLatsCoordinates; transactionDetail[_trackingID].custodian = _custodian; transactionDetail[_trackingID].custodianAddress = _custodianAddress; addCounterParties(_trackingID,_custodian); //the new custodian gets added to the counterparties map. } } function getAllProducts() public returns(Product[] memory) { emit sendArray(supplyChain); return supplyChain; } }
calls an internal function and appends the custodian to the product using the trackingID
addCounterParties(_trackingID,_custodian);
950,903
[ 1, 12550, 392, 2713, 445, 471, 8144, 326, 276, 641, 369, 2779, 358, 326, 3017, 1450, 326, 11093, 734, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 527, 4789, 1988, 606, 24899, 6440, 734, 16, 67, 71, 641, 369, 2779, 1769, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } pragma solidity ^0.5.16; //import "./CarefulMath.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } struct Double { uint256 mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint256 rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 descaledMantissa) = divUInt( a.mantissa, scalar ); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint256 numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 doubleScaledProduct) = mulUInt( a.mantissa, b.mantissa ); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt( halfExpScale, doubleScaledProduct ); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint256 product) = divUInt( doubleScaledProductWithHalfScale, expScale ); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3( Exp memory a, Exp memory b, Exp memory c ) internal pure returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint256 a, uint256 b) internal pure returns (uint256) { return add_(a, b, "addition overflow"); } function add_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint256 a, uint256 b) internal pure returns (uint256) { return sub_(a, b, "subtraction underflow"); } function sub_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Exp memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Double memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint256 a, uint256 b) internal pure returns (uint256) { return mul_(a, b, "multiplication overflow"); } function mul_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Exp memory b) internal pure returns (uint256) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Double memory b) internal pure returns (uint256) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint256 a, uint256 b) internal pure returns (uint256) { return div_(a, b, "divide by zero"); } function div_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function fraction(uint256 a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } contract CToken { /*** User Interface ***/ 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 exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); } contract getAccountLiquidity is Exponential, ComptrollerErrorReporter { struct AccountLiquidityLocalVars { uint256 sumCollateral; uint256 sumBorrowPlusEffects; uint256 cTokenBalance; uint256 borrowBalance; uint256 exchangeRateMantissa; uint256 oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } function getHypotheticalAccountLiquidity( address account, CToken[] memory assets, uint256[] memory collateralFactorMantissa, uint256[] memory underlyingPrice ) public view returns ( Error, uint256, uint256, uint256, uint256 ) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint256 oErr; MathError mErr; // For each asset the account is in //CToken[] memory assets = accountAssets[account]; for (uint256 i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken ( oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa ) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0, 0, 0); } //vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.collateralFactor = Exp({mantissa: collateralFactorMantissa[i]}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset //vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); vars.oraclePriceMantissa = underlyingPrice[i]; if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) (mErr, vars.tokensToDenom) = mulExp3( vars.collateralFactor, vars.exchangeRate, vars.oraclePrice ); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0, 0, 0); } // sumCollateral += tokensToDenom * cTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt( vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral ); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt( vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects ); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0, 0, 0); } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return ( Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0, vars.sumCollateral, vars.sumBorrowPlusEffects ); } else { return ( Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral, vars.sumCollateral, vars.sumBorrowPlusEffects ); } } }
* @dev Divide an Exp by a scalar, returning a new Exp./
function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 descaledMantissa) = divUInt( a.mantissa, scalar ); if (err0 != MathError.NO_ERROR) { } }
1,271,124
[ 1, 7244, 831, 392, 7784, 635, 279, 4981, 16, 5785, 279, 394, 7784, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3739, 13639, 12, 2966, 3778, 279, 16, 2254, 5034, 4981, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 10477, 668, 16, 7784, 3778, 13, 203, 565, 288, 203, 3639, 261, 10477, 668, 393, 20, 16, 2254, 5034, 3044, 18931, 49, 970, 21269, 13, 273, 3739, 14342, 12, 203, 5411, 279, 18, 81, 970, 21269, 16, 203, 5411, 4981, 203, 3639, 11272, 203, 3639, 309, 261, 370, 20, 480, 2361, 668, 18, 3417, 67, 3589, 13, 288, 203, 3639, 289, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-12-27 */ ////// lib/openzeppelin-contracts/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) /* pragma solidity ^0.8.0; */ /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } ////// lib/openzeppelin-contracts/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) /* pragma solidity ^0.8.0; */ /* import "../utils/Context.sol"; */ /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } ////// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) /* pragma solidity ^0.8.0; */ /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `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); } ////// lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) /* pragma solidity ^0.8.0; */ /* import "../IERC20.sol"; */ /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } ////// lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol) /* pragma solidity ^0.8.0; */ /* import "./IERC20.sol"; */ /* import "./extensions/IERC20Metadata.sol"; */ /* import "../../utils/Context.sol"; */ /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } ////// lib/openzeppelin-contracts/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) /* pragma solidity ^0.8.0; */ /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } ////// lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol) /* pragma solidity ^0.8.0; */ // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } ////// src/IUniswapV2Factory.sol /* pragma solidity 0.8.10; */ /* pragma experimental ABIEncoderV2; */ interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } ////// src/IUniswapV2Pair.sol /* pragma solidity 0.8.10; */ /* pragma experimental ABIEncoderV2; */ interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } ////// src/IUniswapV2Router02.sol /* pragma solidity 0.8.10; */ /* pragma experimental ABIEncoderV2; */ interface IUniswapV2Router02 { 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 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; } ////// src/BunnyInu.sol /* pragma solidity ^0.8.10; */ /* import {ERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; */ /* import {IERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */ /* import {Ownable} from "lib/openzeppelin-contracts/contracts/access/Ownable.sol"; */ /* import {Address} from "lib/openzeppelin-contracts/contracts/utils/Address.sol"; */ /* import {SafeMath} from "lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol"; */ /* import {IUniswapV2Router02} from "./IUniswapV2Router02.sol"; */ /* import {IUniswapV2Factory} from "./IUniswapV2Factory.sol"; */ /* import {IUniswapV2Pair} from "./IUniswapV2Pair.sol"; */ contract BunnyInu is Ownable, IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; string public constant name_ = "BunnyInu"; string public constant symbol_ = "BUNNY"; uint8 public constant decimals_ = 18; uint256 public totalSupply_ = 0; address public owner_; address public constant UNISWAP_ROUTER = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public constant DEAD = 0x000000000000000000000000000000000000dEaD; address public constant ZERO = 0x0000000000000000000000000000000000000000; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool public mintingDisabled = false; bool public antibot = true; bool public sellCooldown = false; uint public sellCooldownSeconds; mapping(address => bool) public blacklist; mapping(address => uint256) private _txCounter; mapping(address => bool) public automatedMarketMakerPairs; mapping(address => bool) private _isExcludedFromFees; mapping(address => uint256) private _lastBuyTimestamp; address payable public developerWallet; address payable public marketingWallet; address payable public liquidityWallet; uint256 public buyTaxDevelopment; uint256 public buyTaxMarketing; uint256 public buyTaxLiquidity; uint256 public sellTaxDevelopment; uint256 public sellTaxMarketing; uint256 public sellTaxLiquidity; uint256 public maxTransactions; uint256 public maxWallet; uint256 public swapTokensAtAmount = 100000 * (10**18); uint256 public lastSwapTime; bool private swapping; constructor ( address payable _developerWallet, address payable _marketingWallet, address payable _liquidityWallet, uint256 _buyTaxDevelopment, uint256 _buyTaxMarketing, uint256 _buyTaxLiquidity, uint256 _sellTaxDevelopment, uint256 _sellTaxMarketing, uint256 _sellTaxLiquidity, uint256 _maxTransactions, uint256 _maxWallet, uint256 _sellCooldownSeconds ) { developerWallet = _developerWallet; marketingWallet = _marketingWallet; liquidityWallet = _liquidityWallet; buyTaxDevelopment = _buyTaxDevelopment; buyTaxMarketing = _buyTaxMarketing; buyTaxLiquidity = _buyTaxLiquidity; sellTaxDevelopment = _sellTaxDevelopment; sellTaxMarketing = _sellTaxMarketing; sellTaxLiquidity = _sellTaxLiquidity; maxTransactions = _maxTransactions; maxWallet = _maxWallet; sellCooldownSeconds = _sellCooldownSeconds; owner_ = msg.sender; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(UNISWAP_ROUTER); address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); _mint(owner_, 1000000000 * 10**18); mintingDisabled = true; } function name() public view virtual returns (string memory) { return name_; } function symbol() public view virtual returns (string memory) { return symbol_; } function decimals() public view virtual returns (uint8) { return decimals_; } function totalSupply() public view virtual override returns (uint256) { return totalSupply_; } function owner() public view virtual override returns (address) { return owner_; } 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); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _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"); _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"); require(blacklist[sender] != true, "This sender is blacklisted"); require(blacklist[recipient] != true, "This recipient is blacklisted"); require(_txCounter[sender] < maxTransactions, "This address is at the max TX limit"); require(recipient == owner() || recipient == uniswapV2Pair || recipient == address(uniswapV2Router) || recipient == developerWallet || recipient == marketingWallet || recipient == liquidityWallet || (_balances[recipient] + amount < totalSupply_ * maxWallet), "This address is at the max wallet limit"); // todo do we really need to check the router require(antibot == false || sender == owner_ || recipient == owner_, "Antibot is currently enabled"); uint256 _maxTxAmount = (totalSupply_ * maxTransactions) / 10000; uint256 _maxWallet = (totalSupply_ * maxWallet) / 10000; require( sender == owner() || sender == uniswapV2Pair || amount <= _maxTxAmount, "TX Limit Exceeded" ); if (sender != owner() && recipient != owner() && recipient != address(this) && recipient != address(0) && recipient != uniswapV2Pair) { uint256 currentBalance = balanceOf(recipient); require(currentBalance + amount <= _maxWallet, "ERC20: transfer puts recipient above max wallet"); } uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); // todo ensure the following two blocks work as intended if (sender == uniswapV2Pair && sellCooldown) { require(_lastBuyTimestamp[recipient] > block.timestamp - sellCooldownSeconds || recipient == owner_, "Sell cooldown enabled"); } if (sender != uniswapV2Pair) { _lastBuyTimestamp[recipient] = block.timestamp; } _beforeTokenTransfer(sender, recipient, amount); uint256 contractTokenBalance = balanceOf(address(this)); uint256 contractNativeBalance = address(this).balance; bool canSwap = contractTokenBalance >= swapTokensAtAmount; if (canSwap && !swapping && !automatedMarketMakerPairs[sender] && sender != address(uniswapV2Router) && sender != owner_ && recipient != owner_) { swapping = true; bool isBuy = true; if (sender == uniswapV2Pair || sender == address(uniswapV2Router) || sender == address(this)) { isBuy = false; // todo - test to ensure this works } _executeSwap(contractTokenBalance, contractNativeBalance, isBuy); lastSwapTime = block.timestamp; swapping = false; } bool takeFee = true; if (sender == uniswapV2Pair || recipient == uniswapV2Pair) { takeFee = true; } if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) { takeFee = false; } if (swapping) { takeFee = false; } if (sender == owner()) { takeFee = false; } uint totalFee = buyTaxDevelopment + buyTaxMarketing + buyTaxLiquidity; if (sender == uniswapV2Pair) { totalFee = sellTaxDevelopment + sellTaxMarketing + sellTaxLiquidity; } _txCounter[sender]++; if (takeFee) { uint256 fees = (amount * totalFee) / 10000; amount -= fees; _executeTransfer(sender, address(this), fees); } _executeTransfer(sender, recipient, amount); } function _executeTransfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function _mint( address account, uint256 amount ) internal virtual { require(!mintingDisabled, "No more tokens can be minted."); 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); } function _burn( address account, uint256 amount ) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; totalSupply_ -= amount; emit Transfer(account, address(0), amount); } function _approve( address holder, address spender, uint256 amount ) internal virtual { require(holder != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[holder][spender] = amount; emit Approval(holder, spender, amount); } function swapTokensForNative(uint256 tokens) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokens); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokens, 0, // accept any amount of native path, address(this), block.timestamp ); } function addLiquidity(uint256 tokens, uint256 native) private { _approve(address(this), address(uniswapV2Router), tokens); uniswapV2Router.addLiquidityETH{value: native}( address(this), tokens, 0, 0, liquidityWallet, block.timestamp ); } function _executeSwap( uint256 tokens, uint256 native, bool isBuy ) private { if (tokens <= 0) { return; } uint totalFee = buyTaxDevelopment + buyTaxMarketing + buyTaxLiquidity; if (!isBuy) { totalFee = sellTaxDevelopment + sellTaxMarketing + sellTaxLiquidity; } uint swapTokensDevelopment = (tokens * buyTaxDevelopment) / totalFee; uint swapTokensMarketing = (tokens * buyTaxMarketing) / totalFee; uint tokensForLiquidity = (tokens * buyTaxLiquidity) / totalFee; if (!isBuy) { swapTokensDevelopment = (tokens * sellTaxDevelopment) / totalFee; swapTokensMarketing = (tokens * sellTaxMarketing) / totalFee; tokensForLiquidity = (tokens * sellTaxLiquidity) / totalFee; } uint256 swapTokensLiquidity = tokensForLiquidity / 2; uint256 addTokensLiquidity = tokensForLiquidity - swapTokensLiquidity; uint256 swapTokensTotal = swapTokensDevelopment + swapTokensMarketing + swapTokensLiquidity; uint256 initNativeBal = address(this).balance; swapTokensForNative(swapTokensTotal); uint256 nativeSwapped = (address(this).balance - initNativeBal) + native; uint256 nativeDevelopment = (nativeSwapped * swapTokensDevelopment) / swapTokensTotal; uint256 nativeMarketing = (nativeSwapped * swapTokensMarketing) / swapTokensTotal; uint256 nativeLiquidity = nativeSwapped - nativeDevelopment - nativeMarketing; if (nativeDevelopment > 0) { payable(developerWallet).transfer(nativeDevelopment); } if (nativeMarketing > 0) { payable(marketingWallet).transfer(nativeMarketing); } if (nativeLiquidity > 0) { // ? is this conditional necessary addLiquidity(addTokensLiquidity, nativeLiquidity); } } // Function to receive Ether. msg.data must be empty receive() external payable {} // Fallback function is called when msg.data is not empty fallback() external payable {} function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function setAutomatedMarketMakerPair( address pair, bool value ) public onlyOwner { require(pair != uniswapV2Pair, "AMM pair can not be removed"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair( address pair, bool value ) private { require(automatedMarketMakerPairs[pair] != value, "AMM pair must be set to a new value"); automatedMarketMakerPairs[pair] = value; } /* Deployer Functions */ function toggleAntibot( bool _antibot ) external onlyOwner { antibot = !_antibot; } function toggleSellCooldown( bool _sellCooldown ) external onlyOwner { sellCooldown = !_sellCooldown; } function adjustSellCooldownSeconds( uint256 _sellCooldownSeconds ) external onlyOwner { sellCooldownSeconds = _sellCooldownSeconds; } function blacklistAddress( address toBlacklist ) external onlyOwner { blacklist[toBlacklist] = true; } function whitelistAddress( address toWhitelist ) external onlyOwner { blacklist[toWhitelist] = false; } function adjustDeveloperWallet( address payable _developerWallet ) external onlyOwner { developerWallet = _developerWallet; } function adjustMarketingWallet( address payable _marketingWallet ) external onlyOwner { marketingWallet = _marketingWallet; } function adjustLiquidityWallet( address payable _liquidityWallet ) external onlyOwner { liquidityWallet = _liquidityWallet; } function adjustBuyTaxDevelopment( uint256 _buyTaxDevelopment ) external onlyOwner { require(_buyTaxDevelopment <= 3333); buyTaxDevelopment = _buyTaxDevelopment; } function adjustBuyTaxMarketing( uint256 _buyTaxMarketing ) external onlyOwner { require(_buyTaxMarketing <= 3333); buyTaxMarketing = _buyTaxMarketing; } function adjustBuyTaxLiquidity( uint256 _buyTaxLiquidity ) external onlyOwner { require(_buyTaxLiquidity <= 3333); buyTaxLiquidity = _buyTaxLiquidity; } function adjustSellTaxDevelopment( uint256 _sellTaxDevelopment ) external onlyOwner { require(_sellTaxDevelopment <= 3333); sellTaxDevelopment = _sellTaxDevelopment; } function adjustSellTaxMarketing( uint256 _sellTaxMarketing ) external onlyOwner { require(_sellTaxMarketing <= 3333); sellTaxMarketing = _sellTaxMarketing; } function adjustSellTaxLiquidity( uint256 _sellTaxLiquidity ) external onlyOwner { require(_sellTaxLiquidity <= 3333); sellTaxLiquidity = _sellTaxLiquidity; } function adjustMaxTransactions( uint256 _maxTransactions ) external onlyOwner { maxTransactions = _maxTransactions; } function adjustMaxWallet( uint256 _maxWallet ) external onlyOwner { require(_maxWallet <= 10000); maxWallet = _maxWallet; } function adjustUniswapV2Router( address _newAddress ) external onlyOwner { require(_newAddress != address(uniswapV2Router), "The address must point to a new and different router"); uniswapV2Router = IUniswapV2Router02(_newAddress); address _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH()); uniswapV2Pair = _uniswapV2Pair; } function transferOwnership( address _newOwner ) public override onlyOwner { require(_newOwner != address(0)); emit OwnershipTransferred(owner_, _newOwner); owner_ = _newOwner; } function renounceOwnership() public override onlyOwner { emit OwnershipTransferred(owner_, address(0)); owner_ = address(0); } function getAntibot() public view returns(bool) { return antibot; } function getSellCooldown() public view returns(bool) { return sellCooldown; } function getSellCooldownSeconds() public view returns(uint) { return sellCooldownSeconds; } function isBlacklist( address _query ) public view returns(bool) { return blacklist[_query]; } function getDeveloperWallet() public view returns(address) { return developerWallet; } function getMarketingWallet() public view returns(address) { return marketingWallet; } function getLiquidityWallet() public view returns(address) { return liquidityWallet; } function getBuyTaxDevelopment() public view returns(uint) { return buyTaxDevelopment; } function getBuyTaxMarketing() public view returns(uint) { return buyTaxMarketing; } function getBuyTaxLiquidity() public view returns(uint) { return buyTaxLiquidity; } function getSellTaxDevelopment() public view returns(uint) { return sellTaxDevelopment; } function getSellTaxMarketing() public view returns(uint) { return sellTaxMarketing; } function getSellTaxLiquidity() public view returns(uint) { return sellTaxLiquidity; } function getMaxTransactions() public view returns(uint) { return maxTransactions; } function getMaxWallet() public view returns(uint) { return maxWallet; } function getUniswapV2Router() public view returns(IUniswapV2Router02) { return uniswapV2Router; } function getUniswapV2Pair() public view returns(address) { return uniswapV2Pair; } function getOwner() public view returns(address) { return owner_; } function isRenounced() public view returns(bool) { if (owner_ == address(0)) { return true; } else { return false; } } }
todo ensure the following two blocks work as intended
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"); require(blacklist[sender] != true, "This sender is blacklisted"); require(blacklist[recipient] != true, "This recipient is blacklisted"); require(_txCounter[sender] < maxTransactions, "This address is at the max TX limit"); require(antibot == false || sender == owner_ || recipient == owner_, "Antibot is currently enabled"); uint256 _maxTxAmount = (totalSupply_ * maxTransactions) / 10000; uint256 _maxWallet = (totalSupply_ * maxWallet) / 10000; require( sender == owner() || sender == uniswapV2Pair || amount <= _maxTxAmount, "TX Limit Exceeded" ); if (sender != owner() && recipient != owner() && recipient != address(this) && recipient != address(0) && recipient != uniswapV2Pair) { uint256 currentBalance = balanceOf(recipient); require(currentBalance + amount <= _maxWallet, "ERC20: transfer puts recipient above max wallet"); } uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if (sender == uniswapV2Pair && sellCooldown) { require(_lastBuyTimestamp[recipient] > block.timestamp - sellCooldownSeconds || recipient == owner_, "Sell cooldown enabled"); } if (sender != uniswapV2Pair) { _lastBuyTimestamp[recipient] = block.timestamp; } _beforeTokenTransfer(sender, recipient, amount); uint256 contractTokenBalance = balanceOf(address(this)); uint256 contractNativeBalance = address(this).balance; bool canSwap = contractTokenBalance >= swapTokensAtAmount; if (canSwap && !swapping && !automatedMarketMakerPairs[sender] && sender != address(uniswapV2Router) && sender != owner_ && recipient != owner_) { swapping = true; bool isBuy = true; if (sender == uniswapV2Pair || sender == address(uniswapV2Router) || sender == address(this)) { } _executeSwap(contractTokenBalance, contractNativeBalance, isBuy); lastSwapTime = block.timestamp; swapping = false; } bool takeFee = true; if (sender == uniswapV2Pair || recipient == uniswapV2Pair) { takeFee = true; } if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) { takeFee = false; } if (swapping) { takeFee = false; } if (sender == owner()) { takeFee = false; } uint totalFee = buyTaxDevelopment + buyTaxMarketing + buyTaxLiquidity; if (sender == uniswapV2Pair) { totalFee = sellTaxDevelopment + sellTaxMarketing + sellTaxLiquidity; } _txCounter[sender]++; if (takeFee) { uint256 fees = (amount * totalFee) / 10000; amount -= fees; _executeTransfer(sender, address(this), fees); } _executeTransfer(sender, recipient, amount); }
4,815,187
[ 1, 9012, 3387, 326, 3751, 2795, 4398, 1440, 487, 12613, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 5024, 288, 203, 3639, 2583, 12, 15330, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 20367, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 22491, 63, 15330, 65, 480, 638, 16, 315, 2503, 5793, 353, 25350, 8863, 203, 3639, 2583, 12, 22491, 63, 20367, 65, 480, 638, 16, 315, 2503, 8027, 353, 25350, 8863, 203, 3639, 2583, 24899, 978, 4789, 63, 15330, 65, 411, 943, 14186, 16, 315, 2503, 1758, 353, 622, 326, 943, 23211, 1800, 8863, 203, 3639, 2583, 12, 970, 495, 352, 422, 629, 747, 5793, 422, 3410, 67, 747, 8027, 422, 3410, 67, 16, 315, 14925, 495, 352, 353, 4551, 3696, 8863, 203, 203, 3639, 2254, 5034, 389, 1896, 4188, 6275, 273, 261, 4963, 3088, 1283, 67, 380, 943, 14186, 13, 342, 12619, 31, 203, 3639, 2254, 5034, 389, 1896, 16936, 273, 261, 4963, 3088, 1283, 67, 380, 943, 16936, 13, 342, 12619, 31, 203, 3639, 2583, 12, 203, 5411, 5793, 422, 3410, 1435, 747, 5793, 422, 640, 291, 91, 438, 58, 22, 4154, 747, 3844, 1648, 389, 1896, 4188, 6275, 16, 203, 5411, 315, 16556, 7214, 1312, 5816, 6, 203, 3639, 11272, 203, 203, 3639, 309, 261, 15330, 480, 3410, 1435, 597, 8027, 480, 3410, 1435, 597, 8027, 480, 1758, 12, 2211, 2 ]
/** ****************************************************************************************************************************************************************************************** $$$$$$$\ $$\ $$\ $$\ $$\ $$ __$$\ $$ | \__| $$ | $$ | $$ | $$ | $$$$$$\ $$$$$$\$$$$\ $$$$$$\ $$$$$$$\ $$$$$$\ $$$$$$\ $$$$$$\ $$\ $$$$$$$\ $$ | $$\ $$\ $$$$$$$\ $$ | $$\ $$ | $$ |$$ __$$\ $$ _$$ _$$\ $$ __$$\ $$ _____|$$ __$$\ \____$$\ \_$$ _| $$ |$$ _____| $$ | $$ | $$ |$$ _____|$$ | $$ | $$ | $$ |$$$$$$$$ |$$ / $$ / $$ |$$ / $$ |$$ / $$ | \__| $$$$$$$ | $$ | $$ |$$ / $$ | $$ | $$ |$$ / $$$$$$ / $$ | $$ |$$ ____|$$ | $$ | $$ |$$ | $$ |$$ | $$ | $$ __$$ | $$ |$$\ $$ |$$ | $$ | $$ | $$ |$$ | $$ _$$< $$$$$$$ |\$$$$$$$\ $$ | $$ | $$ |\$$$$$$ |\$$$$$$$\ $$ | \$$$$$$$ | \$$$$ |$$ |\$$$$$$$\ $$$$$$$$\ \$$$$$$ |\$$$$$$$\ $$ | \$$\ \_______/ \_______|\__| \__| \__| \______/ \_______|\__| \_______| \____/ \__| \_______| \________| \______/ \_______|\__| \__| _ _ _ _ | | | | | |(_) __ ____ ____ __ ___ | |_ | |__ __ _ __ _ _ __ ___ ___ | | _ __ __ ___ \ \ /\ / /\ \ /\ / /\ \ /\ / / / _ \| __|| '_ \ / _` | / _` || '_ ` _ \ / _ \ | || |\ \ / / / _ \ \ V V / \ V V / \ V V / _ | __/| |_ | | | || (_| || (_| || | | | | || __/ _ | || | \ V / | __/ \_/\_/ \_/\_/ \_/\_/ (_) \___| \__||_| |_| \__, | \__,_||_| |_| |_| \___|(_)|_||_| \_/ \___| __/ | |___/ ****************************************************************************************************************************************************************************************** Contract Name: Democratic Luck Contract Symbol: DemoLuck Version: 1.0 Author: Alan Yan Author Email: [email protected] Publish Date: 2018/11 Official Website: www.ethgame.live Copyright: All rights reserved Contract Describe: A game that include investment, math strategy, luck and democratic mechanism for game equilibrium. It based on eth blockchain network. Let's hope the whole world's people can enjoy this new revolutionary game and have fun! Game Rules: 1. This game use ether cryptocurrency. To participate in the game, user need to use a browser such as chrome/Firefox with the metamask plugin installed. 2. User can directly participate in the game without registration first. If user buy share or buy ticket, then will be automatically registered. User also can manually register for free. The process of manual registration is very simple, just click the 'Register' button on the website, and then click 'Confirm' in the pop-up metamask window. Registration will complete. 3. Each user will have an account with a purse and a dedicated promotion url link. User can send this link to others and invite others to participate in the game, if the others join the game and get prize, user will always receive 5% of the others' prize as reward. 4. After each round of the game begins, user can buy shares of the game and become the shareholder. The price of the shares is 1eth/share, and 70% of the cost ether will put into the jackpot prize pool, 20% will be constantly distributed to all earlier shares (including itself), and 10% will be given to the last share buyer at the end of game round as a special prize. 5. When there is a jackpot prize pool, then anyone can buy luck tickets at any time to win the jackpot prize pool. The price of the luck ticket is 0.01 eth, and 50% of the cost ether will instantly distribute to all current shares, and 50% of the cost ether will instantly distribute to all earlier luck tickets (including itself). 6. When a luck ticket was been bought, a 48-hour countdown will auto start. If a new luck ticket was been bought during the countdown, then 48-hour countdown will restart again. If when the 48-hour countdown is over, there is still no new ticket was been bought. Then the game will enter the vote period. The vote period is 24 hours. Every shareholder can participate in vote. Shareholder's share amount is votes amount. Shareholders can choose to continue wait or end the game round. If the shareholder didn't not manually vote, the default option is continue wait, if votes amount of end game round is more than 50% of the total votes amount, then game round will auto end. During the voting period, if a new luck ticket was been bought, then vote will be cancelled and restart the 48-hour countdown again. After vote period over and shareholders didn't vote to end game round, then game will continue wait and restart the 48-hour countdown again. 7. During the game, shareholders or luck ticket buyers can view their own prize at any time. The prize is dynamic estimation and change with the game progress. 8. When the game is over, the prize will be automatically distributed. The prize distribution rules are: the instantly prize obtained by shareholders and luck ticket buyers during the game will be their prize too, also the total share capital's 10% will reward to the last share buyer at the end of the game as a special prize, the last luck ticket buyer will win the jackpot prize pool. 9. After the game is over, The prize that each player received, the platform will charge 5% as a service fee, and the remaining 95% will automatically deposited into the purse of user's account. User can withdraw the prize to own personal ether account at any time. 10. If player (shareholder or luck ticket buyer) wins the prize in the game round, and player has a referrer, the referrer will receive 5% of the prize as a reward. When player withdraw the prize from purse, the reward will be sent to referer's purse. 11. After each game round ended and distributed prize, the next round will automatically restart. **/ pragma solidity ^0.4.24; /** @title Democratic Luck */ contract DemocraticLuck { using SafeMath for uint256; //event when shareholder buy share event event_buyShare(address indexed _addr, uint256 indexed _indexNo, uint256 _num); //event when player buy luck ticket event event_buyTicket(address indexed _addr, uint256 indexed _indexNo, uint256 _num); //event when shareholder vote event event_shareholderVote(address indexed _addr, uint256 indexed _indexNo, uint256 _vote); //event when round end and jackpot winner event event_endRound(uint256 indexed _indexNo, address indexed _addr, uint256 _prize); address private Owner; uint256 private rdSharePrice = 1 ether; //share's price uint256 private rdTicketPrice = 0.01 ether; //luck ticket's price uint256 private rdIndexNo = 0; //game round's index No counter uint256 private userIDCnt = 0; //user's id counter uint256 private rdStateActive = 1; //game round's active state uint256 private rdStateEnd = 2; //game round's end state uint256 private rdTicketTime = 48 hours; //countdown time since a ticket was been bought uint256 private rdVoteTime = 24 hours; //vote time since countdown time over uint256 private serviceFee = 5; //system charge service fee rate uint256 private refererFee = 5; //referer user's prize percent 5% uint256 private sharePotRate = 70; //share price's percent into jackpot uint256 private shrPrizeRate = 20; //share price's percent to distribute to current shares uint256 private shrLastBuyerRate = 10; //share price's percent to last share buyer uint256 private ticketPotRate = 50; //ticket price's percent to distribute to current shares uint256 private serviceFeeCnt; //owner service fee count //user's account information struct userAcc{ uint256 purse; //user's purse uint256 refCode; //user's unique referrer code uint256 frefCode; //user from referrer code } //game shareholder's information struct rdShareholder{ uint256 cost; //shareholder cost to buy share uint256 shareNum; //shareholder's shares amount uint256 shrAvgBonus; //shareholder's shares average value to calculate bonus from later shares uint256 shrTckAvgBonus; //shareholder's shares average value to calculate bonus from tickets sale uint256 vote; //shareholder's vote to coutinue or end game round uint256 lastShrVoteTime; //shareholder's last vote time } //luck ticket buyer's information struct rdTckBuyer{ uint256 cost; //ticket buyer cost to buy ticket uint256 ticketNum; //ticket's amount uint256 tckAvgBonus; //ticket buyer's average value to calculate bonus from later tickets } //game round's information struct rdInfo{ uint256 state; //round's state: 1,active 2,end uint256 sharePot; //all share's capital pot uint256 shrJackpot; //round's jackpot uint256 shareholderNum; //shareholders amount uint256 shareNum; //shares amount uint256 shrAvgBonus; //round's shares average value to calculate bonus from later shares uint256 shrTckAvgBonus; //round's shares average value to calculate bonus from tickets sale uint256 ticketPot; //luck ticket sales amount uint256 tckBuyerNum; //luck ticket buyers amount uint256 ticketNum; //luck ticket's saled amount uint256 tckAvgBonus; //round's ticket buyer's average value to calculate bonus from later tickets uint256 lastTckBuyTime; //time of last ticket was been bought uint256 lastShrVoteTime; //last time of shareholders vote uint256 shrVotesEnd; //count of votes to end address lastShareBuyer; //who bought the last share address lastTckBuyer; //who bought the last luck ticket } mapping(uint256 => address) private userIDAddr; //user'id => user's account mapping(address => userAcc) private userAccs; //user's account => user's account information mapping(address => uint256[]) private userUnWithdrawRound; //round list that user didn't withdraw yet mapping(uint256 => mapping(address => rdShareholder)) private rdShareholders; //round's index No => shareholder's account => shareholder's information mapping(uint256 => rdInfo) private rdInfos; //round's index No => round's information mapping(uint256 => mapping(address => rdTckBuyer)) private rdTckBuyers; //round's index No => luck ticket buyer's account => ticket buyer's information /* Modifiers */ /** @dev check caller is owner */ modifier onlyOwner() { require(Owner == msg.sender); _; } /** @dev check caller is person */ modifier isPerson() { address addr = msg.sender; uint256 size; assembly {size := extcodesize(addr)} require(size == 0); require(tx.origin == msg.sender); _; } /** @dev create contract */ constructor() public { Owner = msg.sender; startNewRound(); } /** @dev tarnsfer ownership to new account * @param _owner new owner account */ function transferOwnership(address _owner) onlyOwner() public { Owner = _owner; } /** @dev get contract owner account * @return _addr owner account */ function owner() public view returns (address _addr) { return Owner; } /** @dev start new game round */ function startNewRound() internal { rdIndexNo++; rdInfo memory rdInf = rdInfo(rdStateActive, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, address(0), address(0)); rdInfos[rdIndexNo] = rdInf; } /** @dev new user register * @param _frefCode referer id */ function userRegister(uint256 _frefCode) isPerson() public { require(msg.sender != address(0)); require(!checkUserExist(msg.sender)); addNewUser(msg.sender, _frefCode); } /** @dev add new user * @param _addr user account * @param _frefCode referer id */ function addNewUser(address _addr, uint256 _frefCode) internal { if(getAddrOfRefCode(_frefCode) == address(0)) _frefCode = 0; userIDCnt++; userAcc memory uAcc = userAcc(0, userIDCnt, _frefCode); userAccs[_addr] = uAcc; userIDAddr[userIDCnt] = _addr; } /** @dev add new shareholder into game round * @param _indexNo round's index No * @param _addr shareholder account */ function addRdShareholder(uint256 _indexNo, address _addr) internal { rdShareholder memory rdPly = rdShareholder(0, 0, 0, 0, 0, 0); rdShareholders[_indexNo][_addr] = rdPly; rdInfos[_indexNo].shareholderNum++; if(!checkUserInUnWithdrawRd(_indexNo, _addr)) userUnWithdrawRound[_addr].push(_indexNo); } /** @dev add new ticket buyer into game round * @param _indexNo round's index No * @param _addr ticket buyer account */ function addRdTicketBuyer(uint256 _indexNo, address _addr) internal { rdTckBuyer memory rdPly = rdTckBuyer(0, 0, 0); rdTckBuyers[_indexNo][_addr] = rdPly; rdInfos[_indexNo].tckBuyerNum++; if(!checkUserInUnWithdrawRd(_indexNo, _addr)) userUnWithdrawRound[_addr].push(_indexNo); } /** @dev shareholder buy shares * @param _indexNo round's index No * @param _frefCode referer id */ function buyShare(uint256 _indexNo, uint256 _frefCode) isPerson() public payable { require(msg.sender != address(0)); require(checkRdActive(_indexNo)); require(msg.value.sub(rdSharePrice) >= 0); uint256 _num = msg.value.div(rdSharePrice); uint256 cost = rdSharePrice.mul(_num); if(!checkUserExist(msg.sender)) addNewUser(msg.sender, _frefCode); if(!checkShareholderInRd(_indexNo, msg.sender)) addRdShareholder(_indexNo, msg.sender); addRoundShare(_indexNo, msg.sender, cost, _num); calcServiceFee(cost); if(msg.value.sub(cost) > 0) userAccs[msg.sender].purse += msg.value.sub(cost); emit event_buyShare(msg.sender, _indexNo, _num); } /** @dev add shares info when shareholder bought * @param _indexNo round's index No * @param _addr shareholder's account * @param _cost cost amount * @param _num shares amount */ function addRoundShare(uint256 _indexNo, address _addr, uint256 _cost, uint256 _num) internal { rdInfos[_indexNo].lastShareBuyer = _addr; rdInfos[_indexNo].shareNum += _num; rdInfos[_indexNo].sharePot = rdInfos[_indexNo].sharePot + _cost; rdInfos[_indexNo].shrJackpot = rdInfos[_indexNo].shrJackpot + (_cost * sharePotRate / 100); rdInfos[_indexNo].shrAvgBonus = rdInfos[_indexNo].shrAvgBonus + (_cost * shrPrizeRate / 100) / rdInfos[_indexNo].shareNum; rdShareholders[_indexNo][_addr].cost += _cost; rdShareholders[_indexNo][_addr].shareNum += _num; rdShareholders[_indexNo][_addr].shrAvgBonus = (rdInfos[_indexNo].shrAvgBonus * rdShareholders[_indexNo][_addr].shareNum - (rdInfos[_indexNo].shrAvgBonus - (_cost * shrPrizeRate / 100) / rdInfos[_indexNo].shareNum - rdShareholders[_indexNo][_addr].shrAvgBonus) * (rdShareholders[_indexNo][_addr].shareNum - _num) - (_cost * shrPrizeRate / 100) * rdShareholders[_indexNo][_addr].shareNum / rdInfos[_indexNo].shareNum) / rdShareholders[_indexNo][_addr].shareNum; rdShareholders[_indexNo][_addr].shrTckAvgBonus = (rdInfos[_indexNo].shrTckAvgBonus * rdShareholders[_indexNo][_addr].shareNum - (rdInfos[_indexNo].shrTckAvgBonus - rdShareholders[_indexNo][_addr].shrTckAvgBonus) * (rdShareholders[_indexNo][_addr].shareNum - _num)) / rdShareholders[_indexNo][_addr].shareNum; } /** @dev buy luck ticket * @param _indexNo round's index No * @param _frefCode referer id */ function buyTicket(uint256 _indexNo, uint256 _frefCode) isPerson() public payable { require(msg.sender != address(0)); require(checkRdActive(_indexNo)); require(rdInfos[_indexNo].shrJackpot > 0); require(msg.value.sub(rdTicketPrice) >= 0); uint256 _num = msg.value.div(rdTicketPrice); uint256 cost = rdTicketPrice.mul(_num); if(!checkUserExist(msg.sender)) addNewUser(msg.sender, _frefCode); if(!checkTicketBuyerInRd(_indexNo, msg.sender)) addRdTicketBuyer(_indexNo, msg.sender); addRoundTicket(_indexNo, msg.sender, cost, _num); calcServiceFee(cost); if(msg.value.sub(cost) > 0) userAccs[msg.sender].purse += msg.value.sub(cost); emit event_buyTicket(msg.sender, _indexNo, _num); } /** @dev add ticket info * @param _indexNo round's index No * @param _addr buyer's account * @param _cost cost amount * @param _num tickets amount */ function addRoundTicket(uint256 _indexNo, address _addr, uint256 _cost, uint256 _num) internal { rdInfos[_indexNo].lastTckBuyTime = now; rdInfos[_indexNo].lastTckBuyer = _addr; rdInfos[_indexNo].ticketNum += _num; rdInfos[_indexNo].ticketPot = rdInfos[_indexNo].ticketPot + _cost; rdInfos[_indexNo].shrTckAvgBonus = rdInfos[_indexNo].shrTckAvgBonus + (_cost * ticketPotRate / 100) / rdInfos[_indexNo].shareNum; rdInfos[_indexNo].tckAvgBonus = rdInfos[_indexNo].tckAvgBonus + (_cost * (100 - ticketPotRate) / 100) / rdInfos[_indexNo].ticketNum; rdTckBuyers[_indexNo][_addr].cost += _cost; rdTckBuyers[_indexNo][_addr].ticketNum += _num; rdTckBuyers[_indexNo][_addr].tckAvgBonus = (rdInfos[_indexNo].tckAvgBonus * rdTckBuyers[_indexNo][_addr].ticketNum - (rdInfos[_indexNo].tckAvgBonus - (_cost * (100 - ticketPotRate) / 100) / rdInfos[_indexNo].ticketNum - rdTckBuyers[_indexNo][_addr].tckAvgBonus) * (rdTckBuyers[_indexNo][_addr].ticketNum - _num) - (_cost * (100 - ticketPotRate) / 100) * rdTckBuyers[_indexNo][_addr].ticketNum / rdInfos[_indexNo].ticketNum) / rdTckBuyers[_indexNo][_addr].ticketNum; } /** * @dev get user amount * @return _num user amount */ function getUserCount() public view returns(uint256 _num) { return userIDCnt; } /** * @dev get user's information * @param _addr user's account * @return user's information */ function getUserInfo(address _addr) public view returns(uint256, uint256, uint256) { require(_addr != address(0)); require(checkUserExist(_addr)); uint256 prize = 0; for(uint256 i = 0; i < userUnWithdrawRound[_addr].length; i++) { uint256 indexNo = userUnWithdrawRound[_addr][i]; if(rdInfos[indexNo].state == rdStateEnd) prize += calcRdPlayerPrize(indexNo, _addr); } prize = userAccs[_addr].purse + prize * (100 - serviceFee) / 100; return (prize, userAccs[_addr].refCode, userAccs[_addr].frefCode); } /** @dev user withdraw eth from purse, withdraw all every time */ function userWithdraw() isPerson() public { require(msg.sender != address(0)); require(checkUserExist(msg.sender)); address addr = msg.sender; uint256 prize = 0; uint256 unEndRd = 0; for(uint256 i = 0; i < userUnWithdrawRound[addr].length; i++) { uint256 indexNo = userUnWithdrawRound[addr][i]; if(rdInfos[indexNo].state == rdStateEnd) prize += calcRdPlayerPrize(indexNo, addr); else unEndRd = indexNo; } require(prize > 0); userUnWithdrawRound[addr].length = 0; if(unEndRd > 0) userUnWithdrawRound[addr].push(unEndRd); prize = prize * (100 - serviceFee) / 100; if(userAccs[addr].frefCode != 0) { address frefAddr = getAddrOfRefCode(userAccs[addr].frefCode); if(frefAddr != address(0)) { uint256 refPrize = (prize * refererFee) / 100; userAccs[frefAddr].purse += refPrize; prize -= refPrize; } } prize += userAccs[addr].purse; userAccs[addr].purse = 0; addr.transfer(prize); } /** * @dev calculate player's prize * @param _indexNo round's index No * @param _addr player's account * @return _prize player's prize */ function calcRdPlayerPrize(uint256 _indexNo, address _addr) internal view returns(uint256 _prize) { uint256 prize = 0; if(rdShareholders[_indexNo][_addr].shareNum > 0) prize += calcShrPrize(_indexNo, _addr); if(rdTckBuyers[_indexNo][_addr].ticketNum > 0) prize += calcTckPrize(_indexNo, _addr); return prize; } /** * @dev calculate shareholder's share prize * @param _indexNo round's index No * @param _addr shareholder account * @return _prize shareholder's prize */ function calcShrPrize(uint256 _indexNo, address _addr) internal view returns(uint256 _prize) { uint256 prize = 0; prize += (rdInfos[_indexNo].shrAvgBonus - rdShareholders[_indexNo][_addr].shrAvgBonus) * rdShareholders[_indexNo][_addr].shareNum; prize += (rdInfos[_indexNo].shrTckAvgBonus - rdShareholders[_indexNo][_addr].shrTckAvgBonus) * rdShareholders[_indexNo][_addr].shareNum; if(rdInfos[_indexNo].lastShareBuyer == _addr) prize += (rdInfos[_indexNo].sharePot * shrLastBuyerRate) / 100; return prize; } /** * @dev calculate ticket buyer's ticket prize * @param _indexNo round's index No * @param _addr buyer account * @return _prize buyer's prize */ function calcTckPrize(uint256 _indexNo, address _addr) internal view returns(uint256 _prize) { uint256 prize = 0; prize += (rdInfos[_indexNo].tckAvgBonus - rdTckBuyers[_indexNo][_addr].tckAvgBonus) * rdTckBuyers[_indexNo][_addr].ticketNum; if(rdInfos[_indexNo].lastTckBuyer == _addr) prize += rdInfos[_indexNo].shrJackpot; return prize; } /** @dev get active round's index No * @return _rdIndexNo active round's index No */ function getRoundActive() public view returns(uint256 _rdIndexNo) { return rdIndexNo; } /** @dev get round's information * @param _indexNo round's index No * @return _rdIn rounds's information * @return _addrs rounds's information */ function getRdInfo(uint256 _indexNo) public view returns(uint256[] _rdIn, address[] _addrs) { require(checkRdExist(_indexNo)); uint256[] memory rdIn = new uint256[](16); address[] memory addrs = new address[](2); rdIn[0] = rdSharePrice; rdIn[1] = rdTicketPrice; rdIn[2] = rdInfos[_indexNo].state; rdIn[3] = rdInfos[_indexNo].sharePot; rdIn[4] = rdInfos[_indexNo].shrJackpot; rdIn[5] = rdInfos[_indexNo].shareholderNum; rdIn[6] = rdInfos[_indexNo].shareNum; rdIn[7] = rdInfos[_indexNo].shrAvgBonus; rdIn[8] = rdInfos[_indexNo].shrTckAvgBonus; rdIn[9] = rdInfos[_indexNo].ticketPot; rdIn[10] = rdInfos[_indexNo].tckBuyerNum; rdIn[11] = rdInfos[_indexNo].ticketNum; rdIn[12] = rdInfos[_indexNo].tckAvgBonus; rdIn[13] = rdInfos[_indexNo].lastTckBuyTime; rdIn[14] = rdInfos[_indexNo].lastShrVoteTime; rdIn[15] = rdInfos[_indexNo].shrVotesEnd; addrs[0] = rdInfos[_indexNo].lastShareBuyer; addrs[1] = rdInfos[_indexNo].lastTckBuyer; return (rdIn, addrs); } /** @dev get round's countdown time or vote time state * @param _indexNo round's index No * @return _timeState countdown time or vote time * @return _timeLeft left time */ function getRdTimeState(uint256 _indexNo) public view returns(uint256 _timeState, uint256 _timeLeft) { require(checkRdActive(_indexNo)); uint256 nowTime = now; uint256 timeState = 0; uint256 timeLeft = 0; uint256 timeStart = getRdLastCntDownStart(_indexNo, nowTime); if(timeStart > 0) { if(nowTime < (timeStart + rdTicketTime)) { timeState = 1; timeLeft = (timeStart + rdTicketTime) - nowTime; } else { timeState = 2; timeLeft = (timeStart + rdTicketTime + rdVoteTime) - nowTime; } } return (timeState, timeLeft); } /** @dev get round's last countdown start time * @param _indexNo round's index No * @param _nowTime now time * @return _timeStart last countdown start time */ function getRdLastCntDownStart(uint256 _indexNo, uint256 _nowTime) internal view returns(uint256 _timeStart) { require(checkRdActive(_indexNo)); uint256 timeStart = 0; if(rdInfos[_indexNo].lastTckBuyTime > 0) { uint256 timeSpan = _nowTime - rdInfos[_indexNo].lastTckBuyTime; uint256 num = timeSpan / (rdTicketTime + rdVoteTime); timeStart = rdInfos[_indexNo].lastTckBuyTime + num * (rdTicketTime + rdVoteTime); } return timeStart; } /** @dev get round's player's information * @param _indexNo round's index No * @param _addr player's account * @return _rdPly1 shareholder's information * @return _rdPly2 ticket buyer's information */ function getRdPlayerInfo(uint256 _indexNo, address _addr) public view returns(uint256[] _rdPly1, uint256[] _rdPly2) { require(checkShareholderInRd(_indexNo, _addr) || checkTicketBuyerInRd(_indexNo, _addr)); uint256[] memory rdPly1 = new uint256[](6); uint256[] memory rdPly2 = new uint256[](3); if(checkShareholderInRd(_indexNo, _addr)) { rdPly1[0] = rdShareholders[_indexNo][_addr].cost; rdPly1[1] = rdShareholders[_indexNo][_addr].shareNum; rdPly1[2] = rdShareholders[_indexNo][_addr].shrAvgBonus; rdPly1[3] = rdShareholders[_indexNo][_addr].shrTckAvgBonus; rdPly1[4] = calcShrPrize(_indexNo, _addr); rdPly1[5] = 0; if(checkRdInVoteState(_indexNo)) rdPly1[5] = getRdshareholderVoteVal(_indexNo, _addr, now); } if(checkTicketBuyerInRd(_indexNo, _addr)) { rdPly2[0] = rdTckBuyers[_indexNo][_addr].cost; rdPly2[1] = rdTckBuyers[_indexNo][_addr].ticketNum; rdPly2[2] = calcTckPrize(_indexNo, _addr); } return (rdPly1, rdPly2); } /** @dev shareholder vote to coutinue or end round * @param _indexNo round's index No * @param _vote coutinue or end round */ function shareholderVote(uint256 _indexNo, uint256 _vote) isPerson() public { require(checkRdInVoteState(_indexNo)); require(checkShareholderInRd(_indexNo, msg.sender)); require(_vote == 0 || _vote == 1); address addr = msg.sender; uint256 nowTime = now; uint256 timeStart = getRdLastCntDownStart(_indexNo, nowTime); if(rdInfos[_indexNo].lastShrVoteTime < (timeStart + rdTicketTime)) { rdShareholders[_indexNo][addr].vote = 0; rdInfos[_indexNo].shrVotesEnd = 0; } if(rdShareholders[_indexNo][addr].lastShrVoteTime > (timeStart + rdTicketTime)) { if(_vote == 1 && _vote != rdShareholders[_indexNo][addr].vote) rdInfos[_indexNo].shrVotesEnd += rdShareholders[_indexNo][addr].shareNum; else if(_vote == 0 && _vote != rdShareholders[_indexNo][addr].vote) rdInfos[_indexNo].shrVotesEnd -= rdShareholders[_indexNo][addr].shareNum; } else if(_vote == 1) rdInfos[_indexNo].shrVotesEnd += rdShareholders[_indexNo][addr].shareNum; rdShareholders[_indexNo][addr].vote = _vote; rdShareholders[_indexNo][addr].lastShrVoteTime = nowTime; rdInfos[_indexNo].lastShrVoteTime = nowTime; emit event_shareholderVote(addr, _indexNo, _vote); if((rdInfos[_indexNo].shrVotesEnd * 2) > rdInfos[_indexNo].shareNum) endRound(_indexNo); } /** @dev get round's shareholder vote result * @param _indexNo round's index No * @return _votesEnd votes amount to end round * @return _voteAll all votes amount */ function getRdVotesCount(uint256 _indexNo) public view returns(uint256 _votesEnd, uint256 _voteAll) { require(checkRdInVoteState(_indexNo)); uint256 nowTime = now; uint256 shrVotesEnd = 0; uint256 timeStart = getRdLastCntDownStart(_indexNo, nowTime); if(timeStart > 0 && rdInfos[_indexNo].lastShrVoteTime > (timeStart + rdTicketTime)) shrVotesEnd = rdInfos[_indexNo].shrVotesEnd; return (shrVotesEnd, rdInfos[_indexNo].shareNum); } /** * @dev end game round,then start new round * @param _indexNo round's index No */ function endRound(uint256 _indexNo) internal { rdInfos[_indexNo].state = rdStateEnd; owner().transfer(serviceFeeCnt); serviceFeeCnt = 0; emit event_endRound(_indexNo, rdInfos[_indexNo].lastTckBuyer, rdInfos[_indexNo].shrJackpot); startNewRound(); } /** @dev get user from referer id * @param _refCode referer id * @return _addr user account */ function getAddrOfRefCode(uint256 _refCode) internal view returns(address _addr) { if(userIDAddr[_refCode] != address(0)) return userIDAddr[_refCode]; return address(0); } /** @dev check user registered? * @param _addr user account * @return _result exist or not */ function checkUserExist(address _addr) internal view returns(bool _result) { if(userAccs[_addr].refCode != 0) return true; return false; } /** @dev check round exist? * @param _indexNo round's index no * @return _result exist or not */ function checkRdExist(uint256 _indexNo) internal view returns(bool _result) { if(rdInfos[_indexNo].state > 0) return true; return false; } /** @dev check round is active? * @param _indexNo round's index no * @return _result active or not */ function checkRdActive(uint256 _indexNo) internal view returns(bool _result) { require(checkRdExist(_indexNo)); if(rdInfos[_indexNo].state == rdStateActive) return true; return false; } /** @dev check round is in vote state? * @param _indexNo round's index no * @return _result in vote state or not */ function checkRdInVoteState(uint256 _indexNo) internal view returns(bool _result) { require(checkRdActive(_indexNo)); uint256 timeState = 0; (timeState,) = getRdTimeState(_indexNo); if(timeState == 2) return true; return false; } /** @dev check user is shareholder in a round? * @param _indexNo round's index no * @param _addr shareholder account * @return _result is shareholder or not */ function checkShareholderInRd(uint256 _indexNo, address _addr) public view returns(bool _result) { require(checkRdExist(_indexNo)); if(rdShareholders[_indexNo][_addr].shareNum > 0) return true; return false; } /** @dev check user is ticket buyer in a round? * @param _indexNo round's index no * @param _addr ticket buyer account * @return _result is ticket buyer or not */ function checkTicketBuyerInRd(uint256 _indexNo, address _addr) public view returns(bool _result) { require(checkRdExist(_indexNo)); if(rdTckBuyers[_indexNo][_addr].ticketNum > 0) return true; return false; } /** @dev check user in a round and didn't withdraw yet? * @param _indexNo round's index no * @param _addr user account * @return _result in or not */ function checkUserInUnWithdrawRd(uint256 _indexNo, address _addr) internal view returns(bool _result) { require(checkUserExist(_addr)); require(checkRdExist(_indexNo)); for(uint256 i = 0; i < userUnWithdrawRound[_addr].length; i++) { if(userUnWithdrawRound[_addr][i] == _indexNo) return true; } return false; } /** @dev get shareholder's vote * @param _indexNo round's index no * @param _addr shareholder account * @param _nowTime current time * @return _result shareholder's vote */ function getRdshareholderVoteVal(uint256 _indexNo, address _addr, uint256 _nowTime) internal view returns(uint256 _result) { uint256 timeStart = getRdLastCntDownStart(_indexNo, _nowTime); if(rdShareholders[_indexNo][_addr].vote == 1 && rdShareholders[_indexNo][_addr].lastShrVoteTime > (timeStart + rdTicketTime)) return 1; return 0; } /** @dev calculate service fee * @param _cost buyer's cost */ function calcServiceFee(uint256 _cost) internal { serviceFeeCnt += (_cost * serviceFee) / 100; if(serviceFeeCnt >= 1 ether) { owner().transfer(serviceFeeCnt); serviceFeeCnt = 0; } } } 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) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns(uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } }
luck ticket buyers amount
uint256 tckBuyerNum;
13,123,077
[ 1, 80, 9031, 9322, 30143, 414, 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, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 268, 363, 38, 16213, 2578, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/100/0x62D007D4c4Db781C24FF6ac19279B9A9Ec32b344/sources/contracts/recover/recover.sol
* @dev To be emitted when a party pays or reimburses the other. @param _claimID The index of the claim. @param _party The party that paid. @param _amount The amount paid./
event Fund(uint indexed _claimID, Party _party, uint _amount);
14,273,891
[ 1, 774, 506, 17826, 1347, 279, 18285, 293, 8271, 578, 283, 381, 70, 295, 2420, 326, 1308, 18, 282, 389, 14784, 734, 1021, 770, 434, 326, 7516, 18, 282, 389, 21214, 1021, 18285, 716, 30591, 18, 282, 389, 8949, 1021, 3844, 30591, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 478, 1074, 12, 11890, 8808, 389, 14784, 734, 16, 6393, 93, 389, 21214, 16, 2254, 389, 8949, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../interfaces/ISinglePlus.sol"; import "../interfaces/ICompositePlus.sol"; import "../interfaces/venus/IVToken.sol"; import "../interfaces/fortube/IForTubeBank.sol"; import "../interfaces/yfi/IVault.sol"; import "../interfaces/autofarm/IAutoBTC.sol"; /** * @dev Zap for BTC plus on BSC. */ contract BTCZapBsc is Initializable { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; event Minted(address indexed account, address indexed target, uint256 amount, uint256 mintAmount); event Redeemed(address indexed account, address indexed source, uint256 amount, uint256 redeemAmount); address public constant BTCB = address(0x7130d2A12B9BCbFAe4f2634d864A1Ee1Ce3Ead9c); address public constant VENUS_BTC = address(0x882C173bC7Ff3b7786CA16dfeD3DFFfb9Ee7847B); address public constant VENUS_BTC_PLUS = address(0xcf8D1D3Fce7C2138F85889068e50F0e7a18b5321); address public constant FORTUBE_BTCB = address(0xb5C15fD55C73d9BeeC046CB4DAce1e7975DcBBBc); address public constant FORTUBE_BANK = address(0x0cEA0832e9cdBb5D476040D58Ea07ecfbeBB7672); address public constant FORTUBE_CONTROLLER = address(0xc78248D676DeBB4597e88071D3d889eCA70E5469); address public constant FORTUBE_BTCB_PLUS = address(0x73FddFb941c11d16C827169Bb94aCC227841C396); address public constant ACS_BTCB = address(0x0395fCC8E1a1E30A1427D4079aF6E23c805E3eeF); address public constant ACS_BTCB_PLUS = address(0xD7806143A4206aa9A816b964e4c994F533b830b0); address public constant AUTO_BTC = address(0x6B7Ea9F1EF1E6c662761201998Dc876b88Ed7414); address public constant AUTO_BTC_PLUS = address(0x02827D495B2bBe37e1C021eB91BCdCc92cD3b604); address public constant AUTO_BTC_V2 = address(0x5AA676577F7A69F8761F5A19ae6057A386D6a48e); address public constant AUTO_BTC_V2_PLUS = address(0x7780b26aB2586Ad0e0192CafAAE93BfA09a106F3); address public constant BTCB_PLUS = address(0xe884E6695C4cB3c8DEFFdB213B50f5C2a1a9E0A2); uint256 public constant WAD = 10 ** 18; address public governance; /** * @dev Initializes the Zap contract. */ function initialize() public initializer { governance = msg.sender; IERC20Upgradeable(BTCB).safeApprove(VENUS_BTC, uint256(int256(-1))); IERC20Upgradeable(VENUS_BTC).safeApprove(VENUS_BTC_PLUS, uint256(int256(-1))); IERC20Upgradeable(BTCB).safeApprove(FORTUBE_CONTROLLER, uint256(int256(-1))); IERC20Upgradeable(FORTUBE_BTCB).safeApprove(FORTUBE_BTCB_PLUS, uint256(int256(-1))); IERC20Upgradeable(BTCB).safeApprove(ACS_BTCB, uint256(int256(-1))); IERC20Upgradeable(ACS_BTCB).safeApprove(ACS_BTCB_PLUS, uint256(int256(-1))); IERC20Upgradeable(BTCB).safeApprove(AUTO_BTC, uint256(int256(-1))); IERC20Upgradeable(AUTO_BTC).safeApprove(AUTO_BTC_PLUS, uint256(int256(-1))); IERC20Upgradeable(BTCB).safeApprove(AUTO_BTC_V2, uint256(int256(-1))); IERC20Upgradeable(AUTO_BTC_V2).safeApprove(AUTO_BTC_V2_PLUS, uint256(int256(-1))); IERC20Upgradeable(VENUS_BTC_PLUS).safeApprove(BTCB_PLUS, uint256(int256(-1))); IERC20Upgradeable(ACS_BTCB_PLUS).safeApprove(BTCB_PLUS, uint256(int256(-1))); } /** * @dev Mints vBTC+ with BTCB. * @param _amount Amount of BTCB used to mint vBTC+ */ function mintVBTCPlus(uint256 _amount) public { require(_amount > 0, "zero amount"); IERC20Upgradeable(BTCB).safeTransferFrom(msg.sender, address(this), _amount); IVToken(VENUS_BTC).mint(_amount); uint256 _vbtc = IERC20Upgradeable(VENUS_BTC).balanceOf(address(this)); ISinglePlus(VENUS_BTC_PLUS).mint(_vbtc); uint256 _vbtcPlus = IERC20Upgradeable(VENUS_BTC_PLUS).balanceOf(address(this)); IERC20Upgradeable(VENUS_BTC_PLUS).safeTransfer(msg.sender, _vbtcPlus); emit Minted(msg.sender, VENUS_BTC_PLUS, _amount, _vbtcPlus); } /** * @dev Redeems vBTC+ to BTCB. * @param _amount Amount of vTCB+ to redeem. */ function redeemVBTCPlus(uint256 _amount) public { require(_amount > 0, "zero amount"); IERC20Upgradeable(VENUS_BTC_PLUS).safeTransferFrom(msg.sender, address(this), _amount); ISinglePlus(VENUS_BTC_PLUS).redeem(_amount); uint256 _vbtc = IERC20Upgradeable(VENUS_BTC).balanceOf(address(this)); IVToken(VENUS_BTC).redeem(_vbtc); uint256 _btcb = IERC20Upgradeable(BTCB).balanceOf(address(this)); IERC20Upgradeable(BTCB).safeTransfer(msg.sender, _btcb); emit Redeemed(msg.sender, VENUS_BTC_PLUS, _btcb, _amount); } /** * @dev Mints fBTCB+ with BTCB. * @param _amount Amount of BTCB used to mint fBTCB+ */ function mintFBTCBPlus(uint256 _amount) public { require(_amount > 0, "zero amount"); IERC20Upgradeable(BTCB).safeTransferFrom(msg.sender, address(this), _amount); IForTubeBank(FORTUBE_BANK).deposit(BTCB, _amount); uint256 _fbtcb = IERC20Upgradeable(FORTUBE_BTCB).balanceOf(address(this)); ISinglePlus(FORTUBE_BTCB_PLUS).mint(_fbtcb); uint256 _fbtcbPlus = IERC20Upgradeable(FORTUBE_BTCB_PLUS).balanceOf(address(this)); IERC20Upgradeable(FORTUBE_BTCB_PLUS).safeTransfer(msg.sender, _fbtcbPlus); emit Minted(msg.sender, FORTUBE_BTCB_PLUS, _amount, _fbtcbPlus); } /** * @dev Redeems fBTC+ to BTCB. * @param _amount Amount of fTCB+ to redeem. */ function redeemFBTCBPlus(uint256 _amount) public { require(_amount > 0, "zero amount"); IERC20Upgradeable(FORTUBE_BTCB_PLUS).safeTransferFrom(msg.sender, address(this), _amount); ISinglePlus(FORTUBE_BTCB_PLUS).redeem(_amount); uint256 _fbtcb = IERC20Upgradeable(FORTUBE_BTCB).balanceOf(address(this)); IForTubeBank(FORTUBE_BANK).withdraw(BTCB, _fbtcb); uint256 _btcb = IERC20Upgradeable(BTCB).balanceOf(address(this)); IERC20Upgradeable(BTCB).safeTransfer(msg.sender, _btcb); emit Redeemed(msg.sender, FORTUBE_BTCB_PLUS, _btcb, _amount); } /** * @dev Mints acsBTCB+ with BTCB. * @param _amount Amount of BTCB used to mint acsBTCB+ */ function mintAcsBTCBPlus(uint256 _amount) public { require(_amount > 0, "zero amount"); IERC20Upgradeable(BTCB).safeTransferFrom(msg.sender, address(this), _amount); IVault(ACS_BTCB).deposit(_amount); uint256 _acsBtcb = IERC20Upgradeable(ACS_BTCB).balanceOf(address(this)); ISinglePlus(ACS_BTCB_PLUS).mint(_acsBtcb); uint256 _acsBtcbPlus = IERC20Upgradeable(ACS_BTCB_PLUS).balanceOf(address(this)); IERC20Upgradeable(ACS_BTCB_PLUS).safeTransfer(msg.sender, _acsBtcbPlus); emit Minted(msg.sender, ACS_BTCB_PLUS, _amount, _acsBtcbPlus); } /** * @dev Redeems acsBTC+ to BTCB. * @param _amount Amount of acsTCB+ to redeem. */ function redeemAcsBTCBPlus(uint256 _amount) public { require(_amount > 0, "zero amount"); IERC20Upgradeable(ACS_BTCB_PLUS).safeTransferFrom(msg.sender, address(this), _amount); ISinglePlus(ACS_BTCB_PLUS).redeem(_amount); uint256 _acsBtcb = IERC20Upgradeable(ACS_BTCB).balanceOf(address(this)); IVault(ACS_BTCB).withdraw(_acsBtcb); uint256 _btcb = IERC20Upgradeable(BTCB).balanceOf(address(this)); IERC20Upgradeable(BTCB).safeTransfer(msg.sender, _btcb); emit Redeemed(msg.sender, ACS_BTCB_PLUS, _btcb, _amount); } /** * @dev Mints autoBTC+ with BTCB. * @param _amount Amount of BTCB used to mint autoBTC+ */ function mintAutoBTCPlus(uint256 _amount) public { require(_amount > 0, "zero amount"); IERC20Upgradeable(BTCB).safeTransferFrom(msg.sender, address(this), _amount); IAutoBTC(AUTO_BTC).mint(_amount); uint256 _autoBtc = IERC20Upgradeable(AUTO_BTC).balanceOf(address(this)); ISinglePlus(AUTO_BTC_PLUS).mint(_autoBtc); uint256 _autoBtcPlus = IERC20Upgradeable(AUTO_BTC_PLUS).balanceOf(address(this)); IERC20Upgradeable(AUTO_BTC_PLUS).safeTransfer(msg.sender, _autoBtcPlus); emit Minted(msg.sender, AUTO_BTC_PLUS, _amount, _autoBtcPlus); } /** * @dev Redeems autoBTC+ to BTCB. * @param _amount Amount of autoTCB+ to redeem. */ function redeemAutoBTCPlus(uint256 _amount) public { require(_amount > 0, "zero amount"); IERC20Upgradeable(AUTO_BTC_PLUS).safeTransferFrom(msg.sender, address(this), _amount); ISinglePlus(AUTO_BTC_PLUS).redeem(_amount); uint256 _autoBtc = IERC20Upgradeable(AUTO_BTC).balanceOf(address(this)); IAutoBTC(AUTO_BTC).redeem(_autoBtc); uint256 _btcb = IERC20Upgradeable(BTCB).balanceOf(address(this)); IERC20Upgradeable(BTCB).safeTransfer(msg.sender, _btcb); emit Redeemed(msg.sender, AUTO_BTC_PLUS, _btcb, _amount); } /** * @dev Mints autoBTCv2+ with BTCB. * @param _amount Amount of BTCB used to mint autoBTCv2+ */ function mintAutoBTCV2Plus(uint256 _amount) public { require(_amount > 0, "zero amount"); IERC20Upgradeable(BTCB).safeTransferFrom(msg.sender, address(this), _amount); IAutoBTC(AUTO_BTC_V2).mint(_amount); uint256 _autoBtcV2 = IERC20Upgradeable(AUTO_BTC_V2).balanceOf(address(this)); ISinglePlus(AUTO_BTC_V2_PLUS).mint(_autoBtcV2); uint256 _autoBtcV2Plus = IERC20Upgradeable(AUTO_BTC_V2_PLUS).balanceOf(address(this)); IERC20Upgradeable(AUTO_BTC_V2_PLUS).safeTransfer(msg.sender, _autoBtcV2Plus); emit Minted(msg.sender, AUTO_BTC_V2_PLUS, _amount, _autoBtcV2Plus); } /** * @dev Redeems autoBTCv2+ to BTCB. * @param _amount Amount of autoTCBv2+ to redeem. */ function redeemAutoBTCV2Plus(uint256 _amount) public { require(_amount > 0, "zero amount"); IERC20Upgradeable(AUTO_BTC_V2_PLUS).safeTransferFrom(msg.sender, address(this), _amount); ISinglePlus(AUTO_BTC_V2_PLUS).redeem(_amount); uint256 _autoBtcV2 = IERC20Upgradeable(AUTO_BTC_V2).balanceOf(address(this)); IAutoBTC(AUTO_BTC_V2).redeem(_autoBtcV2); uint256 _btcb = IERC20Upgradeable(BTCB).balanceOf(address(this)); IERC20Upgradeable(BTCB).safeTransfer(msg.sender, _btcb); emit Redeemed(msg.sender, AUTO_BTC_V2_PLUS, _btcb, _amount); } /** * @dev Mints BTCB+ with BTCB. * @param _amount Amount of BTCB used to mint BTCB+ */ function mintBTCBPlus(uint256 _amount) public { require(_amount > 0, "zero amount"); // Always starts with vBTC+! IERC20Upgradeable(BTCB).safeTransferFrom(msg.sender, address(this), _amount); IVToken(VENUS_BTC).mint(_amount); uint256 _vbtc = IERC20Upgradeable(VENUS_BTC).balanceOf(address(this)); ISinglePlus(VENUS_BTC_PLUS).mint(_vbtc); uint256 _vbtcPlus = IERC20Upgradeable(VENUS_BTC_PLUS).balanceOf(address(this)); address[] memory _tokens = new address[](1); _tokens[0] = VENUS_BTC_PLUS; uint256[] memory _amounts = new uint256[](1); _amounts[0] = _vbtcPlus; ICompositePlus(BTCB_PLUS).mint(_tokens, _amounts); uint256 _btcbPlus = IERC20Upgradeable(BTCB_PLUS).balanceOf(address(this)); IERC20Upgradeable(BTCB_PLUS).safeTransfer(msg.sender, _btcbPlus); emit Minted(msg.sender, BTCB_PLUS, _amount, _btcbPlus); } /** * @dev Redeems BTCB+ to BTCB. * @param _amount Amount of BTCB+ to redeem. */ function redeemBTCBPlus(uint256 _amount) public { require(_amount > 0, "zero amount"); IERC20Upgradeable(BTCB_PLUS).safeTransferFrom(msg.sender, address(this), _amount); ICompositePlus(BTCB_PLUS).redeem(_amount); uint256 _vbtcPlus = IERC20Upgradeable(VENUS_BTC_PLUS).balanceOf(address(this)); ISinglePlus(VENUS_BTC_PLUS).redeem(_vbtcPlus); uint256 _vbtc = IERC20Upgradeable(VENUS_BTC).balanceOf(address(this)); IVToken(VENUS_BTC).redeem(_vbtc); uint256 _acsBtcbPlus = IERC20Upgradeable(ACS_BTCB_PLUS).balanceOf(address(this)); ISinglePlus(ACS_BTCB_PLUS).redeem(_acsBtcbPlus); uint256 _acsBtcb = IERC20Upgradeable(ACS_BTCB).balanceOf(address(this)); IVault(ACS_BTCB).withdraw(_acsBtcb); uint256 _btcb = IERC20Upgradeable(BTCB).balanceOf(address(this)); IERC20Upgradeable(BTCB).safeTransfer(msg.sender, _btcb); emit Redeemed(msg.sender, BTCB_PLUS, _btcb, _amount); } }
* @dev Redeems acsBTC+ to BTCB. @param _amount Amount of acsTCB+ to redeem./
function redeemAcsBTCBPlus(uint256 _amount) public { require(_amount > 0, "zero amount"); IERC20Upgradeable(ACS_BTCB_PLUS).safeTransferFrom(msg.sender, address(this), _amount); ISinglePlus(ACS_BTCB_PLUS).redeem(_amount); uint256 _acsBtcb = IERC20Upgradeable(ACS_BTCB).balanceOf(address(this)); IVault(ACS_BTCB).withdraw(_acsBtcb); uint256 _btcb = IERC20Upgradeable(BTCB).balanceOf(address(this)); IERC20Upgradeable(BTCB).safeTransfer(msg.sender, _btcb); emit Redeemed(msg.sender, ACS_BTCB_PLUS, _btcb, _amount); }
5,536,493
[ 1, 426, 323, 7424, 1721, 87, 38, 15988, 15, 358, 605, 56, 8876, 18, 225, 389, 8949, 16811, 434, 1721, 87, 56, 8876, 15, 358, 283, 24903, 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 ]
[ 1, 1, 1, 1, 1, 1, 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, 283, 24903, 37, 2143, 38, 56, 8876, 13207, 12, 11890, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 2583, 24899, 8949, 405, 374, 16, 315, 7124, 3844, 8863, 203, 203, 3639, 467, 654, 39, 3462, 10784, 429, 12, 2226, 55, 67, 38, 56, 8876, 67, 6253, 3378, 2934, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 3639, 4437, 1714, 13207, 12, 2226, 55, 67, 38, 56, 8876, 67, 6253, 3378, 2934, 266, 24903, 24899, 8949, 1769, 203, 203, 3639, 2254, 5034, 389, 28965, 38, 5111, 70, 273, 467, 654, 39, 3462, 10784, 429, 12, 2226, 55, 67, 38, 56, 8876, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 467, 12003, 12, 2226, 55, 67, 38, 56, 8876, 2934, 1918, 9446, 24899, 28965, 38, 5111, 70, 1769, 203, 203, 3639, 2254, 5034, 389, 70, 5111, 70, 273, 467, 654, 39, 3462, 10784, 429, 12, 38, 56, 8876, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 467, 654, 39, 3462, 10784, 429, 12, 38, 56, 8876, 2934, 4626, 5912, 12, 3576, 18, 15330, 16, 389, 70, 5111, 70, 1769, 203, 203, 3639, 3626, 868, 24903, 329, 12, 3576, 18, 15330, 16, 432, 4596, 67, 38, 56, 8876, 67, 6253, 3378, 16, 389, 70, 5111, 70, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `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.0 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: GPL-3.0 // Docgen-SOLC: 0.6.0 pragma solidity ^0.8.0; // Inheritance import "../utils/Owned.sol"; import "../interfaces/IRewardsDistribution.sol"; // Libraires import "../libraries/SafeDecimalMath.sol"; // Internal references import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // https://docs.synthetix.io/contracts/source/contracts/rewardsdistribution contract RewardsDistribution is Owned, IRewardsDistribution { using SafeMath for uint256; using SafeDecimalMath for uint256; /** * @notice Authorised addresses able to call distributeRewards */ mapping(address => bool) public rewardDistributors; /** * @notice Address of the Synthetix ProxyERC20 */ address public pop; /** * @notice Address of the FeePoolProxy */ address public treasury; /** * @notice An array of addresses and amounts to send */ DistributionData[] public override distributions; constructor( address _owner, address _pop, address _treasury ) public Owned(_owner) { pop = _pop; treasury = _treasury; } // ========== EXTERNAL SETTERS ========== function setPop(address _pop) external onlyOwner { pop = _pop; } function setTreasury(address _treasury) external onlyOwner { treasury = _treasury; } function approveRewardDistributor(address _distributor, bool _approved) external onlyOwner { emit RewardDistributorUpdated(_distributor, _approved); rewardDistributors[_distributor] = _approved; } // ========== EXTERNAL FUNCTIONS ========== /** * @notice Adds a Rewards DistributionData struct to the distributions * array. Any entries here will be iterated and rewards distributed to * each address when tokens are sent to this contract and distributeRewards() * is called by the autority. * @param destination An address to send rewards tokens too * @param amount The amount of rewards tokens to send * @param isLocker If the contract is a popLocker which has a slightly different notifyRewardsAmount interface */ function addRewardDistribution( address destination, uint256 amount, bool isLocker ) external onlyOwner returns (bool) { require(destination != address(0), "Cant add a zero address"); require(amount != 0, "Cant add a zero amount"); DistributionData memory rewardsDistribution = DistributionData(destination, amount, isLocker); distributions.push(rewardsDistribution); emit RewardDistributionAdded(distributions.length - 1, destination, amount, isLocker); return true; } /** * @notice Deletes a RewardDistribution from the distributions * so it will no longer be included in the call to distributeRewards() * @param index The index of the DistributionData to delete */ function removeRewardDistribution(uint256 index) external onlyOwner { require(index <= distributions.length - 1, "index out of bounds"); // shift distributions indexes across delete distributions[index]; } /** * @notice Edits a RewardDistribution in the distributions array. * @param index The index of the DistributionData to edit * @param destination The destination address. Send the same address to keep or different address to change it. * @param amount The amount of tokens to edit. Send the same number to keep or change the amount of tokens to send. * @param isLocker If the contract is a popLocker which has a slightly different notifyRewardsAmount interface */ function editRewardDistribution( uint256 index, address destination, uint256 amount, bool isLocker ) external onlyOwner returns (bool) { require(index <= distributions.length - 1, "index out of bounds"); distributions[index].destination = destination; distributions[index].amount = amount; distributions[index].isLocker = isLocker; return true; } function distributeRewards(uint256 amount) external override returns (bool) { require(amount > 0, "Nothing to distribute"); require(rewardDistributors[msg.sender], "not authorized"); require(pop != address(0), "Pop is not set"); require(treasury != address(0), "Treasury is not set"); require( IERC20(pop).balanceOf(address(this)) >= amount, "RewardsDistribution contract does not have enough tokens to distribute" ); uint256 remainder = amount; // Iterate the array of distributions sending the configured amounts for (uint256 i = 0; i < distributions.length; i++) { if (distributions[i].destination != address(0) || distributions[i].amount != 0) { remainder = remainder.sub(distributions[i].amount); // Approve the POP IERC20(pop).approve(distributions[i].destination, distributions[i].amount); // If the contract implements RewardsDistributionRecipient.sol, inform it how many POP its received. bytes memory payload; if (distributions[i].isLocker) { payload = abi.encodeWithSignature("notifyRewardAmount(address,uint256)", pop, distributions[i].amount); } else { payload = abi.encodeWithSignature("notifyRewardAmount(uint256)", distributions[i].amount); } // solhint-disable avoid-low-level-calls (bool success, ) = distributions[i].destination.call(payload); if (!success) { // Note: we're ignoring the return value as it will fail for contracts that do not implement RewardsDistributionRecipient.sol } } } // After all ditributions have been sent, send the remainder to the RewardsEscrow contract IERC20(pop).transfer(treasury, remainder); emit RewardsDistributed(amount); return true; } /* ========== VIEWS ========== */ /** * @notice Retrieve the length of the distributions array */ function distributionsLength() external view override returns (uint256) { return distributions.length; } /* ========== Events ========== */ event RewardDistributionAdded(uint256 index, address destination, uint256 amount, bool isLocker); event RewardsDistributed(uint256 amount); event RewardDistributorUpdated(address indexed distributor, bool approved); } // SPDX-License-Identifier: GPL-3.0 // Docgen-SOLC: 0.6.0 pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/irewardsdistribution interface IRewardsDistribution { // Structs struct DistributionData { address destination; uint256 amount; bool isLocker; } function distributions(uint256 index) external view returns ( address destination, uint256 amount, bool isLocker ); // DistributionData function distributionsLength() external view returns (uint256); // Mutative Functions function distributeRewards(uint256 amount) external returns (bool); } // SPDX-License-Identifier: GPL-3.0 // Docgen-SOLC: 0.6.0 pragma solidity ^0.8.0; // Libraries import "@openzeppelin/contracts/utils/math/SafeMath.sol"; // https://docs.synthetix.io/contracts/source/libraries/safedecimalmath library SafeDecimalMath { using SafeMath for uint256; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint256 public constant UNIT = 10**uint256(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint256 public constant PRECISE_UNIT = 10**uint256(highPrecisionDecimals); uint256 private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint256(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint256) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint256) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint256 quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint256 x, uint256 y) internal pure returns (uint256) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { uint256 resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint256 x, uint256 y) internal pure returns (uint256) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint256 i) internal pure returns (uint256) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint256 i) internal pure returns (uint256) { uint256 quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } // Computes `a - b`, setting the value to 0 if b > a. function floorsub(uint256 a, uint256 b) internal pure returns (uint256) { return b >= a ? 0 : a - b; } /* ---------- Utilities ---------- */ /* * Absolute value of the input, returned as a signed number. */ function signedAbs(int256 x) internal pure returns (int256) { return x < 0 ? -x : x; } /* * Absolute value of the input, returned as an unsigned number. */ function abs(int256 x) internal pure returns (uint256) { return uint256(signedAbs(x)); } } // SPDX-License-Identifier: GPL-3.0 // Docgen-SOLC: 0.8.0 pragma solidity ^0.8.0; // https://docs.synthetix.io/contracts/source/contracts/owned contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner() { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); }
* @return The result of safely multiplying x and y, interpreting the operands as fixed-point decimals of a standard unit. @dev The operands should be in the standard unit factor which will be divided out after the product of x and y is evaluated, so that product must be less than 2256. Unlike multiplyDecimal, this function rounds the result to the nearest increment. Rounding is useful when you need to retain fidelity for small decimal numbers (eg. small fractions or percentages)./
function multiplyDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _multiplyDecimalRound(x, y, UNIT); }
10,242,151
[ 1, 2463, 1021, 563, 434, 15303, 10194, 310, 619, 471, 677, 16, 10634, 310, 326, 14883, 487, 5499, 17, 1153, 15105, 434, 279, 4529, 2836, 18, 225, 1021, 14883, 1410, 506, 316, 326, 4529, 2836, 5578, 1492, 903, 506, 26057, 596, 1839, 326, 3017, 434, 619, 471, 677, 353, 12697, 16, 1427, 716, 3017, 1297, 506, 5242, 2353, 576, 5034, 18, 25448, 10194, 5749, 16, 333, 445, 21196, 326, 563, 358, 326, 11431, 5504, 18, 11370, 310, 353, 5301, 1347, 1846, 1608, 358, 15096, 13444, 292, 560, 364, 5264, 6970, 5600, 261, 1332, 18, 5264, 8330, 87, 578, 5551, 1023, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 10194, 5749, 11066, 12, 11890, 5034, 619, 16, 2254, 5034, 677, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 389, 7027, 1283, 5749, 11066, 12, 92, 16, 677, 16, 28721, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract BitUPToken is ERC20, Ownable { using SafeMath for uint; /*----------------- Token Information -----------------*/ string public constant name = "BitUP Token"; string public constant symbol = "BUT"; uint8 public decimals = 18; // (ERC20 API) Decimal precision, factor is 1e18 mapping (address => uint256) balances; // User's balances table mapping (address => mapping (address => uint256)) allowed; // User's allowances table /*----------------- Alloc Information -----------------*/ uint256 public totalSupply; uint256 public presaleSupply; // Pre-sale supply uint256 public angelSupply; // Angel supply uint256 public marketingSupply; // marketing supply uint256 public foundationSupply; // /Foundation supply uint256 public teamSupply; // Team supply uint256 public communitySupply; // Community supply uint256 public teamSupply6Months; //Amount of Team supply could be released after 6 months uint256 public teamSupply12Months; //Amount of Team supply could be released after 12 months uint256 public teamSupply18Months; //Amount of Team supply could be released after 18 months uint256 public teamSupply24Months; //Amount of Team supply could be released after 24 months uint256 public TeamLockingPeriod6Months; // Locking period for team's supply, release 1/4 per 6 months uint256 public TeamLockingPeriod12Months; // Locking period for team's supply, release 1/4 per 6 months uint256 public TeamLockingPeriod18Months; // Locking period for team's supply, release 1/4 per 6 months uint256 public TeamLockingPeriod24Months; // Locking period for team's supply, release 1/4 per 6 months address public presaleAddress; // Presale address address public angelAddress; // Angel address address public marketingAddress; // marketing address address public foundationAddress; // Foundation address address public teamAddress; // Team address address public communityAddress; // Community address function () { //if ether is sent to this address, send it back. //throw; require(false); } /*----------------- Modifiers -----------------*/ modifier nonZeroAddress(address _to) { // Ensures an address is provided require(_to != 0x0); _; } modifier nonZeroAmount(uint _amount) { // Ensures a non-zero amount require(_amount > 0); _; } modifier nonZeroValue() { // Ensures a non-zero value is passed require(msg.value > 0); _; } modifier checkTeamLockingPeriod6Months() { // Ensures locking period is over assert(now >= TeamLockingPeriod6Months); _; } modifier checkTeamLockingPeriod12Months() { // Ensures locking period is over assert(now >= TeamLockingPeriod12Months); _; } modifier checkTeamLockingPeriod18Months() { // Ensures locking period is over assert(now >= TeamLockingPeriod18Months); _; } modifier checkTeamLockingPeriod24Months() { // Ensures locking period is over assert(now >= TeamLockingPeriod24Months); _; } modifier onlyTeam() { // Ensures only team can call the function require(msg.sender == teamAddress); _; } /*----------------- Burn -----------------*/ event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; // balances[burner] = balances[burner].sub(_value); decrementBalance(burner, _value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } /*----------------- Token API -----------------*/ // ------------------------------------------------- // Total supply // ------------------------------------------------- function totalSupply() constant returns (uint256){ return totalSupply; } // ------------------------------------------------- // Transfers amount to address // ------------------------------------------------- function transfer(address _to, uint256 _amount) returns (bool success) { require(balanceOf(msg.sender) >= _amount); uint previousBalances = balances[msg.sender] + balances[_to]; addToBalance(_to, _amount); decrementBalance(msg.sender, _amount); Transfer(msg.sender, _to, _amount); assert(balances[msg.sender] + balances[_to] == previousBalances); return true; } // ------------------------------------------------- // Transfers from one address to another (need allowance to be called first) // ------------------------------------------------- function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) { require(balanceOf(_from) >= _amount); require(allowance(_from, msg.sender) >= _amount); uint previousBalances = balances[_from] + balances[_to]; decrementBalance(_from, _amount); addToBalance(_to, _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); Transfer(_from, _to, _amount); assert(balances[_from] + balances[_to] == previousBalances); return true; } // ------------------------------------------------- // Approves another address a certain amount of FUEL // ------------------------------------------------- function approve(address _spender, uint256 _value) returns (bool success) { require((_value == 0) || (allowance(msg.sender, _spender) == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // ------------------------------------------------- // Gets an address's FUEL allowance // ------------------------------------------------- function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // ------------------------------------------------- // Gets the FUEL balance of any address // ------------------------------------------------- function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } // ------------------------------------------------- // Contract's constructor // ------------------------------------------------- function BitUPToken() { totalSupply = 1000000000 * 1e18; // 100% - 1 billion total BUT with 18 decimals presaleSupply = 400000000 * 1e18; // 40% - 400 million BUT pre-crowdsale angelSupply = 50000000 * 1e18; // 5% - 50 million BUT for the angel crowdsale teamSupply = 200000000 * 1e18; // 20% - 200 million BUT for team. 1/4 part released per 6 months foundationSupply = 150000000 * 1e18; // 15% - 300 million BUT for foundation/incentivising efforts marketingSupply = 100000000 * 1e18; // 10% - 100 million BUT for communitySupply = 100000000 * 1e18; // 10% - 100 million BUT for teamSupply6Months = 50000000 * 1e18; // team supply release 1/4 per 6 months teamSupply12Months = 50000000 * 1e18; // team supply release 1/4 per 6 months teamSupply18Months = 50000000 * 1e18; // team supply release 1/4 per 6 months teamSupply24Months = 50000000 * 1e18; // team supply release 1/4 per 6 months angelAddress = 0xeF01453A730486d262D0b490eF1aDBBF62C2Fe00; // Angel address presaleAddress = 0x2822332F63a6b80E21cEA5C8c43Cb6f393eb5703; // Presale address teamAddress = 0x8E199e0c1DD38d455815E11dc2c9A64D6aD893B7; // Team address foundationAddress = 0xcA972ac76F4Db643C30b86E4A9B54EaBB88Ce5aD; // Foundation address marketingAddress = 0xd2631280F7f0472271Ae298aF034eBa549d792EA; // marketing address communityAddress = 0xF691e8b2B2293D3d3b06ecdF217973B40258208C; //Community address TeamLockingPeriod6Months = now.add(180 * 1 days); // 180 days locking period TeamLockingPeriod12Months = now.add(360 * 1 days); // 360 days locking period TeamLockingPeriod18Months = now.add(450 * 1 days); // 450 days locking period TeamLockingPeriod24Months = now.add(730 * 1 days); // 730 days locking period addToBalance(foundationAddress, foundationSupply); foundationSupply = 0; addToBalance(marketingAddress, marketingSupply); marketingSupply = 0; addToBalance(communityAddress, communitySupply); communitySupply = 0; addToBalance(presaleAddress, presaleSupply); presaleSupply = 0; addToBalance(angelAddress, angelSupply); angelSupply = 0; } // ------------------------------------------------- // Releases 1/4 of team supply after 6 months // ------------------------------------------------- function releaseTeamTokensAfter6Months() checkTeamLockingPeriod6Months onlyTeam returns(bool success) { require(teamSupply6Months > 0); addToBalance(teamAddress, teamSupply6Months); Transfer(0x0, teamAddress, teamSupply6Months); teamSupply6Months = 0; teamSupply.sub(teamSupply6Months); return true; } // ------------------------------------------------- // Releases 1/4 of team supply after 12 months // ------------------------------------------------- function releaseTeamTokensAfter12Months() checkTeamLockingPeriod12Months onlyTeam returns(bool success) { require(teamSupply12Months > 0); addToBalance(teamAddress, teamSupply12Months); Transfer(0x0, teamAddress, teamSupply12Months); teamSupply12Months = 0; teamSupply.sub(teamSupply12Months); return true; } // ------------------------------------------------- // Releases 1/4 of team supply after 18 months // ------------------------------------------------- function releaseTeamTokensAfter18Months() checkTeamLockingPeriod18Months onlyTeam returns(bool success) { require(teamSupply18Months > 0); addToBalance(teamAddress, teamSupply18Months); Transfer(0x0, teamAddress, teamSupply18Months); teamSupply18Months = 0; teamSupply.sub(teamSupply18Months); return true; } // ------------------------------------------------- // Releases 1/4 of team supply after 24 months // ------------------------------------------------- function releaseTeamTokensAfter24Months() checkTeamLockingPeriod24Months onlyTeam returns(bool success) { require(teamSupply24Months > 0); addToBalance(teamAddress, teamSupply24Months); Transfer(0x0, teamAddress, teamSupply24Months); teamSupply24Months = 0; teamSupply.sub(teamSupply24Months); return true; } // ------------------------------------------------- // Adds to balance // ------------------------------------------------- function addToBalance(address _address, uint _amount) internal { balances[_address] = SafeMath.add(balances[_address], _amount); } // ------------------------------------------------- // Removes from balance // ------------------------------------------------- function decrementBalance(address _address, uint _amount) internal { balances[_address] = SafeMath.sub(balances[_address], _amount); } }
Locking period for team's supply, release 1/4 per 6 months
uint256 public TeamLockingPeriod12Months;
366,306
[ 1, 2531, 310, 3879, 364, 5927, 1807, 14467, 16, 3992, 404, 19, 24, 1534, 1666, 8846, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 10434, 2531, 310, 5027, 2138, 19749, 31, 10402, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; library CommonLibrary { struct Data { mapping (uint => Node) nodes; mapping (string => uint) nodesID; mapping (string => uint16) nodeGroups; uint16 nodeGroupID; uint nodeID; uint ownerNotationId; uint addNodeAddressId; } struct Node { string nodeName; address producer; address node; uint256 date; bool starmidConfirmed; address[] outsourceConfirmed; uint16[] nodeGroup; uint8 producersPercent; uint16 nodeSocialMedia; } function addNodeGroup(Data storage self, string _newNodeGroup) returns(bool _result, uint16 _id) { if (self.nodeGroups[_newNodeGroup] == 0) { _id = self.nodeGroupID += 1; self.nodeGroups[_newNodeGroup] = self.nodeGroupID; _result = true; } } function addNode( Data storage self, string _newNode, uint8 _producersPercent ) returns (bool _result, uint _id) { if (self.nodesID[_newNode] < 1 && _producersPercent < 100) { _id = self.nodeID += 1; require(self.nodeID < 1000000000000); self.nodes[self.nodeID].nodeName = _newNode; self.nodes[self.nodeID].producer = msg.sender; self.nodes[self.nodeID].date = block.timestamp; self.nodes[self.nodeID].starmidConfirmed = false; self.nodes[self.nodeID].producersPercent = _producersPercent; self.nodesID[_newNode] = self.nodeID; _result = true; } else _result = false; } function editNode( Data storage self, uint _nodeID, address _nodeAddress, bool _isNewProducer, address _newProducer, uint8 _newProducersPercent, bool _starmidConfirmed ) returns (bool) { if (_isNewProducer == true) { self.nodes[_nodeID].node = _nodeAddress; self.nodes[_nodeID].producer = _newProducer; self.nodes[_nodeID].producersPercent = _newProducersPercent; self.nodes[_nodeID].starmidConfirmed = _starmidConfirmed; return true; } else { self.nodes[_nodeID].node = _nodeAddress; self.nodes[_nodeID].starmidConfirmed = _starmidConfirmed; return true; } } function addNodeAddress(Data storage self, uint _nodeID, address _nodeAddress) returns(bool _result, uint _id) { if (msg.sender == self.nodes[_nodeID].producer) { if (self.nodes[_nodeID].node == 0) { self.nodes[_nodeID].node = _nodeAddress; _id = self.addNodeAddressId += 1;//for event count _result = true; } else _result = false; } else _result = false; } //-----------------------------------------Starmid Exchange functions function stockMinSellPrice(StarCoinLibrary.Data storage self, uint _buyPrice, uint _node) constant returns (uint _minSellPrice) { _minSellPrice = _buyPrice + 1; for (uint i = 0; i < self.stockSellOrderPrices[_node].length; i++) { if(self.stockSellOrderPrices[_node][i] < _minSellPrice) _minSellPrice = self.stockSellOrderPrices[_node][i]; } } function stockMaxBuyPrice (StarCoinLibrary.Data storage self, uint _sellPrice, uint _node) constant returns (uint _maxBuyPrice) { _maxBuyPrice = _sellPrice - 1; for (uint i = 0; i < self.stockBuyOrderPrices[_node].length; i++) { if(self.stockBuyOrderPrices[_node][i] > _maxBuyPrice) _maxBuyPrice = self.stockBuyOrderPrices[_node][i]; } } function stockDeleteFirstOrder(StarCoinLibrary.Data storage self, uint _node, uint _price, bool _isStockSellOrders) { if (_isStockSellOrders == true) uint _length = self.stockSellOrders[_node][_price].length; else _length = self.stockBuyOrders[_node][_price].length; for (uint ii = 0; ii < _length - 1; ii++) { if (_isStockSellOrders == true) self.stockSellOrders[_node][_price][ii] = self.stockSellOrders[_node][_price][ii + 1]; else self.stockBuyOrders[_node][_price][ii] = self.stockBuyOrders[_node][_price][ii + 1]; } if (_isStockSellOrders == true) { delete self.stockSellOrders[_node][_price][self.stockSellOrders[_node][_price].length - 1]; self.stockSellOrders[_node][_price].length--; //Delete _price from stockSellOrderPrices[_node][] if it&#39;s the last order if (self.stockSellOrders[_node][_price].length == 0) { uint fromArg = 99999; for (uint8 iii = 0; iii < self.stockSellOrderPrices[_node].length - 1; iii++) { if (self.stockSellOrderPrices[_node][iii] == _price) { fromArg = iii; } if (fromArg != 99999 && iii >= fromArg) self.stockSellOrderPrices[_node][iii] = self.stockSellOrderPrices[_node][iii + 1]; } delete self.stockSellOrderPrices[_node][self.stockSellOrderPrices[_node].length-1]; self.stockSellOrderPrices[_node].length--; } } else { delete self.stockBuyOrders[_node][_price][self.stockBuyOrders[_node][_price].length - 1]; self.stockBuyOrders[_node][_price].length--; //Delete _price from stockBuyOrderPrices[_node][] if it&#39;s the last order if (self.stockBuyOrders[_node][_price].length == 0) { fromArg = 99999; for (iii = 0; iii < self.stockBuyOrderPrices[_node].length - 1; iii++) { if (self.stockBuyOrderPrices[_node][iii] == _price) { fromArg = iii; } if (fromArg != 99999 && iii >= fromArg) self.stockBuyOrderPrices[_node][iii] = self.stockBuyOrderPrices[_node][iii + 1]; } delete self.stockBuyOrderPrices[_node][self.stockBuyOrderPrices[_node].length-1]; self.stockBuyOrderPrices[_node].length--; } } } function stockSaveOwnerInfo(StarCoinLibrary.Data storage self, uint _node, uint _amount, address _buyer, address _seller, uint _price) { //--------------------------------------_buyer self.StockOwnersBuyPrice[_buyer][_node].sumPriceAmount += _amount*_price; self.StockOwnersBuyPrice[_buyer][_node].sumDateAmount += _amount*block.timestamp; self.StockOwnersBuyPrice[_buyer][_node].sumAmount += _amount; uint16 _thisNode = 0; for (uint16 i6 = 0; i6 < self.stockOwnerInfo[_buyer].nodes.length; i6++) { if (self.stockOwnerInfo[_buyer].nodes[i6] == _node) _thisNode = 1; } if (_thisNode == 0) self.stockOwnerInfo[_buyer].nodes.push(_node); //--------------------------------------_seller if(self.StockOwnersBuyPrice[_seller][_node].sumPriceAmount > 0) { self.StockOwnersBuyPrice[_seller][_node].sumPriceAmount -= _amount*_price; self.StockOwnersBuyPrice[_buyer][_node].sumDateAmount -= _amount*block.timestamp; self.StockOwnersBuyPrice[_buyer][_node].sumAmount -= _amount; } _thisNode = 0; for (i6 = 0; i6 < self.stockOwnerInfo[_seller].nodes.length; i6++) { if (self.stockOwnerInfo[_seller].nodes[i6] == _node) _thisNode = i6; } if (_thisNode > 0) { for (uint ii = _thisNode; ii < self.stockOwnerInfo[msg.sender].nodes.length - 1; ii++) { self.stockOwnerInfo[msg.sender].nodes[ii] = self.stockOwnerInfo[msg.sender].nodes[ii + 1]; } delete self.stockOwnerInfo[msg.sender].nodes[self.stockOwnerInfo[msg.sender].nodes.length - 1]; } } function deleteStockBuyOrder(StarCoinLibrary.Data storage self, uint _iii, uint _node, uint _price) { for (uint ii = _iii; ii < self.stockBuyOrders[_node][_price].length - 1; ii++) { self.stockBuyOrders[_node][_price][ii] = self.stockBuyOrders[_node][_price][ii + 1]; } delete self.stockBuyOrders[_node][_price][self.stockBuyOrders[_node][_price].length - 1]; self.stockBuyOrders[_node][_price].length--; //Delete _price from stockBuyOrderPrices[_node][] if it&#39;s the last order if (self.stockBuyOrders[_node][_price].length == 0) { uint _fromArg = 99999; for (_iii = 0; _iii < self.stockBuyOrderPrices[_node].length - 1; _iii++) { if (self.stockBuyOrderPrices[_node][_iii] == _price) { _fromArg = _iii; } if (_fromArg != 99999 && _iii >= _fromArg) self.stockBuyOrderPrices[_node][_iii] = self.stockBuyOrderPrices[_node][_iii + 1]; } delete self.stockBuyOrderPrices[_node][self.stockBuyOrderPrices[_node].length-1]; self.stockBuyOrderPrices[_node].length--; } } function deleteStockSellOrder(StarCoinLibrary.Data storage self, uint _iii, uint _node, uint _price) { for (uint ii = _iii; ii < self.stockSellOrders[_node][_price].length - 1; ii++) { self.stockSellOrders[_node][_price][ii] = self.stockSellOrders[_node][_price][ii + 1]; } delete self.stockSellOrders[_node][_price][self.stockSellOrders[_node][_price].length - 1]; self.stockSellOrders[_node][_price].length--; //Delete _price from stockSellOrderPrices[_node][] if it&#39;s the last order if (self.stockSellOrders[_node][_price].length == 0) { uint _fromArg = 99999; for (_iii = 0; _iii < self.stockSellOrderPrices[_node].length - 1; _iii++) { if (self.stockSellOrderPrices[_node][_iii] == _price) { _fromArg = _iii; } if (_fromArg != 99999 && _iii >= _fromArg) self.stockSellOrderPrices[_node][_iii] = self.stockSellOrderPrices[_node][_iii + 1]; } delete self.stockSellOrderPrices[_node][self.stockSellOrderPrices[_node].length-1]; self.stockSellOrderPrices[_node].length--; } } } library StarCoinLibrary { struct Data { uint256 lastMint; mapping (address => uint256) balanceOf; mapping (address => uint256) frozen; uint32 ordersId; mapping (uint256 => orderInfo[]) buyOrders; mapping (uint256 => orderInfo[]) sellOrders; mapping (address => mapping (uint => uint)) stockBalanceOf; mapping (address => mapping (uint => uint)) stockFrozen; mapping (uint => uint) emissionLimits; uint32 stockOrdersId; mapping (uint => emissionNodeInfo) emissions; mapping (uint => mapping (uint256 => stockOrderInfo[])) stockBuyOrders; mapping (uint => mapping (uint256 => stockOrderInfo[])) stockSellOrders; mapping (address => mapping (uint => uint)) lastDividends; mapping (address => mapping (uint => averageBuyPrice)) StockOwnersBuyPrice; mapping (address => ownerInfo) stockOwnerInfo; uint[] buyOrderPrices; uint[] sellOrderPrices; mapping (uint => uint[]) stockBuyOrderPrices; mapping (uint => uint[]) stockSellOrderPrices; mapping (address => uint) pendingWithdrawals; } struct orderInfo { uint date; address client; uint256 amount; uint256 price; bool isBuyer; uint orderId; } struct emissionNodeInfo { uint emissionNumber; uint date; } struct stockOrderInfo { uint date; address client; uint256 amount; uint256 price; bool isBuyer; uint orderId; uint node; } struct averageBuyPrice { uint sumPriceAmount; uint sumDateAmount; uint sumAmount; } struct ownerInfo { uint index; uint[] nodes; } event Transfer(address indexed from, address indexed to, uint256 value); event TradeHistory(uint date, address buyer, address seller, uint price, uint amount, uint orderId); function buyOrder(Data storage self, uint256 _buyPrice) returns (uint[4] _results) { uint _remainingValue = msg.value; uint256[4] memory it; if (minSellPrice(self, _buyPrice) != _buyPrice + 1) { it[3] = self.sellOrderPrices.length; for (it[1] = 0; it[1] < it[3]; it[1]++) { uint _minPrice = minSellPrice(self, _buyPrice); it[2] = self.sellOrders[_minPrice].length; for (it[0] = 0; it[0] < it[2]; it[0]++) { uint _amount = _remainingValue/_minPrice; if (_amount >= self.sellOrders[_minPrice][0].amount) { //buy starcoins for ether self.balanceOf[msg.sender] += self.sellOrders[_minPrice][0].amount;// adds the amount to buyer&#39;s balance self.frozen[self.sellOrders[_minPrice][0].client] -= self.sellOrders[_minPrice][0].amount;// subtracts the amount from seller&#39;s frozen balance Transfer(self.sellOrders[_minPrice][0].client, msg.sender, self.sellOrders[_minPrice][0].amount); //transfer ether to seller uint256 amountTransfer = _minPrice*self.sellOrders[_minPrice][0].amount; self.pendingWithdrawals[self.sellOrders[_minPrice][0].client] += amountTransfer; //save the transaction TradeHistory(block.timestamp, msg.sender, self.sellOrders[_minPrice][0].client, _minPrice, self.sellOrders[_minPrice][0].amount, self.sellOrders[_minPrice][0].orderId); _remainingValue -= amountTransfer; _results[0] += self.sellOrders[_minPrice][0].amount; //delete sellOrders[_minPrice][0] and move each element deleteFirstOrder(self, _minPrice, true); if (_remainingValue/_minPrice < 1) break; } else { //edit sellOrders[_minPrice][0] self.sellOrders[_minPrice][0].amount = self.sellOrders[_minPrice][0].amount - _amount; //buy starcoins for ether self.balanceOf[msg.sender] += _amount;// adds the _amount to buyer&#39;s balance self.frozen[self.sellOrders[_minPrice][0].client] -= _amount;// subtracts the _amount from seller&#39;s frozen balance Transfer(self.sellOrders[_minPrice][0].client, msg.sender, _amount); //save the transaction TradeHistory(block.timestamp, msg.sender, self.sellOrders[_minPrice][0].client, _minPrice, _amount, self.sellOrders[_minPrice][0].orderId); //transfer ether to seller uint256 amountTransfer1 = _amount*_minPrice; self.pendingWithdrawals[self.sellOrders[_minPrice][0].client] += amountTransfer1; _remainingValue -= amountTransfer1; _results[0] += _amount; if(_remainingValue/_minPrice < 1) { _results[3] = 1; break; } } } if (_remainingValue/_minPrice < 1) { _results[3] = 1; break; } } if(_remainingValue/_buyPrice < 1) self.pendingWithdrawals[msg.sender] += _remainingValue;//returns change to buyer } if (minSellPrice(self, _buyPrice) == _buyPrice + 1 && _remainingValue/_buyPrice >= 1) { //save new order _results[1] = _remainingValue/_buyPrice; if (_remainingValue - _results[1]*_buyPrice > 0) self.pendingWithdrawals[msg.sender] += _remainingValue - _results[1]*_buyPrice;//returns change to buyer self.ordersId += 1; _results[2] = self.ordersId; self.buyOrders[_buyPrice].push(orderInfo( block.timestamp, msg.sender, _results[1], _buyPrice, true, self.ordersId)); _results[3] = 1; //Add _buyPrice to buyOrderPrices[] it[0] = 99999; for (it[1] = 0; it[1] < self.buyOrderPrices.length; it[1]++) { if (self.buyOrderPrices[it[1]] == _buyPrice) it[0] = it[1]; } if (it[0] == 99999) self.buyOrderPrices.push(_buyPrice); } } function minSellPrice(Data storage self, uint _buyPrice) constant returns (uint _minSellPrice) { _minSellPrice = _buyPrice + 1; for (uint i = 0; i < self.sellOrderPrices.length; i++) { if(self.sellOrderPrices[i] < _minSellPrice) _minSellPrice = self.sellOrderPrices[i]; } } function sellOrder(Data storage self, uint256 _sellPrice, uint _amount) returns (uint[4] _results) { uint _remainingAmount = _amount; require(self.balanceOf[msg.sender] >= _amount); uint256[4] memory it; if (maxBuyPrice(self, _sellPrice) != _sellPrice - 1) { it[3] = self.buyOrderPrices.length; for (it[1] = 0; it[1] < it[3]; it[1]++) { uint _maxPrice = maxBuyPrice(self, _sellPrice); it[2] = self.buyOrders[_maxPrice].length; for (it[0] = 0; it[0] < it[2]; it[0]++) { if (_remainingAmount >= self.buyOrders[_maxPrice][0].amount) { //sell starcoins for ether self.balanceOf[msg.sender] -= self.buyOrders[_maxPrice][0].amount;// subtracts amount from seller&#39;s balance self.balanceOf[self.buyOrders[_maxPrice][0].client] += self.buyOrders[_maxPrice][0].amount;// adds the amount to buyer&#39;s balance Transfer(msg.sender, self.buyOrders[_maxPrice][0].client, self.buyOrders[_maxPrice][0].amount); //transfer ether to seller uint _amountTransfer = _maxPrice*self.buyOrders[_maxPrice][0].amount; self.pendingWithdrawals[msg.sender] += _amountTransfer; //save the transaction TradeHistory(block.timestamp, self.buyOrders[_maxPrice][0].client, msg.sender, _maxPrice, self.buyOrders[_maxPrice][0].amount, self.buyOrders[_maxPrice][0].orderId); _remainingAmount -= self.buyOrders[_maxPrice][0].amount; _results[0] += self.buyOrders[_maxPrice][0].amount; //delete buyOrders[_maxPrice][0] and move each element deleteFirstOrder(self, _maxPrice, false); if(_remainingAmount < 1) break; } else { //edit buyOrders[_maxPrice][0] self.buyOrders[_maxPrice][0].amount = self.buyOrders[_maxPrice][0].amount-_remainingAmount; //buy starcoins for ether self.balanceOf[msg.sender] -= _remainingAmount;// subtracts amount from seller&#39;s balance self.balanceOf[self.buyOrders[_maxPrice][0].client] += _remainingAmount;// adds the amount to buyer&#39;s balance Transfer(msg.sender, self.buyOrders[_maxPrice][0].client, _remainingAmount); //save the transaction TradeHistory(block.timestamp, self.buyOrders[_maxPrice][0].client, msg.sender, _maxPrice, _remainingAmount, self.buyOrders[_maxPrice][0].orderId); //transfer ether to seller uint256 amountTransfer1 = _maxPrice*_remainingAmount; self.pendingWithdrawals[msg.sender] += amountTransfer1; _results[0] += _remainingAmount; _remainingAmount = 0; break; } } if (_remainingAmount<1) { _results[3] = 1; break; } } } if (maxBuyPrice(self, _sellPrice) == _sellPrice - 1 && _remainingAmount >= 1) { //save new order _results[1] = _remainingAmount; self.ordersId += 1; _results[2] = self.ordersId; self.sellOrders[_sellPrice].push(orderInfo( block.timestamp, msg.sender, _results[1], _sellPrice, false, _results[2])); _results[3] = 1; //transfer starcoins to the frozen balance self.frozen[msg.sender] += _remainingAmount; self.balanceOf[msg.sender] -= _remainingAmount; //Add _sellPrice to sellOrderPrices[] it[0] = 99999; for (it[1] = 0; it[1] < self.sellOrderPrices.length; it[1]++) { if (self.sellOrderPrices[it[1]] == _sellPrice) it[0] = it[1]; } if (it[0] == 99999) self.sellOrderPrices.push(_sellPrice); } } function maxBuyPrice (Data storage self, uint _sellPrice) constant returns (uint _maxBuyPrice) { _maxBuyPrice = _sellPrice - 1; for (uint i = 0; i < self.buyOrderPrices.length; i++) { if(self.buyOrderPrices[i] > _maxBuyPrice) _maxBuyPrice = self.buyOrderPrices[i]; } } function deleteFirstOrder(Data storage self, uint _price, bool _isSellOrders) { if (_isSellOrders == true) uint _length = self.sellOrders[_price].length; else _length = self.buyOrders[_price].length; for (uint ii = 0; ii < _length - 1; ii++) { if (_isSellOrders == true) self.sellOrders[_price][ii] = self.sellOrders[_price][ii + 1]; else self.buyOrders[_price][ii] = self.buyOrders[_price][ii+1]; } if (_isSellOrders == true) { delete self.sellOrders[_price][self.sellOrders[_price].length - 1]; self.sellOrders[_price].length--; //Delete _price from sellOrderPrices[] if it&#39;s the last order if (_length == 1) { uint _fromArg = 99999; for (uint8 iii = 0; iii < self.sellOrderPrices.length - 1; iii++) { if (self.sellOrderPrices[iii] == _price) { _fromArg = iii; } if (_fromArg != 99999 && iii >= _fromArg) self.sellOrderPrices[iii] = self.sellOrderPrices[iii + 1]; } delete self.sellOrderPrices[self.sellOrderPrices.length-1]; self.sellOrderPrices.length--; } } else { delete self.buyOrders[_price][self.buyOrders[_price].length - 1]; self.buyOrders[_price].length--; //Delete _price from buyOrderPrices[] if it&#39;s the last order if (_length == 1) { _fromArg = 99999; for (iii = 0; iii < self.buyOrderPrices.length - 1; iii++) { if (self.buyOrderPrices[iii] == _price) { _fromArg = iii; } if (_fromArg != 99999 && iii >= _fromArg) self.buyOrderPrices[iii] = self.buyOrderPrices[iii + 1]; } delete self.buyOrderPrices[self.buyOrderPrices.length-1]; self.buyOrderPrices.length--; } } } function cancelBuyOrder(Data storage self, uint _thisOrderID, uint _price) public returns(bool) { for (uint8 iii = 0; iii < self.buyOrders[_price].length; iii++) { if (self.buyOrders[_price][iii].orderId == _thisOrderID) { //delete buyOrders[_price][iii] and move each element require(msg.sender == self.buyOrders[_price][iii].client); uint _remainingValue = self.buyOrders[_price][iii].price*self.buyOrders[_price][iii].amount; for (uint ii = iii; ii < self.buyOrders[_price].length - 1; ii++) { self.buyOrders[_price][ii] = self.buyOrders[_price][ii + 1]; } delete self.buyOrders[_price][self.buyOrders[_price].length - 1]; self.buyOrders[_price].length--; self.pendingWithdrawals[msg.sender] += _remainingValue;//returns ether to buyer break; } } //Delete _price from buyOrderPrices[] if it&#39;s the last order if (self.buyOrders[_price].length == 0) { uint _fromArg = 99999; for (uint8 iiii = 0; iiii < self.buyOrderPrices.length - 1; iiii++) { if (self.buyOrderPrices[iiii] == _price) { _fromArg = iiii; } if (_fromArg != 99999 && iiii >= _fromArg) self.buyOrderPrices[iiii] = self.buyOrderPrices[iiii + 1]; } delete self.buyOrderPrices[self.buyOrderPrices.length-1]; self.buyOrderPrices.length--; } return true; } function cancelSellOrder(Data storage self, uint _thisOrderID, uint _price) public returns(bool) { for (uint8 iii = 0; iii < self.sellOrders[_price].length; iii++) { if (self.sellOrders[_price][iii].orderId == _thisOrderID) { require(msg.sender == self.sellOrders[_price][iii].client); //return starcoins from the frozen balance to seller self.frozen[msg.sender] -= self.sellOrders[_price][iii].amount; self.balanceOf[msg.sender] += self.sellOrders[_price][iii].amount; //delete sellOrders[_price][iii] and move each element for (uint ii = iii; ii < self.sellOrders[_price].length - 1; ii++) { self.sellOrders[_price][ii] = self.sellOrders[_price][ii + 1]; } delete self.sellOrders[_price][self.sellOrders[_price].length - 1]; self.sellOrders[_price].length--; break; } } //Delete _price from sellOrderPrices[] if it&#39;s the last order if (self.sellOrders[_price].length == 0) { uint _fromArg = 99999; for (uint8 iiii = 0; iiii < self.sellOrderPrices.length - 1; iiii++) { if (self.sellOrderPrices[iiii] == _price) { _fromArg = iiii; } if (_fromArg != 99999 && iiii >= _fromArg) self.sellOrderPrices[iiii] = self.sellOrderPrices[iiii + 1]; } delete self.sellOrderPrices[self.sellOrderPrices.length-1]; self.sellOrderPrices.length--; } return true; } } library StarmidLibrary { event Transfer(address indexed from, address indexed to, uint256 value); event StockTransfer(address indexed from, address indexed to, uint indexed node, uint256 value); event StockTradeHistory(uint node, uint date, address buyer, address seller, uint price, uint amount, uint orderId); function stockBuyOrder(StarCoinLibrary.Data storage self, uint _node, uint256 _buyPrice, uint _amount) public returns (uint[4] _results) { require(self.balanceOf[msg.sender] >= _buyPrice*_amount); uint256[4] memory it; if (CommonLibrary.stockMinSellPrice(self, _buyPrice, _node) != _buyPrice + 1) { it[3] = self.stockSellOrderPrices[_node].length; for (it[1] = 0; it[1] < it[3]; it[1]++) { uint minPrice = CommonLibrary.stockMinSellPrice(self, _buyPrice, _node); it[2] = self.stockSellOrders[_node][minPrice].length; for (it[0] = 0; it[0] < it[2]; it[0]++) { if (_amount >= self.stockSellOrders[_node][minPrice][0].amount) { //buy stocks for starcoins self.stockBalanceOf[msg.sender][_node] += self.stockSellOrders[_node][minPrice][0].amount;// add the amount to buyer&#39;s balance self.stockFrozen[self.stockSellOrders[_node][minPrice][0].client][_node] -= self.stockSellOrders[_node][minPrice][0].amount;// subtracts amount from seller&#39;s frozen stock balance //write stockOwnerInfo and stockOwners for dividends CommonLibrary.stockSaveOwnerInfo(self, _node, self.stockSellOrders[_node][minPrice][0].amount, msg.sender, self.stockSellOrders[_node][minPrice][0].client, minPrice); //transfer starcoins to seller self.balanceOf[msg.sender] -= self.stockSellOrders[_node][minPrice][0].amount*minPrice;// subtracts amount from buyer&#39;s balance self.balanceOf[self.stockSellOrders[_node][minPrice][0].client] += self.stockSellOrders[_node][minPrice][0].amount*minPrice;// adds the amount to seller&#39;s balance Transfer(self.stockSellOrders[_node][minPrice][0].client, msg.sender, self.stockSellOrders[_node][minPrice][0].amount*minPrice); //save the transaction into event StocksTradeHistory; StockTradeHistory(_node, block.timestamp, msg.sender, self.stockSellOrders[_node][minPrice][0].client, minPrice, self.stockSellOrders[_node][minPrice][0].amount, self.stockSellOrders[_node][minPrice][0].orderId); _amount -= self.stockSellOrders[_node][minPrice][0].amount; _results[0] += self.stockSellOrders[_node][minPrice][0].amount; //delete stockSellOrders[_node][minPrice][0] and move each element CommonLibrary.stockDeleteFirstOrder(self, _node, minPrice, true); if (_amount<1) break; } else { //edit stockSellOrders[_node][minPrice][0] self.stockSellOrders[_node][minPrice][0].amount -= _amount; //buy stocks for starcoins self.stockBalanceOf[msg.sender][_node] += _amount;// adds the _amount to buyer&#39;s balance self.stockFrozen[self.stockSellOrders[_node][minPrice][0].client][_node] -= _amount;// subtracts _amount from seller&#39;s frozen stock balance //write stockOwnerInfo and stockOwners for dividends CommonLibrary.stockSaveOwnerInfo(self, _node, _amount, msg.sender, self.stockSellOrders[_node][minPrice][0].client, minPrice); //transfer starcoins to seller self.balanceOf[msg.sender] -= _amount*minPrice;// subtracts _amount from buyer&#39;s balance self.balanceOf[self.stockSellOrders[_node][minPrice][0].client] += _amount*minPrice;// adds the amount to seller&#39;s balance Transfer(self.stockSellOrders[_node][minPrice][0].client, msg.sender, _amount*minPrice); //save the transaction into event StocksTradeHistory; StockTradeHistory(_node, block.timestamp, msg.sender, self.stockSellOrders[_node][minPrice][0].client, minPrice, _amount, self.stockSellOrders[_node][minPrice][0].orderId); _results[0] += _amount; _amount = 0; break; } } if(_amount < 1) { _results[3] = 1; break; } } } if (CommonLibrary.stockMinSellPrice(self, _buyPrice, _node) == _buyPrice + 1 && _amount >= 1) { //save new order _results[1] = _amount; self.stockOrdersId += 1; _results[2] = self.stockOrdersId; self.stockBuyOrders[_node][_buyPrice].push(StarCoinLibrary.stockOrderInfo(block.timestamp, msg.sender, _results[1], _buyPrice, true, self.stockOrdersId, _node)); _results[3] = 1; //transfer starcoins to the frozen balance self.frozen[msg.sender] += _amount*_buyPrice; self.balanceOf[msg.sender] -= _amount*_buyPrice; //Add _buyPrice to stockBuyOrderPrices[_node][] it[0] = 99999; for (it[1] = 0; it[1] < self.stockBuyOrderPrices[_node].length; it[1]++) { if (self.stockBuyOrderPrices[_node][it[1]] == _buyPrice) it[0] = it[1]; } if (it[0] == 99999) self.stockBuyOrderPrices[_node].push(_buyPrice); } } function stockSellOrder(StarCoinLibrary.Data storage self, uint _node, uint _sellPrice, uint _amount) returns (uint[4] _results) { require(self.stockBalanceOf[msg.sender][_node] >= _amount); uint[4] memory it; if (CommonLibrary.stockMaxBuyPrice(self, _sellPrice, _node) != _sellPrice - 1) { it[3] = self.stockBuyOrderPrices[_node].length; for (it[1] = 0; it[1] < it[3]; it[1]++) { uint _maxPrice = CommonLibrary.stockMaxBuyPrice(self, _sellPrice, _node); it[2] = self.stockBuyOrders[_node][_maxPrice].length; for (it[0] = 0; it[0] < it[2]; it[0]++) { if (_amount >= self.stockBuyOrders[_node][_maxPrice][0].amount) { //sell stocks for starcoins self.stockBalanceOf[msg.sender][_node] -= self.stockBuyOrders[_node][_maxPrice][0].amount;// subtracts the _amount from seller&#39;s balance self.stockBalanceOf[self.stockBuyOrders[_node][_maxPrice][0].client][_node] += self.stockBuyOrders[_node][_maxPrice][0].amount;// adds the _amount to buyer&#39;s balance //write stockOwnerInfo and stockOwners for dividends CommonLibrary.stockSaveOwnerInfo(self, _node, self.stockBuyOrders[_node][_maxPrice][0].amount, self.stockBuyOrders[_node][_maxPrice][0].client, msg.sender, _maxPrice); //transfer starcoins to seller self.balanceOf[msg.sender] += self.stockBuyOrders[_node][_maxPrice][0].amount*_maxPrice;// adds the amount to buyer&#39;s balance self.frozen[self.stockBuyOrders[_node][_maxPrice][0].client] -= self.stockBuyOrders[_node][_maxPrice][0].amount*_maxPrice;// subtracts amount from seller&#39;s frozen balance Transfer(self.stockBuyOrders[_node][_maxPrice][0].client, msg.sender, self.stockBuyOrders[_node][_maxPrice][0].amount*_maxPrice); //save the transaction StockTradeHistory(_node, block.timestamp, self.stockBuyOrders[_node][_maxPrice][0].client, msg.sender, _maxPrice, self.stockBuyOrders[_node][_maxPrice][0].amount, self.stockBuyOrders[_node][_maxPrice][0].orderId); _amount -= self.stockBuyOrders[_node][_maxPrice][0].amount; _results[0] += self.stockBuyOrders[_node][_maxPrice][0].amount; //delete stockBuyOrders[_node][_maxPrice][0] and move each element CommonLibrary.stockDeleteFirstOrder(self, _node, _maxPrice, false); if(_amount < 1) break; } else { //edit stockBuyOrders[_node][_maxPrice][0] self.stockBuyOrders[_node][_maxPrice][0].amount -= _amount; //sell stocks for starcoins self.stockBalanceOf[msg.sender][_node] -= _amount;// subtracts _amount from seller&#39;s balance self.stockBalanceOf[self.stockBuyOrders[_node][_maxPrice][0].client][_node] += _amount;// adds the _amount to buyer&#39;s balance //write stockOwnerInfo and stockOwners for dividends CommonLibrary.stockSaveOwnerInfo(self, _node, _amount, self.stockBuyOrders[_node][_maxPrice][0].client, msg.sender, _maxPrice); //transfer starcoins to seller self.balanceOf[msg.sender] += _amount*_maxPrice;// adds the _amount to buyer&#39;s balance self.frozen[self.stockBuyOrders[_node][_maxPrice][0].client] -= _amount*_maxPrice;// subtracts _amount from seller&#39;s frozen balance Transfer(self.stockBuyOrders[_node][_maxPrice][0].client, msg.sender, _amount*_maxPrice); //save the transaction StockTradeHistory(_node, block.timestamp, self.stockBuyOrders[_node][_maxPrice][0].client, msg.sender, _maxPrice, _amount, self.stockBuyOrders[_node][_maxPrice][0].orderId); _results[0] += _amount; _amount = 0; break; } } if (_amount < 1) { _results[3] = 1; break; } } } if (CommonLibrary.stockMaxBuyPrice(self, _sellPrice, _node) == _sellPrice - 1 && _amount >= 1) { //save new order _results[1] = _amount; self.stockOrdersId += 1; _results[2] = self.stockOrdersId; self.stockSellOrders[_node][_sellPrice].push(StarCoinLibrary.stockOrderInfo(block.timestamp, msg.sender, _results[1], _sellPrice, false, self.stockOrdersId, _node)); _results[3] = 1; //transfer stocks to the frozen stock balance self.stockFrozen[msg.sender][_node] += _amount; self.stockBalanceOf[msg.sender][_node] -= _amount; //Add _sellPrice to stockSellOrderPrices[_node][] it[0] = 99999; for (it[1] = 0; it[1] < self.stockSellOrderPrices[_node].length; it[1]++) { if (self.stockSellOrderPrices[_node][it[1]] == _sellPrice) it[0] = it[1]; } if (it[0] == 99999) self.stockSellOrderPrices[_node].push(_sellPrice); } } function stockCancelBuyOrder(StarCoinLibrary.Data storage self, uint _node, uint _thisOrderID, uint _price) public returns(bool) { for (uint iii = 0; iii < self.stockBuyOrders[_node][_price].length; iii++) { if (self.stockBuyOrders[_node][_price][iii].orderId == _thisOrderID) { require(msg.sender == self.stockBuyOrders[_node][_price][iii].client); //return starcoins from the buyer`s frozen balance self.frozen[msg.sender] -= self.stockBuyOrders[_node][_price][iii].amount*_price; self.balanceOf[msg.sender] += self.stockBuyOrders[_node][_price][iii].amount*_price; //delete stockBuyOrders[_node][_price][iii] and move each element for (uint ii = iii; ii < self.stockBuyOrders[_node][_price].length - 1; ii++) { self.stockBuyOrders[_node][_price][ii] = self.stockBuyOrders[_node][_price][ii + 1]; } delete self.stockBuyOrders[_node][_price][self.stockBuyOrders[_node][_price].length - 1]; self.stockBuyOrders[_node][_price].length--; break; } } //Delete _price from stockBuyOrderPrices[_node][] if it&#39;s the last order if (self.stockBuyOrders[_node][_price].length == 0) { uint _fromArg = 99999; for (iii = 0; iii < self.stockBuyOrderPrices[_node].length - 1; iii++) { if (self.stockBuyOrderPrices[_node][iii] == _price) { _fromArg = iii; } if (_fromArg != 99999 && iii >= _fromArg) self.stockBuyOrderPrices[_node][iii] = self.stockBuyOrderPrices[_node][iii + 1]; } delete self.stockBuyOrderPrices[_node][self.stockBuyOrderPrices[_node].length-1]; self.stockBuyOrderPrices[_node].length--; } return true; } function stockCancelSellOrder(StarCoinLibrary.Data storage self, uint _node, uint _thisOrderID, uint _price) public returns(bool) { for (uint iii = 0; iii < self.stockSellOrders[_node][_price].length; iii++) { if (self.stockSellOrders[_node][_price][iii].orderId == _thisOrderID) { require(msg.sender == self.stockSellOrders[_node][_price][iii].client); //return stocks from the seller`s frozen stock balance self.stockFrozen[msg.sender][_node] -= self.stockSellOrders[_node][_price][iii].amount; self.stockBalanceOf[msg.sender][_node] += self.stockSellOrders[_node][_price][iii].amount; //delete stockSellOrders[_node][_price][iii] and move each element for (uint ii = iii; ii < self.stockSellOrders[_node][_price].length - 1; ii++) { self.stockSellOrders[_node][_price][ii] = self.stockSellOrders[_node][_price][ii + 1]; } delete self.stockSellOrders[_node][_price][self.stockSellOrders[_node][_price].length - 1]; self.stockSellOrders[_node][_price].length--; break; } } //Delete _price from stockSellOrderPrices[_node][] if it&#39;s the last order if (self.stockSellOrders[_node][_price].length == 0) { uint _fromArg = 99999; for (iii = 0; iii < self.stockSellOrderPrices[_node].length - 1; iii++) { if (self.stockSellOrderPrices[_node][iii] == _price) { _fromArg = iii; } if (_fromArg != 99999 && iii >= _fromArg) self.stockSellOrderPrices[_node][iii] = self.stockSellOrderPrices[_node][iii + 1]; } delete self.stockSellOrderPrices[_node][self.stockSellOrderPrices[_node].length-1]; self.stockSellOrderPrices[_node].length--; } return true; } } library StarmidLibraryExtra { event Transfer(address indexed from, address indexed to, uint256 value); event StockTransfer(address indexed from, address indexed to, uint indexed node, uint256 value); event StockTradeHistory(uint node, uint date, address buyer, address seller, uint price, uint amount, uint orderId); event TradeHistory(uint date, address buyer, address seller, uint price, uint amount, uint orderId); function buyCertainOrder(StarCoinLibrary.Data storage self, uint _price, uint _thisOrderID) returns (bool) { uint _remainingValue = msg.value; for (uint8 iii = 0; iii < self.sellOrders[_price].length; iii++) { if (self.sellOrders[_price][iii].orderId == _thisOrderID) { uint _amount = _remainingValue/_price; require(_amount <= self.sellOrders[_price][iii].amount); if (_amount == self.sellOrders[_price][iii].amount) { //buy starcoins for ether self.balanceOf[msg.sender] += self.sellOrders[_price][iii].amount;// adds the amount to buyer&#39;s balance self.frozen[self.sellOrders[_price][iii].client] -= self.sellOrders[_price][iii].amount;// subtracts the amount from seller&#39;s frozen balance Transfer(self.sellOrders[_price][iii].client, msg.sender, self.sellOrders[_price][iii].amount); //transfer ether to seller self.pendingWithdrawals[self.sellOrders[_price][iii].client] += _price*self.sellOrders[_price][iii].amount; //save the transaction TradeHistory(block.timestamp, msg.sender, self.sellOrders[_price][iii].client, _price, self.sellOrders[_price][iii].amount, self.sellOrders[_price][iii].orderId); _remainingValue -= _price*self.sellOrders[_price][iii].amount; //delete sellOrders[_price][iii] and move each element for (uint ii = iii; ii < self.sellOrders[_price].length - 1; ii++) { self.sellOrders[_price][ii] = self.sellOrders[_price][ii + 1]; } delete self.sellOrders[_price][self.sellOrders[_price].length - 1]; self.sellOrders[_price].length--; //Delete _price from sellOrderPrices[] if it&#39;s the last order if (self.sellOrders[_price].length == 0) { uint fromArg = 99999; for (ii = 0; ii < self.sellOrderPrices.length - 1; ii++) { if (self.sellOrderPrices[ii] == _price) { fromArg = ii; } if (fromArg != 99999 && ii >= fromArg) self.sellOrderPrices[ii] = self.sellOrderPrices[ii + 1]; } delete self.sellOrderPrices[self.sellOrderPrices.length-1]; self.sellOrderPrices.length--; } return true; break; } else { //edit sellOrders[_price][iii] self.sellOrders[_price][iii].amount = self.sellOrders[_price][iii].amount - _amount; //buy starcoins for ether self.balanceOf[msg.sender] += _amount;// adds the _amount to buyer&#39;s balance self.frozen[self.sellOrders[_price][iii].client] -= _amount;// subtracts the _amount from seller&#39;s frozen balance Transfer(self.sellOrders[_price][iii].client, msg.sender, _amount); //save the transaction TradeHistory(block.timestamp, msg.sender, self.sellOrders[_price][iii].client, _price, _amount, self.sellOrders[_price][iii].orderId); //transfer ether to seller self.pendingWithdrawals[self.sellOrders[_price][iii].client] += _amount*_price; _remainingValue -= _amount*_price; return true; break; } } } self.pendingWithdrawals[msg.sender] += _remainingValue;//returns change to buyer } function sellCertainOrder(StarCoinLibrary.Data storage self, uint _amount, uint _price, uint _thisOrderID) returns (bool) { for (uint8 iii = 0; iii < self.buyOrders[_price].length; iii++) { if (self.buyOrders[_price][iii].orderId == _thisOrderID) { require(_amount <= self.buyOrders[_price][iii].amount && self.balanceOf[msg.sender] >= _amount); if (_amount == self.buyOrders[_price][iii].amount) { //sell starcoins for ether self.balanceOf[msg.sender] -= self.buyOrders[_price][iii].amount;// subtracts amount from seller&#39;s balance self.balanceOf[self.buyOrders[_price][iii].client] += self.buyOrders[_price][iii].amount;// adds the amount to buyer&#39;s balance Transfer(msg.sender, self.buyOrders[_price][iii].client, self.buyOrders[_price][iii].amount); //transfer ether to seller uint _amountTransfer = _price*self.buyOrders[_price][iii].amount; self.pendingWithdrawals[msg.sender] += _amountTransfer; //save the transaction TradeHistory(block.timestamp, self.buyOrders[_price][iii].client, msg.sender, _price, self.buyOrders[_price][iii].amount, self.buyOrders[_price][iii].orderId); _amount -= self.buyOrders[_price][iii].amount; //delete buyOrders[_price][iii] and move each element for (uint ii = iii; ii < self.buyOrders[_price].length - 1; ii++) { self.buyOrders[_price][ii] = self.buyOrders[_price][ii + 1]; } delete self.buyOrders[_price][self.buyOrders[_price].length - 1]; self.buyOrders[_price].length--; //Delete _price from buyOrderPrices[] if it&#39;s the last order if (self.buyOrders[_price].length == 0) { uint _fromArg = 99999; for (uint8 iiii = 0; iiii < self.buyOrderPrices.length - 1; iiii++) { if (self.buyOrderPrices[iiii] == _price) { _fromArg = iiii; } if (_fromArg != 99999 && iiii >= _fromArg) self.buyOrderPrices[iiii] = self.buyOrderPrices[iiii + 1]; } delete self.buyOrderPrices[self.buyOrderPrices.length-1]; self.buyOrderPrices.length--; } return true; break; } else { //edit buyOrders[_price][iii] self.buyOrders[_price][iii].amount = self.buyOrders[_price][iii].amount - _amount; //buy starcoins for ether self.balanceOf[msg.sender] -= _amount;// subtracts amount from seller&#39;s balance self.balanceOf[self.buyOrders[_price][iii].client] += _amount;// adds the amount to buyer&#39;s balance Transfer(msg.sender, self.buyOrders[_price][iii].client, _amount); //save the transaction TradeHistory(block.timestamp, self.buyOrders[_price][iii].client, msg.sender, _price, _amount, self.buyOrders[_price][iii].orderId); //transfer ether to seller self.pendingWithdrawals[msg.sender] += _price*_amount; return true; break; } } } } function stockBuyCertainOrder(StarCoinLibrary.Data storage self, uint _node, uint _price, uint _amount, uint _thisOrderID) returns (bool) { require(self.balanceOf[msg.sender] >= _price*_amount); for (uint8 iii = 0; iii < self.stockSellOrders[_node][_price].length; iii++) { if (self.stockSellOrders[_node][_price][iii].orderId == _thisOrderID) { require(_amount <= self.stockSellOrders[_node][_price][iii].amount); if (_amount == self.stockSellOrders[_node][_price][iii].amount) { //buy stocks for starcoins self.stockBalanceOf[msg.sender][_node] += self.stockSellOrders[_node][_price][iii].amount;// add the amount to buyer&#39;s balance self.stockFrozen[self.stockSellOrders[_node][_price][iii].client][_node] -= self.stockSellOrders[_node][_price][iii].amount;// subtracts amount from seller&#39;s frozen stock balance //write stockOwnerInfo and stockOwners for dividends CommonLibrary.stockSaveOwnerInfo(self, _node, self.stockSellOrders[_node][_price][iii].amount, msg.sender, self.stockSellOrders[_node][_price][iii].client, _price); //transfer starcoins to seller self.balanceOf[msg.sender] -= self.stockSellOrders[_node][_price][iii].amount*_price;// subtracts amount from buyer&#39;s balance self.balanceOf[self.stockSellOrders[_node][_price][iii].client] += self.stockSellOrders[_node][_price][iii].amount*_price;// adds the amount to seller&#39;s balance Transfer(self.stockSellOrders[_node][_price][iii].client, msg.sender, self.stockSellOrders[_node][_price][iii].amount*_price); //save the transaction into event StocksTradeHistory; StockTradeHistory(_node, block.timestamp, msg.sender, self.stockSellOrders[_node][_price][iii].client, _price, self.stockSellOrders[_node][_price][iii].amount, self.stockSellOrders[_node][_price][iii].orderId); _amount -= self.stockSellOrders[_node][_price][iii].amount; //delete stockSellOrders[_node][_price][iii] and move each element CommonLibrary.deleteStockSellOrder(self, iii, _node, _price); return true; break; } else { //edit stockSellOrders[_node][_price][iii] self.stockSellOrders[_node][_price][iii].amount -= _amount; //buy stocks for starcoins self.stockBalanceOf[msg.sender][_node] += _amount;// adds the amount to buyer&#39;s balance self.stockFrozen[self.stockSellOrders[_node][_price][iii].client][_node] -= _amount;// subtracts amount from seller&#39;s frozen stock balance //write stockOwnerInfo and stockOwners for dividends CommonLibrary.stockSaveOwnerInfo(self, _node, _amount, msg.sender, self.stockSellOrders[_node][_price][iii].client, _price); //transfer starcoins to seller self.balanceOf[msg.sender] -= _amount*_price;// subtracts amount from buyer&#39;s balance self.balanceOf[self.stockSellOrders[_node][_price][iii].client] += _amount*_price;// adds the amount to seller&#39;s balance Transfer(self.stockSellOrders[_node][_price][iii].client, msg.sender, _amount*_price); //save the transaction into event StocksTradeHistory; StockTradeHistory(_node, block.timestamp, msg.sender, self.stockSellOrders[_node][_price][iii].client, _price, _amount, self.stockSellOrders[_node][_price][iii].orderId); _amount = 0; return true; break; } } } } function stockSellCertainOrder(StarCoinLibrary.Data storage self, uint _node, uint _price, uint _amount, uint _thisOrderID) returns (bool results) { uint _remainingAmount = _amount; for (uint8 iii = 0; iii < self.stockBuyOrders[_node][_price].length; iii++) { if (self.stockBuyOrders[_node][_price][iii].orderId == _thisOrderID) { require(_amount <= self.stockBuyOrders[_node][_price][iii].amount && self.stockBalanceOf[msg.sender][_node] >= _amount); if (_remainingAmount == self.stockBuyOrders[_node][_price][iii].amount) { //sell stocks for starcoins self.stockBalanceOf[msg.sender][_node] -= self.stockBuyOrders[_node][_price][iii].amount;// subtracts amount from seller&#39;s balance self.stockBalanceOf[self.stockBuyOrders[_node][_price][iii].client][_node] += self.stockBuyOrders[_node][_price][iii].amount;// adds the amount to buyer&#39;s balance //write stockOwnerInfo and stockOwners for dividends CommonLibrary.stockSaveOwnerInfo(self, _node, self.stockBuyOrders[_node][_price][iii].amount, self.stockBuyOrders[_node][_price][iii].client, msg.sender, _price); //transfer starcoins to seller self.balanceOf[msg.sender] += self.stockBuyOrders[_node][_price][iii].amount*_price;// adds the amount to buyer&#39;s balance self.frozen[self.stockBuyOrders[_node][_price][iii].client] -= self.stockBuyOrders[_node][_price][iii].amount*_price;// subtracts amount from seller&#39;s frozen balance Transfer(self.stockBuyOrders[_node][_price][iii].client, msg.sender, self.stockBuyOrders[_node][_price][iii].amount*_price); //save the transaction StockTradeHistory(_node, block.timestamp, self.stockBuyOrders[_node][_price][iii].client, msg.sender, _price, self.stockBuyOrders[_node][_price][iii].amount, self.stockBuyOrders[_node][_price][iii].orderId); _amount -= self.stockBuyOrders[_node][_price][iii].amount; //delete stockBuyOrders[_node][_price][iii] and move each element CommonLibrary.deleteStockBuyOrder(self, iii, _node, _price); results = true; break; } else { //edit stockBuyOrders[_node][_price][0] self.stockBuyOrders[_node][_price][iii].amount -= _amount; //sell stocks for starcoins self.stockBalanceOf[msg.sender][_node] -= _amount;// subtracts amount from seller&#39;s balance self.stockBalanceOf[self.stockBuyOrders[_node][_price][iii].client][_node] += _amount;// adds the amount to buyer&#39;s balance //write stockOwnerInfo and stockOwners for dividends CommonLibrary.stockSaveOwnerInfo(self, _node, _amount, self.stockBuyOrders[_node][_price][iii].client, msg.sender, _price); //transfer starcoins to seller self.balanceOf[msg.sender] += _amount*_price;// adds the amount to buyer&#39;s balance self.frozen[self.stockBuyOrders[_node][_price][iii].client] -= _amount*_price;// subtracts amount from seller&#39;s frozen balance Transfer(self.stockBuyOrders[_node][_price][iii].client, msg.sender, _amount*_price); //save the transaction StockTradeHistory(_node, block.timestamp, self.stockBuyOrders[_node][_price][iii].client, msg.sender, _price, _amount, self.stockBuyOrders[_node][_price][iii].orderId); _amount = 0; results = true; break; } } } } } contract Nodes { address public owner; CommonLibrary.Data public vars; mapping (address => string) public confirmationNodes; uint confirmNodeId; uint40 changePercentId; uint40 pushNodeGroupId; uint40 deleteNodeGroupId; event NewNode( uint256 id, string nodeName, uint8 producersPercent, address producer, uint date ); event OwnerNotation(uint256 id, uint date, string newNotation); event NewNodeGroup(uint16 id, string newNodeGroup); event AddNodeAddress(uint id, uint nodeID, address nodeAdress); event EditNode( uint nodeID, address nodeAdress, address newProducer, uint8 newProducersPercent, bool starmidConfirmed ); event ConfirmNode(uint id, uint nodeID); event OutsourceConfirmNode(uint nodeID, address confirmationNode); event ChangePercent(uint id, uint nodeId, uint producersPercent); event PushNodeGroup(uint id, uint nodeId, uint newNodeGroup); event DeleteNodeGroup(uint id, uint nodeId, uint deleteNodeGroup); function Nodes() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } //-----------------------------------------------------Nodes--------------------------------------------------------------- function changeOwner(string _changeOwnerPassword, address _newOwnerAddress) onlyOwner returns(bool) { //One-time tool for emergency owner change if (keccak256(_changeOwnerPassword) == 0xe17a112b6fc12fc80c9b241de72da0d27ce7e244100f3c4e9358162a11bed629) { owner = _newOwnerAddress; return true; } else return false; } function addOwnerNotations(string _newNotation) onlyOwner { uint date = block.timestamp; vars.ownerNotationId += 1; OwnerNotation(vars.ownerNotationId, date, _newNotation); } function addConfirmationNode(string _newConfirmationNode) public returns(bool) { confirmationNodes[msg.sender] = _newConfirmationNode; return true; } function addNodeGroup(string _newNodeGroup) onlyOwner returns(uint16 _id) { bool result; (result, _id) = CommonLibrary.addNodeGroup(vars, _newNodeGroup); require(result); NewNodeGroup(_id, _newNodeGroup); } function addNode(string _newNode, uint8 _producersPercent) returns(bool) { bool result; uint _id; (result, _id) = CommonLibrary.addNode(vars, _newNode, _producersPercent); require(result); NewNode(_id, _newNode, _producersPercent, msg.sender, block.timestamp); return true; } function editNode( uint _nodeID, address _nodeAddress, bool _isNewProducer, address _newProducer, uint8 _newProducersPercent, bool _starmidConfirmed ) onlyOwner returns(bool) { bool x = CommonLibrary.editNode(vars, _nodeID, _nodeAddress,_isNewProducer, _newProducer, _newProducersPercent, _starmidConfirmed); require(x); EditNode(_nodeID, _nodeAddress, _newProducer, _newProducersPercent, _starmidConfirmed); return true; } function addNodeAddress(uint _nodeID, address _nodeAddress) public returns(bool) { bool _result; uint _id; (_result, _id) = CommonLibrary.addNodeAddress(vars, _nodeID, _nodeAddress); require(_result); AddNodeAddress(_id, _nodeID, _nodeAddress); return true; } function pushNodeGroup(uint _nodeID, uint16 _newNodeGroup) public returns(bool) { require(msg.sender == vars.nodes[_nodeID].node); vars.nodes[_nodeID].nodeGroup.push(_newNodeGroup); pushNodeGroupId += 1; PushNodeGroup(pushNodeGroupId, _nodeID, _newNodeGroup); return true; } function deleteNodeGroup(uint _nodeID, uint16 _deleteNodeGroup) public returns(bool) { require(msg.sender == vars.nodes[_nodeID].node); for(uint16 i = 0; i < vars.nodes[_nodeID].nodeGroup.length; i++) { if(_deleteNodeGroup == vars.nodes[_nodeID].nodeGroup[i]) { for(uint16 ii = i; ii < vars.nodes[_nodeID].nodeGroup.length - 1; ii++) vars.nodes[_nodeID].nodeGroup[ii] = vars.nodes[_nodeID].nodeGroup[ii + 1]; delete vars.nodes[_nodeID].nodeGroup[vars.nodes[_nodeID].nodeGroup.length - 1]; vars.nodes[_nodeID].nodeGroup.length--; break; } } deleteNodeGroupId += 1; DeleteNodeGroup(deleteNodeGroupId, _nodeID, _deleteNodeGroup); return true; } function confirmNode(uint _nodeID) onlyOwner returns(bool) { vars.nodes[_nodeID].starmidConfirmed = true; confirmNodeId += 1; ConfirmNode(confirmNodeId, _nodeID); return true; } function outsourceConfirmNode(uint _nodeID) public returns(bool) { vars.nodes[_nodeID].outsourceConfirmed.push(msg.sender); OutsourceConfirmNode(_nodeID, msg.sender); return true; } function changePercent(uint _nodeId, uint8 _producersPercent) public returns(bool){ if(msg.sender == vars.nodes[_nodeId].producer && vars.nodes[_nodeId].node == 0x0000000000000000000000000000000000000000) { vars.nodes[_nodeId].producersPercent = _producersPercent; changePercentId += 1; ChangePercent(changePercentId, _nodeId, _producersPercent); return true; } } function getNodeInfo(uint _nodeID) constant public returns( address _producer, address _node, uint _date, bool _starmidConfirmed, string _nodeName, address[] _outsourceConfirmed, uint16[] _nodeGroup, uint _producersPercent ) { _producer = vars.nodes[_nodeID].producer; _node = vars.nodes[_nodeID].node; _date = vars.nodes[_nodeID].date; _starmidConfirmed = vars.nodes[_nodeID].starmidConfirmed; _nodeName = vars.nodes[_nodeID].nodeName; _outsourceConfirmed = vars.nodes[_nodeID].outsourceConfirmed; _nodeGroup = vars.nodes[_nodeID].nodeGroup; _producersPercent = vars.nodes[_nodeID].producersPercent; } } contract Starmid { address public owner; Nodes public nodesVars; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; StarCoinLibrary.Data public sCVars; event Transfer(address indexed from, address indexed to, uint256 value); event BuyOrder(address indexed from, uint orderId, uint buyPrice); event SellOrder(address indexed from, uint orderId, uint sellPrice); event CancelBuyOrder(address indexed from, uint indexed orderId, uint price); event CancelSellOrder(address indexed from, uint indexed orderId, uint price); event TradeHistory(uint date, address buyer, address seller, uint price, uint amount, uint orderId); //----------------------------------------------------Starmid exchange event StockTransfer(address indexed from, address indexed to, uint indexed node, uint256 value); event StockBuyOrder(uint node, uint buyPrice); event StockSellOrder(uint node, uint sellPrice); event StockCancelBuyOrder(uint node, uint price); event StockCancelSellOrder(uint node, uint price); event StockTradeHistory(uint node, uint date, address buyer, address seller, uint price, uint amount, uint orderId); function Starmid(uint256 initialSupply, string tokenName, string tokenSymbol, uint8 decimalUnits) public { owner = 0x378B9eea7ab9C15d9818EAdDe1156A079Cd02ba8; totalSupply = initialSupply; sCVars.balanceOf[msg.sender] = 5000000000; sCVars.balanceOf[0x378B9eea7ab9C15d9818EAdDe1156A079Cd02ba8] = initialSupply - 5000000000; name = tokenName; symbol = tokenSymbol; decimals = decimalUnits; sCVars.lastMint = block.timestamp; sCVars.emissionLimits[1] = 500000; sCVars.emissionLimits[2] = 500000; sCVars.emissionLimits[3] = 500000; sCVars.emissionLimits[4] = 500000; sCVars.emissionLimits[5] = 500000; sCVars.emissionLimits[6] = 500000; } modifier onlyOwner { require(msg.sender == owner); _; } //-----------------------------------------------------StarCoin Exchange------------------------------------------------------ function getWithdrawal() constant public returns(uint _amount) { _amount = sCVars.pendingWithdrawals[msg.sender]; } function withdraw() public returns(bool _result, uint _amount) { _amount = sCVars.pendingWithdrawals[msg.sender]; sCVars.pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(_amount); _result = true; } function changeOwner(string _changeOwnerPassword, address _newOwnerAddress) onlyOwner returns(bool) { //One-time tool for emergency owner change if (keccak256(_changeOwnerPassword) == 0xe17a112b6fc12fc80c9b241de72da0d27ce7e244100f3c4e9358162a11bed629) { owner = _newOwnerAddress; return true; } else return false; } function setNodesVars(address _addr) public { require(msg.sender == 0xfCbA69eF1D63b0A4CcD9ceCeA429157bA48d6a9c); nodesVars = Nodes(_addr); } function getBalance(address _address) constant public returns(uint _balance) { _balance = sCVars.balanceOf[_address]; } function getBuyOrderPrices() constant public returns(uint[] _prices) { _prices = sCVars.buyOrderPrices; } function getSellOrderPrices() constant public returns(uint[] _prices) { _prices = sCVars.sellOrderPrices; } function getOrderInfo(bool _isBuyOrder, uint _price, uint _number) constant public returns(address _address, uint _amount, uint _orderId) { if(_isBuyOrder == true) { _address = sCVars.buyOrders[_price][_number].client; _amount = sCVars.buyOrders[_price][_number].amount; _orderId = sCVars.buyOrders[_price][_number].orderId; } else { _address = sCVars.sellOrders[_price][_number].client; _amount = sCVars.sellOrders[_price][_number].amount; _orderId = sCVars.sellOrders[_price][_number].orderId; } } function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function mint() public onlyOwner returns(uint _mintedAmount) { //Minted amount does not exceed 8,5% per annum. Thus, minting does not greatly increase the total supply //and does not cause significant inflation and depreciation of the starcoin. _mintedAmount = (block.timestamp - sCVars.lastMint)*totalSupply/(12*31536000);//31536000 seconds in year sCVars.balanceOf[msg.sender] += _mintedAmount; totalSupply += _mintedAmount; sCVars.lastMint = block.timestamp; Transfer(0, this, _mintedAmount); Transfer(this, msg.sender, _mintedAmount); } function buyOrder(uint256 _buyPrice) payable public returns (uint[4] _results) { require(_buyPrice > 0 && msg.value > 0); _results = StarCoinLibrary.buyOrder(sCVars, _buyPrice); require(_results[3] == 1); BuyOrder(msg.sender, _results[2], _buyPrice); } function sellOrder(uint256 _sellPrice, uint _amount) public returns (uint[4] _results) { require(_sellPrice > 0 && _amount > 0); _results = StarCoinLibrary.sellOrder(sCVars, _sellPrice, _amount); require(_results[3] == 1); SellOrder(msg.sender, _results[2], _sellPrice); } function cancelBuyOrder(uint _thisOrderID, uint _price) public { require(StarCoinLibrary.cancelBuyOrder(sCVars, _thisOrderID, _price)); CancelBuyOrder(msg.sender, _thisOrderID, _price); } function cancelSellOrder(uint _thisOrderID, uint _price) public { require(StarCoinLibrary.cancelSellOrder(sCVars, _thisOrderID, _price)); CancelSellOrder(msg.sender, _thisOrderID, _price); } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(sCVars.balanceOf[_from] >= _value && sCVars.balanceOf[_to] + _value > sCVars.balanceOf[_to]); sCVars.balanceOf[_from] -= _value; sCVars.balanceOf[_to] += _value; Transfer(_from, _to, _value); } function buyCertainOrder(uint _price, uint _thisOrderID) payable public returns (bool _results) { _results = StarmidLibraryExtra.buyCertainOrder(sCVars, _price, _thisOrderID); require(_results && msg.value > 0); BuyOrder(msg.sender, _thisOrderID, _price); } function sellCertainOrder(uint _amount, uint _price, uint _thisOrderID) public returns (bool _results) { _results = StarmidLibraryExtra.sellCertainOrder(sCVars, _amount, _price, _thisOrderID); require(_results && _amount > 0); SellOrder(msg.sender, _thisOrderID, _price); } //------------------------------------------------------Starmid exchange---------------------------------------------------------- function stockTransfer(address _to, uint _node, uint _value) public { require(_to != 0x0); require(sCVars.stockBalanceOf[msg.sender][_node] >= _value && sCVars.stockBalanceOf[_to][_node] + _value > sCVars.stockBalanceOf[_to][_node]); var (x,y,) = nodesVars.getNodeInfo(_node); require(msg.sender != y);//nodeOwner cannot transfer his stocks, only sell sCVars.stockBalanceOf[msg.sender][_node] -= _value; sCVars.stockBalanceOf[_to][_node] += _value; StockTransfer(msg.sender, _to, _node, _value); } function getEmission(uint _node) constant public returns(uint _emissionNumber, uint _emissionDate, uint _emissionAmount) { _emissionNumber = sCVars.emissions[_node].emissionNumber; _emissionDate = sCVars.emissions[_node].date; _emissionAmount = sCVars.emissionLimits[_emissionNumber]; } function emission(uint _node) public returns(bool _result, uint _emissionNumber, uint _emissionAmount, uint _producersPercent) { var (x,y,,,,,,z,) = nodesVars.getNodeInfo(_node); address _nodeOwner = y; address _nodeProducer = x; _producersPercent = z; require(msg.sender == _nodeOwner || msg.sender == _nodeProducer); uint allStocks; for (uint i = 1; i <= sCVars.emissions[_node].emissionNumber; i++) { allStocks += sCVars.emissionLimits[i]; } if (_nodeOwner !=0x0000000000000000000000000000000000000000 && block.timestamp > sCVars.emissions[_node].date + 5184000 && sCVars.stockBalanceOf[_nodeOwner][_node] <= allStocks/2 ) { _emissionNumber = sCVars.emissions[_node].emissionNumber + 1; sCVars.stockBalanceOf[_nodeOwner][_node] += sCVars.emissionLimits[_emissionNumber]*(100 - _producersPercent)/100; //save stockOwnerInfo for _nodeOwner uint thisNode = 0; for (i = 0; i < sCVars.stockOwnerInfo[_nodeOwner].nodes.length; i++) { if (sCVars.stockOwnerInfo[_nodeOwner].nodes[i] == _node) thisNode = 1; } if (thisNode == 0) sCVars.stockOwnerInfo[_nodeOwner].nodes.push(_node); sCVars.stockBalanceOf[_nodeProducer][_node] += sCVars.emissionLimits[_emissionNumber]*_producersPercent/100; //save stockOwnerInfo for _nodeProducer thisNode = 0; for (i = 0; i < sCVars.stockOwnerInfo[_nodeProducer].nodes.length; i++) { if (sCVars.stockOwnerInfo[_nodeProducer].nodes[i] == _node) thisNode = 1; } if (thisNode == 0) sCVars.stockOwnerInfo[_nodeProducer].nodes.push(_node); sCVars.emissions[_node].date = block.timestamp; sCVars.emissions[_node].emissionNumber = _emissionNumber; _emissionAmount = sCVars.emissionLimits[_emissionNumber]; _result = true; } else _result = false; } function getStockOwnerInfo(address _address) constant public returns(uint[] _nodes) { _nodes = sCVars.stockOwnerInfo[_address].nodes; } function getStockBalance(address _address, uint _node) constant public returns(uint _balance) { _balance = sCVars.stockBalanceOf[_address][_node]; } function getWithFrozenStockBalance(address _address, uint _node) constant public returns(uint _balance) { _balance = sCVars.stockBalanceOf[_address][_node] + sCVars.stockFrozen[_address][_node]; } function getStockOrderInfo(bool _isBuyOrder, uint _node, uint _price, uint _number) constant public returns(address _address, uint _amount, uint _orderId) { if(_isBuyOrder == true) { _address = sCVars.stockBuyOrders[_node][_price][_number].client; _amount = sCVars.stockBuyOrders[_node][_price][_number].amount; _orderId = sCVars.stockBuyOrders[_node][_price][_number].orderId; } else { _address = sCVars.stockSellOrders[_node][_price][_number].client; _amount = sCVars.stockSellOrders[_node][_price][_number].amount; _orderId = sCVars.stockSellOrders[_node][_price][_number].orderId; } } function getStockBuyOrderPrices(uint _node) constant public returns(uint[] _prices) { _prices = sCVars.stockBuyOrderPrices[_node]; } function getStockSellOrderPrices(uint _node) constant public returns(uint[] _prices) { _prices = sCVars.stockSellOrderPrices[_node]; } function stockBuyOrder(uint _node, uint256 _buyPrice, uint _amount) public returns (uint[4] _results) { require(_node > 0 && _buyPrice > 0 && _amount > 0); _results = StarmidLibrary.stockBuyOrder(sCVars, _node, _buyPrice, _amount); require(_results[3] == 1); StockBuyOrder(_node, _buyPrice); } function stockSellOrder(uint _node, uint256 _sellPrice, uint _amount) public returns (uint[4] _results) { require(_node > 0 && _sellPrice > 0 && _amount > 0); _results = StarmidLibrary.stockSellOrder(sCVars, _node, _sellPrice, _amount); require(_results[3] == 1); StockSellOrder(_node, _sellPrice); } function stockCancelBuyOrder(uint _node, uint _thisOrderID, uint _price) public { require(StarmidLibrary.stockCancelBuyOrder(sCVars, _node, _thisOrderID, _price)); StockCancelBuyOrder(_node, _price); } function stockCancelSellOrder(uint _node, uint _thisOrderID, uint _price) public { require(StarmidLibrary.stockCancelSellOrder(sCVars, _node, _thisOrderID, _price)); StockCancelSellOrder(_node, _price); } function getLastDividends(uint _node) public constant returns (uint _lastDividents, uint _dividends) { uint stockAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount; uint sumAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount; if(sumAmount > 0) { uint stockAverageBuyPrice = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumPriceAmount/sumAmount; uint dividendsBase = stockAmount*stockAverageBuyPrice; _lastDividents = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumDateAmount/sumAmount; if(_lastDividents > 0)_dividends = (block.timestamp - _lastDividents)*dividendsBase/(10*31536000); else _dividends = 0; } } //--------------------------------Dividends (10% to stock owner, 2,5% to node owner per annum)------------------------------------ function dividends(uint _node) public returns (bool _result, uint _dividends) { var (x,y,) = nodesVars.getNodeInfo(_node); uint _stockAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount; uint _sumAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount; if(_sumAmount > 0) { uint _stockAverageBuyPrice = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumPriceAmount/_sumAmount; uint _dividendsBase = _stockAmount*_stockAverageBuyPrice; uint _averageDate = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumDateAmount/_sumAmount; //Stock owner`s dividends uint _div = (block.timestamp - _averageDate)*_dividendsBase/(10*31536000);//31536000 seconds in year sCVars.balanceOf[msg.sender] += _div; //Node owner`s dividends uint _nodeDividends = (block.timestamp - _averageDate)*_dividendsBase/(40*31536000);//31536000 seconds in year sCVars.balanceOf[y] += _nodeDividends; sCVars.StockOwnersBuyPrice[msg.sender][_node].sumDateAmount = block.timestamp*_stockAmount;//set new average dividends date totalSupply += _div + _div/4; _dividends = _div + _div/4; Transfer(this, msg.sender, _div); Transfer(this, y, _div/4); _result = true; } } function stockBuyCertainOrder(uint _node, uint _price, uint _amount, uint _thisOrderID) payable public returns (bool _results) { _results = StarmidLibraryExtra.stockBuyCertainOrder(sCVars, _node, _price, _amount, _thisOrderID); require(_results && _node > 0 && _amount > 0); StockBuyOrder(_node, _price); } function stockSellCertainOrder(uint _node, uint _price, uint _amount, uint _thisOrderID) public returns (bool _results) { _results = StarmidLibraryExtra.stockSellCertainOrder(sCVars, _node, _price, _amount, _thisOrderID); require(_results && _node > 0 && _amount > 0); StockSellOrder(_node, _price); } }
----------------------------------------------------Starmid exchange
contract Starmid { address public owner; Nodes public nodesVars; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; StarCoinLibrary.Data public sCVars; event Transfer(address indexed from, address indexed to, uint256 value); event BuyOrder(address indexed from, uint orderId, uint buyPrice); event SellOrder(address indexed from, uint orderId, uint sellPrice); event CancelBuyOrder(address indexed from, uint indexed orderId, uint price); event CancelSellOrder(address indexed from, uint indexed orderId, uint price); event TradeHistory(uint date, address buyer, address seller, uint price, uint amount, uint orderId); event StockTransfer(address indexed from, address indexed to, uint indexed node, uint256 value); event StockBuyOrder(uint node, uint buyPrice); event StockSellOrder(uint node, uint sellPrice); event StockCancelBuyOrder(uint node, uint price); event StockCancelSellOrder(uint node, uint price); event StockTradeHistory(uint node, uint date, address buyer, address seller, uint price, uint amount, uint orderId); function Starmid(uint256 initialSupply, string tokenName, string tokenSymbol, uint8 decimalUnits) public { owner = 0x378B9eea7ab9C15d9818EAdDe1156A079Cd02ba8; totalSupply = initialSupply; sCVars.balanceOf[msg.sender] = 5000000000; sCVars.balanceOf[0x378B9eea7ab9C15d9818EAdDe1156A079Cd02ba8] = initialSupply - 5000000000; name = tokenName; symbol = tokenSymbol; decimals = decimalUnits; sCVars.lastMint = block.timestamp; sCVars.emissionLimits[1] = 500000; sCVars.emissionLimits[2] = 500000; sCVars.emissionLimits[3] = 500000; sCVars.emissionLimits[4] = 500000; sCVars.emissionLimits[5] = 500000; sCVars.emissionLimits[6] = 500000; } modifier onlyOwner { require(msg.sender == owner); _; } function getWithdrawal() constant public returns(uint _amount) { _amount = sCVars.pendingWithdrawals[msg.sender]; } function withdraw() public returns(bool _result, uint _amount) { _amount = sCVars.pendingWithdrawals[msg.sender]; sCVars.pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(_amount); _result = true; } function changeOwner(string _changeOwnerPassword, address _newOwnerAddress) onlyOwner returns(bool) { if (keccak256(_changeOwnerPassword) == 0xe17a112b6fc12fc80c9b241de72da0d27ce7e244100f3c4e9358162a11bed629) { owner = _newOwnerAddress; return true; } else return false; } function changeOwner(string _changeOwnerPassword, address _newOwnerAddress) onlyOwner returns(bool) { if (keccak256(_changeOwnerPassword) == 0xe17a112b6fc12fc80c9b241de72da0d27ce7e244100f3c4e9358162a11bed629) { owner = _newOwnerAddress; return true; } else return false; } function setNodesVars(address _addr) public { require(msg.sender == 0xfCbA69eF1D63b0A4CcD9ceCeA429157bA48d6a9c); nodesVars = Nodes(_addr); } function getBalance(address _address) constant public returns(uint _balance) { _balance = sCVars.balanceOf[_address]; } function getBuyOrderPrices() constant public returns(uint[] _prices) { _prices = sCVars.buyOrderPrices; } function getSellOrderPrices() constant public returns(uint[] _prices) { _prices = sCVars.sellOrderPrices; } function getOrderInfo(bool _isBuyOrder, uint _price, uint _number) constant public returns(address _address, uint _amount, uint _orderId) { if(_isBuyOrder == true) { _address = sCVars.buyOrders[_price][_number].client; _amount = sCVars.buyOrders[_price][_number].amount; _orderId = sCVars.buyOrders[_price][_number].orderId; } else { _address = sCVars.sellOrders[_price][_number].client; _amount = sCVars.sellOrders[_price][_number].amount; _orderId = sCVars.sellOrders[_price][_number].orderId; } } function getOrderInfo(bool _isBuyOrder, uint _price, uint _number) constant public returns(address _address, uint _amount, uint _orderId) { if(_isBuyOrder == true) { _address = sCVars.buyOrders[_price][_number].client; _amount = sCVars.buyOrders[_price][_number].amount; _orderId = sCVars.buyOrders[_price][_number].orderId; } else { _address = sCVars.sellOrders[_price][_number].client; _amount = sCVars.sellOrders[_price][_number].amount; _orderId = sCVars.sellOrders[_price][_number].orderId; } } function getOrderInfo(bool _isBuyOrder, uint _price, uint _number) constant public returns(address _address, uint _amount, uint _orderId) { if(_isBuyOrder == true) { _address = sCVars.buyOrders[_price][_number].client; _amount = sCVars.buyOrders[_price][_number].amount; _orderId = sCVars.buyOrders[_price][_number].orderId; } else { _address = sCVars.sellOrders[_price][_number].client; _amount = sCVars.sellOrders[_price][_number].amount; _orderId = sCVars.sellOrders[_price][_number].orderId; } } function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function mint() public onlyOwner returns(uint _mintedAmount) { sCVars.balanceOf[msg.sender] += _mintedAmount; totalSupply += _mintedAmount; sCVars.lastMint = block.timestamp; Transfer(0, this, _mintedAmount); Transfer(this, msg.sender, _mintedAmount); } function buyOrder(uint256 _buyPrice) payable public returns (uint[4] _results) { require(_buyPrice > 0 && msg.value > 0); _results = StarCoinLibrary.buyOrder(sCVars, _buyPrice); require(_results[3] == 1); BuyOrder(msg.sender, _results[2], _buyPrice); } function sellOrder(uint256 _sellPrice, uint _amount) public returns (uint[4] _results) { require(_sellPrice > 0 && _amount > 0); _results = StarCoinLibrary.sellOrder(sCVars, _sellPrice, _amount); require(_results[3] == 1); SellOrder(msg.sender, _results[2], _sellPrice); } function cancelBuyOrder(uint _thisOrderID, uint _price) public { require(StarCoinLibrary.cancelBuyOrder(sCVars, _thisOrderID, _price)); CancelBuyOrder(msg.sender, _thisOrderID, _price); } function cancelSellOrder(uint _thisOrderID, uint _price) public { require(StarCoinLibrary.cancelSellOrder(sCVars, _thisOrderID, _price)); CancelSellOrder(msg.sender, _thisOrderID, _price); } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(sCVars.balanceOf[_from] >= _value && sCVars.balanceOf[_to] + _value > sCVars.balanceOf[_to]); sCVars.balanceOf[_from] -= _value; sCVars.balanceOf[_to] += _value; Transfer(_from, _to, _value); } function buyCertainOrder(uint _price, uint _thisOrderID) payable public returns (bool _results) { _results = StarmidLibraryExtra.buyCertainOrder(sCVars, _price, _thisOrderID); require(_results && msg.value > 0); BuyOrder(msg.sender, _thisOrderID, _price); } function sellCertainOrder(uint _amount, uint _price, uint _thisOrderID) public returns (bool _results) { _results = StarmidLibraryExtra.sellCertainOrder(sCVars, _amount, _price, _thisOrderID); require(_results && _amount > 0); SellOrder(msg.sender, _thisOrderID, _price); } function stockTransfer(address _to, uint _node, uint _value) public { require(_to != 0x0); require(sCVars.stockBalanceOf[msg.sender][_node] >= _value && sCVars.stockBalanceOf[_to][_node] + _value > sCVars.stockBalanceOf[_to][_node]); var (x,y,) = nodesVars.getNodeInfo(_node); sCVars.stockBalanceOf[msg.sender][_node] -= _value; sCVars.stockBalanceOf[_to][_node] += _value; StockTransfer(msg.sender, _to, _node, _value); } function getEmission(uint _node) constant public returns(uint _emissionNumber, uint _emissionDate, uint _emissionAmount) { _emissionNumber = sCVars.emissions[_node].emissionNumber; _emissionDate = sCVars.emissions[_node].date; _emissionAmount = sCVars.emissionLimits[_emissionNumber]; } function emission(uint _node) public returns(bool _result, uint _emissionNumber, uint _emissionAmount, uint _producersPercent) { var (x,y,,,,,,z,) = nodesVars.getNodeInfo(_node); address _nodeOwner = y; address _nodeProducer = x; _producersPercent = z; require(msg.sender == _nodeOwner || msg.sender == _nodeProducer); uint allStocks; for (uint i = 1; i <= sCVars.emissions[_node].emissionNumber; i++) { allStocks += sCVars.emissionLimits[i]; } if (_nodeOwner !=0x0000000000000000000000000000000000000000 && block.timestamp > sCVars.emissions[_node].date + 5184000 && sCVars.stockBalanceOf[_nodeOwner][_node] <= allStocks/2 ) { _emissionNumber = sCVars.emissions[_node].emissionNumber + 1; sCVars.stockBalanceOf[_nodeOwner][_node] += sCVars.emissionLimits[_emissionNumber]*(100 - _producersPercent)/100; uint thisNode = 0; for (i = 0; i < sCVars.stockOwnerInfo[_nodeOwner].nodes.length; i++) { if (sCVars.stockOwnerInfo[_nodeOwner].nodes[i] == _node) thisNode = 1; } if (thisNode == 0) sCVars.stockOwnerInfo[_nodeOwner].nodes.push(_node); sCVars.stockBalanceOf[_nodeProducer][_node] += sCVars.emissionLimits[_emissionNumber]*_producersPercent/100; for (i = 0; i < sCVars.stockOwnerInfo[_nodeProducer].nodes.length; i++) { if (sCVars.stockOwnerInfo[_nodeProducer].nodes[i] == _node) thisNode = 1; } if (thisNode == 0) sCVars.stockOwnerInfo[_nodeProducer].nodes.push(_node); sCVars.emissions[_node].date = block.timestamp; sCVars.emissions[_node].emissionNumber = _emissionNumber; _emissionAmount = sCVars.emissionLimits[_emissionNumber]; _result = true; } else _result = false; } function emission(uint _node) public returns(bool _result, uint _emissionNumber, uint _emissionAmount, uint _producersPercent) { var (x,y,,,,,,z,) = nodesVars.getNodeInfo(_node); address _nodeOwner = y; address _nodeProducer = x; _producersPercent = z; require(msg.sender == _nodeOwner || msg.sender == _nodeProducer); uint allStocks; for (uint i = 1; i <= sCVars.emissions[_node].emissionNumber; i++) { allStocks += sCVars.emissionLimits[i]; } if (_nodeOwner !=0x0000000000000000000000000000000000000000 && block.timestamp > sCVars.emissions[_node].date + 5184000 && sCVars.stockBalanceOf[_nodeOwner][_node] <= allStocks/2 ) { _emissionNumber = sCVars.emissions[_node].emissionNumber + 1; sCVars.stockBalanceOf[_nodeOwner][_node] += sCVars.emissionLimits[_emissionNumber]*(100 - _producersPercent)/100; uint thisNode = 0; for (i = 0; i < sCVars.stockOwnerInfo[_nodeOwner].nodes.length; i++) { if (sCVars.stockOwnerInfo[_nodeOwner].nodes[i] == _node) thisNode = 1; } if (thisNode == 0) sCVars.stockOwnerInfo[_nodeOwner].nodes.push(_node); sCVars.stockBalanceOf[_nodeProducer][_node] += sCVars.emissionLimits[_emissionNumber]*_producersPercent/100; for (i = 0; i < sCVars.stockOwnerInfo[_nodeProducer].nodes.length; i++) { if (sCVars.stockOwnerInfo[_nodeProducer].nodes[i] == _node) thisNode = 1; } if (thisNode == 0) sCVars.stockOwnerInfo[_nodeProducer].nodes.push(_node); sCVars.emissions[_node].date = block.timestamp; sCVars.emissions[_node].emissionNumber = _emissionNumber; _emissionAmount = sCVars.emissionLimits[_emissionNumber]; _result = true; } else _result = false; } function emission(uint _node) public returns(bool _result, uint _emissionNumber, uint _emissionAmount, uint _producersPercent) { var (x,y,,,,,,z,) = nodesVars.getNodeInfo(_node); address _nodeOwner = y; address _nodeProducer = x; _producersPercent = z; require(msg.sender == _nodeOwner || msg.sender == _nodeProducer); uint allStocks; for (uint i = 1; i <= sCVars.emissions[_node].emissionNumber; i++) { allStocks += sCVars.emissionLimits[i]; } if (_nodeOwner !=0x0000000000000000000000000000000000000000 && block.timestamp > sCVars.emissions[_node].date + 5184000 && sCVars.stockBalanceOf[_nodeOwner][_node] <= allStocks/2 ) { _emissionNumber = sCVars.emissions[_node].emissionNumber + 1; sCVars.stockBalanceOf[_nodeOwner][_node] += sCVars.emissionLimits[_emissionNumber]*(100 - _producersPercent)/100; uint thisNode = 0; for (i = 0; i < sCVars.stockOwnerInfo[_nodeOwner].nodes.length; i++) { if (sCVars.stockOwnerInfo[_nodeOwner].nodes[i] == _node) thisNode = 1; } if (thisNode == 0) sCVars.stockOwnerInfo[_nodeOwner].nodes.push(_node); sCVars.stockBalanceOf[_nodeProducer][_node] += sCVars.emissionLimits[_emissionNumber]*_producersPercent/100; for (i = 0; i < sCVars.stockOwnerInfo[_nodeProducer].nodes.length; i++) { if (sCVars.stockOwnerInfo[_nodeProducer].nodes[i] == _node) thisNode = 1; } if (thisNode == 0) sCVars.stockOwnerInfo[_nodeProducer].nodes.push(_node); sCVars.emissions[_node].date = block.timestamp; sCVars.emissions[_node].emissionNumber = _emissionNumber; _emissionAmount = sCVars.emissionLimits[_emissionNumber]; _result = true; } else _result = false; } function emission(uint _node) public returns(bool _result, uint _emissionNumber, uint _emissionAmount, uint _producersPercent) { var (x,y,,,,,,z,) = nodesVars.getNodeInfo(_node); address _nodeOwner = y; address _nodeProducer = x; _producersPercent = z; require(msg.sender == _nodeOwner || msg.sender == _nodeProducer); uint allStocks; for (uint i = 1; i <= sCVars.emissions[_node].emissionNumber; i++) { allStocks += sCVars.emissionLimits[i]; } if (_nodeOwner !=0x0000000000000000000000000000000000000000 && block.timestamp > sCVars.emissions[_node].date + 5184000 && sCVars.stockBalanceOf[_nodeOwner][_node] <= allStocks/2 ) { _emissionNumber = sCVars.emissions[_node].emissionNumber + 1; sCVars.stockBalanceOf[_nodeOwner][_node] += sCVars.emissionLimits[_emissionNumber]*(100 - _producersPercent)/100; uint thisNode = 0; for (i = 0; i < sCVars.stockOwnerInfo[_nodeOwner].nodes.length; i++) { if (sCVars.stockOwnerInfo[_nodeOwner].nodes[i] == _node) thisNode = 1; } if (thisNode == 0) sCVars.stockOwnerInfo[_nodeOwner].nodes.push(_node); sCVars.stockBalanceOf[_nodeProducer][_node] += sCVars.emissionLimits[_emissionNumber]*_producersPercent/100; for (i = 0; i < sCVars.stockOwnerInfo[_nodeProducer].nodes.length; i++) { if (sCVars.stockOwnerInfo[_nodeProducer].nodes[i] == _node) thisNode = 1; } if (thisNode == 0) sCVars.stockOwnerInfo[_nodeProducer].nodes.push(_node); sCVars.emissions[_node].date = block.timestamp; sCVars.emissions[_node].emissionNumber = _emissionNumber; _emissionAmount = sCVars.emissionLimits[_emissionNumber]; _result = true; } else _result = false; } thisNode = 0; function emission(uint _node) public returns(bool _result, uint _emissionNumber, uint _emissionAmount, uint _producersPercent) { var (x,y,,,,,,z,) = nodesVars.getNodeInfo(_node); address _nodeOwner = y; address _nodeProducer = x; _producersPercent = z; require(msg.sender == _nodeOwner || msg.sender == _nodeProducer); uint allStocks; for (uint i = 1; i <= sCVars.emissions[_node].emissionNumber; i++) { allStocks += sCVars.emissionLimits[i]; } if (_nodeOwner !=0x0000000000000000000000000000000000000000 && block.timestamp > sCVars.emissions[_node].date + 5184000 && sCVars.stockBalanceOf[_nodeOwner][_node] <= allStocks/2 ) { _emissionNumber = sCVars.emissions[_node].emissionNumber + 1; sCVars.stockBalanceOf[_nodeOwner][_node] += sCVars.emissionLimits[_emissionNumber]*(100 - _producersPercent)/100; uint thisNode = 0; for (i = 0; i < sCVars.stockOwnerInfo[_nodeOwner].nodes.length; i++) { if (sCVars.stockOwnerInfo[_nodeOwner].nodes[i] == _node) thisNode = 1; } if (thisNode == 0) sCVars.stockOwnerInfo[_nodeOwner].nodes.push(_node); sCVars.stockBalanceOf[_nodeProducer][_node] += sCVars.emissionLimits[_emissionNumber]*_producersPercent/100; for (i = 0; i < sCVars.stockOwnerInfo[_nodeProducer].nodes.length; i++) { if (sCVars.stockOwnerInfo[_nodeProducer].nodes[i] == _node) thisNode = 1; } if (thisNode == 0) sCVars.stockOwnerInfo[_nodeProducer].nodes.push(_node); sCVars.emissions[_node].date = block.timestamp; sCVars.emissions[_node].emissionNumber = _emissionNumber; _emissionAmount = sCVars.emissionLimits[_emissionNumber]; _result = true; } else _result = false; } function getStockOwnerInfo(address _address) constant public returns(uint[] _nodes) { _nodes = sCVars.stockOwnerInfo[_address].nodes; } function getStockBalance(address _address, uint _node) constant public returns(uint _balance) { _balance = sCVars.stockBalanceOf[_address][_node]; } function getWithFrozenStockBalance(address _address, uint _node) constant public returns(uint _balance) { _balance = sCVars.stockBalanceOf[_address][_node] + sCVars.stockFrozen[_address][_node]; } function getStockOrderInfo(bool _isBuyOrder, uint _node, uint _price, uint _number) constant public returns(address _address, uint _amount, uint _orderId) { if(_isBuyOrder == true) { _address = sCVars.stockBuyOrders[_node][_price][_number].client; _amount = sCVars.stockBuyOrders[_node][_price][_number].amount; _orderId = sCVars.stockBuyOrders[_node][_price][_number].orderId; } else { _address = sCVars.stockSellOrders[_node][_price][_number].client; _amount = sCVars.stockSellOrders[_node][_price][_number].amount; _orderId = sCVars.stockSellOrders[_node][_price][_number].orderId; } } function getStockOrderInfo(bool _isBuyOrder, uint _node, uint _price, uint _number) constant public returns(address _address, uint _amount, uint _orderId) { if(_isBuyOrder == true) { _address = sCVars.stockBuyOrders[_node][_price][_number].client; _amount = sCVars.stockBuyOrders[_node][_price][_number].amount; _orderId = sCVars.stockBuyOrders[_node][_price][_number].orderId; } else { _address = sCVars.stockSellOrders[_node][_price][_number].client; _amount = sCVars.stockSellOrders[_node][_price][_number].amount; _orderId = sCVars.stockSellOrders[_node][_price][_number].orderId; } } function getStockOrderInfo(bool _isBuyOrder, uint _node, uint _price, uint _number) constant public returns(address _address, uint _amount, uint _orderId) { if(_isBuyOrder == true) { _address = sCVars.stockBuyOrders[_node][_price][_number].client; _amount = sCVars.stockBuyOrders[_node][_price][_number].amount; _orderId = sCVars.stockBuyOrders[_node][_price][_number].orderId; } else { _address = sCVars.stockSellOrders[_node][_price][_number].client; _amount = sCVars.stockSellOrders[_node][_price][_number].amount; _orderId = sCVars.stockSellOrders[_node][_price][_number].orderId; } } function getStockBuyOrderPrices(uint _node) constant public returns(uint[] _prices) { _prices = sCVars.stockBuyOrderPrices[_node]; } function getStockSellOrderPrices(uint _node) constant public returns(uint[] _prices) { _prices = sCVars.stockSellOrderPrices[_node]; } function stockBuyOrder(uint _node, uint256 _buyPrice, uint _amount) public returns (uint[4] _results) { require(_node > 0 && _buyPrice > 0 && _amount > 0); _results = StarmidLibrary.stockBuyOrder(sCVars, _node, _buyPrice, _amount); require(_results[3] == 1); StockBuyOrder(_node, _buyPrice); } function stockSellOrder(uint _node, uint256 _sellPrice, uint _amount) public returns (uint[4] _results) { require(_node > 0 && _sellPrice > 0 && _amount > 0); _results = StarmidLibrary.stockSellOrder(sCVars, _node, _sellPrice, _amount); require(_results[3] == 1); StockSellOrder(_node, _sellPrice); } function stockCancelBuyOrder(uint _node, uint _thisOrderID, uint _price) public { require(StarmidLibrary.stockCancelBuyOrder(sCVars, _node, _thisOrderID, _price)); StockCancelBuyOrder(_node, _price); } function stockCancelSellOrder(uint _node, uint _thisOrderID, uint _price) public { require(StarmidLibrary.stockCancelSellOrder(sCVars, _node, _thisOrderID, _price)); StockCancelSellOrder(_node, _price); } function getLastDividends(uint _node) public constant returns (uint _lastDividents, uint _dividends) { uint stockAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount; uint sumAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount; if(sumAmount > 0) { uint stockAverageBuyPrice = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumPriceAmount/sumAmount; uint dividendsBase = stockAmount*stockAverageBuyPrice; _lastDividents = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumDateAmount/sumAmount; if(_lastDividents > 0)_dividends = (block.timestamp - _lastDividents)*dividendsBase/(10*31536000); else _dividends = 0; } } function getLastDividends(uint _node) public constant returns (uint _lastDividents, uint _dividends) { uint stockAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount; uint sumAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount; if(sumAmount > 0) { uint stockAverageBuyPrice = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumPriceAmount/sumAmount; uint dividendsBase = stockAmount*stockAverageBuyPrice; _lastDividents = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumDateAmount/sumAmount; if(_lastDividents > 0)_dividends = (block.timestamp - _lastDividents)*dividendsBase/(10*31536000); else _dividends = 0; } } function dividends(uint _node) public returns (bool _result, uint _dividends) { var (x,y,) = nodesVars.getNodeInfo(_node); uint _stockAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount; uint _sumAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount; if(_sumAmount > 0) { uint _stockAverageBuyPrice = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumPriceAmount/_sumAmount; uint _dividendsBase = _stockAmount*_stockAverageBuyPrice; uint _averageDate = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumDateAmount/_sumAmount; sCVars.balanceOf[msg.sender] += _div; sCVars.balanceOf[y] += _nodeDividends; totalSupply += _div + _div/4; _dividends = _div + _div/4; Transfer(this, msg.sender, _div); Transfer(this, y, _div/4); _result = true; } } function dividends(uint _node) public returns (bool _result, uint _dividends) { var (x,y,) = nodesVars.getNodeInfo(_node); uint _stockAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount; uint _sumAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount; if(_sumAmount > 0) { uint _stockAverageBuyPrice = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumPriceAmount/_sumAmount; uint _dividendsBase = _stockAmount*_stockAverageBuyPrice; uint _averageDate = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumDateAmount/_sumAmount; sCVars.balanceOf[msg.sender] += _div; sCVars.balanceOf[y] += _nodeDividends; totalSupply += _div + _div/4; _dividends = _div + _div/4; Transfer(this, msg.sender, _div); Transfer(this, y, _div/4); _result = true; } } function stockBuyCertainOrder(uint _node, uint _price, uint _amount, uint _thisOrderID) payable public returns (bool _results) { _results = StarmidLibraryExtra.stockBuyCertainOrder(sCVars, _node, _price, _amount, _thisOrderID); require(_results && _node > 0 && _amount > 0); StockBuyOrder(_node, _price); } function stockSellCertainOrder(uint _node, uint _price, uint _amount, uint _thisOrderID) public returns (bool _results) { _results = StarmidLibraryExtra.stockSellCertainOrder(sCVars, _node, _price, _amount, _thisOrderID); require(_results && _node > 0 && _amount > 0); StockSellOrder(_node, _price); } }
2,114,765
[ 1, 9634, 553, 510, 4610, 350, 7829, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 934, 4610, 350, 288, 203, 202, 2867, 1071, 3410, 31, 203, 202, 3205, 1071, 2199, 5555, 31, 203, 202, 1080, 1071, 508, 31, 203, 202, 1080, 1071, 3273, 31, 203, 202, 11890, 28, 1071, 15105, 31, 203, 202, 11890, 5034, 1071, 2078, 3088, 1283, 31, 203, 202, 18379, 27055, 9313, 18, 751, 1071, 272, 39, 5555, 31, 203, 202, 203, 202, 2575, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 202, 2575, 605, 9835, 2448, 12, 2867, 8808, 628, 16, 2254, 20944, 16, 2254, 30143, 5147, 1769, 203, 202, 2575, 348, 1165, 2448, 12, 2867, 8808, 628, 16, 2254, 20944, 16, 2254, 357, 80, 5147, 1769, 203, 202, 2575, 10347, 38, 9835, 2448, 12, 2867, 8808, 628, 16, 2254, 8808, 20944, 16, 2254, 6205, 1769, 203, 202, 2575, 10347, 55, 1165, 2448, 12, 2867, 8808, 628, 16, 2254, 8808, 20944, 16, 2254, 6205, 1769, 203, 202, 2575, 2197, 323, 5623, 12, 11890, 1509, 16, 1758, 27037, 16, 1758, 29804, 16, 2254, 6205, 16, 2254, 3844, 16, 2254, 20944, 1769, 203, 202, 2575, 20296, 363, 5912, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 8808, 756, 16, 2254, 5034, 460, 1769, 203, 202, 2575, 20296, 363, 38, 9835, 2448, 12, 11890, 756, 16, 2254, 30143, 5147, 1769, 203, 202, 2575, 20296, 363, 55, 1165, 2448, 12, 11890, 756, 16, 2254, 357, 80, 5147, 1769, 203, 202, 2575, 20296, 363, 6691, 38, 9835, 2448, 12, 11890, 756, 16, 2254, 6205, 1769, 203, 202, 2575, 20296, 363, 2 ]
./partial_match/1/0xF8d48D0404C74fEa55E9868f0D17e1108238982c/sources/RoboToken.sol
CHANGE THIS. Update the contract name.
contract RoboToken is StandardToken {
15,584,387
[ 1, 14473, 20676, 18, 2315, 326, 6835, 508, 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, 16351, 19686, 83, 1345, 353, 8263, 1345, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; // Project: High Reward Coin // v4, 2017-12-31 // This code is the property of CryptoB2B.io // Copying in whole or in part is prohibited. // Authors: Ivan Fedorov and Dmitry Borodin // Do you want the same ICO platform? www.cryptob2b.io // (A1) // The main contract for the sale and management of rounds. contract CrowdsaleBL{ using SafeMath for uint256; enum ICOType {round1, round2} enum Roles {beneficiary, accountant, manager, observer, bounty, team, company} Token public token; bool public isFinalized; bool public isInitialized; bool public isPausedCrowdsale; mapping (uint8 => address) public wallets; uint256 public startTime = 1516435200; // 20.01.2018 08:00:00 uint256 public endTime = 1519171199; // 20.02.2018 23:59:59 // How many tokens (excluding the bonus) are transferred to the investor in exchange for 1 ETH // **THOUSANDS** 10^3 for human, 1*10**3 for Solidity, 1e3 for MyEtherWallet (MEW). // Example: if 1ETH = 40.5 Token ==> use 40500 uint256 public rate = 400000; // Tokens // If the round does not attain this value before the closing date, the round is recognized as a // failure and investors take the money back (the founders will not interfere in any way). // **QUINTILLIONS** 10^18 / 1*10**18 / 1e18. Example: softcap=15ETH ==> use 15*10**18 (Solidity) or 15e18 (MEW) uint256 public softCap = 1240000*10**18; // 1,24M Tokens (~ $1 000 000) // The maximum possible amount of income // **QUINTILLIONS** 10^18 / 1*10**18 / 1e18. Example: hardcap=123.45ETH ==> use 123450*10**15 (Solidity) or 12345e15 (MEW) uint256 public hardCap = 9240000*10**18; // 9,24M Tokens (~ $12 700 00) // If the last payment is slightly higher than the hardcap, then the usual contracts do // not accept it, because it goes beyond the hardcap. However it is more reasonable to accept the // last payment, very slightly raising the hardcap. The value indicates by how many Token emitted the // last payment can exceed the hardcap to allow it to be paid. Immediately after this buy, the // round closes. The funders should write here a small number, not more than 1% of the CAP. // Can be equal to zero, to cancel. // **QUINTILLIONS** 10^18 / 1*10**18 / 1e18 uint256 public overLimit = 20000*10**18; // Tokens (~$20000) // The minimum possible payment from an investor in ETH. Payments below this value will be rejected. // **QUINTILLIONS** 10^18 / 1*10**18 / 1e18. Example: minPay=0.1ETH ==> use 100*10**15 (Solidity) or 100e15 (MEW) uint256 public minPay = 36*10**15; // 0,036 ETH (~$25) uint256 public ethWeiRaised; uint256 public nonEthWeiRaised; uint256 weiRound1; uint256 public tokenReserved; RefundVault public vault; SVTAllocation public lockedAllocation; struct BonusBlock {uint256 amount; uint256 procent;} BonusBlock[] public bonusPattern; ICOType ICO = ICOType.round2; // only ICO round #2 (no pre-ICO) uint256 allToken; bool public bounty; bool public team; bool public company; bool public partners; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event Finalized(); event Initialized(); function CrowdsaleBL(Token _token, uint256 firstMint) public { // Initially, all next 7 roles/wallets are given to the Manager. The Manager is an employee of the company // with knowledge of IT, who publishes the contract and sets it up. However, money and tokens require // a Beneficiary and other roles (Accountant, Team, etc.). The Manager will not have the right // to receive them. To enable this, the Manager must either enter specific wallets here, or perform // this via method changeWallet. In the finalization methods it is written which wallet and // what percentage of tokens are received. // Receives all the money (when finalizing pre-ICO & ICO) wallets[uint8(Roles.beneficiary)] = 0xe06bD713B2e33C218FDD56295Af74d45cE8c9D98; //msg.sender; // Receives all the tokens for non-ETH investors (when finalizing pre-ICO & ICO) wallets[uint8(Roles.accountant)] = 0xddC98d7d9CdD82172daD7467c8E341cfBEb077DD; //msg.sender; // All rights except the rights to receive tokens or money. Has the right to change any other // wallets (Beneficiary, Accountant, ...), but only if the round has not started. Once the // round is initialized, the Manager has lost all rights to change the wallets. // If the ICO is conducted by one person, then nothing needs to be changed. Permit all 7 roles // point to a single wallet. wallets[uint8(Roles.manager)] = msg.sender; // Has only the right to call paymentsInOtherCurrency (please read the document) wallets[uint8(Roles.observer)] = 0x76d737F21296cd1ED6938DbCA217615681b06336; //msg.sender; wallets[uint8(Roles.bounty)] = 0x4918fc7974d7Ee6F266f9256DfcA610FD735Bf27; //msg.sender; // When the round is finalized, all team tokens are transferred to a special freezing // contract. As soon as defrosting is over, only the Team wallet will be able to // collect all the tokens. It does not store the address of the freezing contract, // but the final wallet of the project team. wallets[uint8(Roles.team)] = 0xc59403026685F553f8a6937C53452b9d1DE4c707; // msg.sender; // startTime, endDiscountTime, endTime (then you can change it in the setup) //changePeriod(now + 5 minutes, now + 5 + 10 minutes, now + 5 + 12 minutes); wallets[uint8(Roles.company)] = 0xc59403026685F553f8a6937C53452b9d1DE4c707; //msg.sender; token = _token; token.setOwner(); token.pause(); // block exchange tokens token.addUnpausedWallet(msg.sender); token.addUnpausedWallet(wallets[uint8(Roles.company)]); token.addUnpausedWallet(wallets[uint8(Roles.bounty)]); token.addUnpausedWallet(wallets[uint8(Roles.accountant)]); if (firstMint > 0){ token.mint(msg.sender,firstMint); } } // Returns the name of the current round in plain text. Constant. function ICOSaleType() public constant returns(string){ return (ICO == ICOType.round1)?'round1':'round2'; } // Transfers the funds of the investor to the contract of return of funds. Internal. function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } // Check for the possibility of buying tokens. Inside. Constant. function validPurchase() internal constant returns (bool) { // The round started and did not end bool withinPeriod = (now > startTime && now < endTime); // Rate is greater than or equal to the minimum bool nonZeroPurchase = msg.value >= minPay; // round is initialized and no "Pause of trading" is set return withinPeriod && nonZeroPurchase && isInitialized && !isPausedCrowdsale; } // Check for the ability to finalize the round. Constant. function hasEnded() public constant returns (bool) { bool timeReached = now > endTime; bool capReached = token.totalSupply().add(tokenReserved) >= hardCap; return (timeReached || capReached) && isInitialized; } function finalizeAll() external { finalize(); finalize1(); finalize2(); finalize3(); finalize4(); } // Finalize. Only available to the Manager and the Beneficiary. If the round failed, then // anyone can call the finalization to unlock the return of funds to investors // You must call a function to finalize each round (after the pre-ICO & after the ICO) function finalize() public { require(wallets[uint8(Roles.manager)] == msg.sender || wallets[uint8(Roles.beneficiary)] == msg.sender|| !goalReached()); require(!isFinalized); require(hasEnded()); isFinalized = true; finalization(); Finalized(); } // The logic of finalization. Internal function finalization() internal { // If the goal of the achievement if (goalReached()) { // Send ether to Beneficiary vault.close(wallets[uint8(Roles.beneficiary)]); // if there is anything to give if (tokenReserved > 0) { // Issue tokens of non-eth investors to Accountant account token.mint(wallets[uint8(Roles.accountant)],tokenReserved); // Reset the counter tokenReserved = 0; } // If the finalization is Round 1 pre-ICO if (ICO == ICOType.round1) { // Reset settings isInitialized = false; isFinalized = false; // Switch to the second round (to ICO) ICO = ICOType.round2; // Reset the collection counter weiRound1 = weiRaised(); ethWeiRaised = 0; nonEthWeiRaised = 0; } else // If the second round is finalized { // Record how many tokens we have issued allToken = token.totalSupply(); // Permission to collect tokens to those who can pick them up bounty = true; team = true; company = true; partners = true; } } else // If they failed round { // Allow investors to withdraw their funds vault.enableRefunds(); } } // The Manager freezes the tokens for the Team. // You must call a function to finalize Round 2 (only after the ICO) function finalize1() public { require(wallets[uint8(Roles.manager)] == msg.sender || wallets[uint8(Roles.beneficiary)] == msg.sender); require(team); team = false; lockedAllocation = new SVTAllocation(token, wallets[uint8(Roles.team)]); token.addUnpausedWallet(lockedAllocation); // 6% - tokens to Team wallet after freeze (77% for investors) // *** CHECK THESE NUMBERS *** token.mint(lockedAllocation, allToken.mul(6).div(77)); } function finalize2() public { require(wallets[uint8(Roles.manager)] == msg.sender || wallets[uint8(Roles.beneficiary)] == msg.sender); require(bounty); bounty = false; // 2% - tokens to bounty wallet (77% for investors) // *** CHECK THESE NUMBERS *** token.mint(wallets[uint8(Roles.bounty)], allToken.mul(2).div(77)); } function finalize3() public { require(wallets[uint8(Roles.manager)] == msg.sender || wallets[uint8(Roles.beneficiary)] == msg.sender); require(company); company = false; // 2% - tokens to company wallet (77% for investors) // *** CHECK THESE NUMBERS *** token.mint(wallets[uint8(Roles.company)],allToken.mul(2).div(77)); } function finalize4() public { require(wallets[uint8(Roles.manager)] == msg.sender || wallets[uint8(Roles.beneficiary)] == msg.sender); require(partners); partners = false; // 13% - tokens to partners+referral wallet (77% for investors) // *** CHECK THESE NUMBERS *** token.mint(wallets[uint8(Roles.accountant)],allToken.mul(13).div(77)); } // Initializing the round. Available to the manager. After calling the function, // the Manager loses all rights: Manager can not change the settings (setup), change // wallets, prevent the beginning of the round, etc. You must call a function after setup // for the initial round (before the Pre-ICO and before the ICO) function initialize() public{ // Only the Manager require(wallets[uint8(Roles.manager)] == msg.sender); // If not yet initialized require(!isInitialized); // And the specified start time has not yet come // If initialization return an error, check the start date! require(now <= startTime); initialization(); Initialized(); isInitialized = true; } function initialization() internal { vault = new RefundVault(); } // At the request of the investor, we raise the funds (if the round has failed because of the hardcap) function claimRefund() public{ vault.refund(msg.sender); } // We check whether we collected the necessary minimum funds. Constant. function goalReached() public constant returns (bool) { return token.totalSupply().add(tokenReserved) >= softCap; } // Customize. The arguments are described in the constructor above. function setup(uint256 _startTime, uint256 _endTime, uint256 _softCap, uint256 _hardCap, uint256 _rate, uint256 _overLimit, uint256 _minPay, uint256[] _amount, uint256[] _procent) public{ changePeriod(_startTime, _endTime); changeRate(_rate, _minPay); changeCap(_softCap, _hardCap, _overLimit); if(_amount.length > 0) setBonusPattern(_amount,_procent); } // Change the date and time: the beginning of the round, the end of the bonus, the end of the round. Available to Manager // Description in the Crowdsale constructor function changePeriod(uint256 _startTime, uint256 _endTime) public{ require(wallets[uint8(Roles.manager)] == msg.sender); require(!isInitialized); // Date and time are correct require(now <= _startTime); require(_startTime < _endTime); startTime = _startTime; endTime = _endTime; } // Change the price (the number of tokens per 1 eth), the maximum hardCap for the last bet, // the minimum bet. Available to the Manager. // Description in the Crowdsale constructor function changeRate(uint256 _rate, uint256 _minPay) public { require(wallets[uint8(Roles.manager)] == msg.sender || wallets[uint8(Roles.observer)] == msg.sender); require(_rate > 0); rate = _rate; minPay = _minPay; } function changeCap(uint256 _softCap, uint256 _hardCap, uint256 _overLimit) public { require(wallets[uint8(Roles.manager)] == msg.sender); require(!isInitialized); require(_hardCap > _softCap); softCap = _softCap; hardCap = _hardCap; overLimit = _overLimit; } function setBonusPattern(uint256[] _amount, uint256[] _procent) public { require(wallets[uint8(Roles.manager)] == msg.sender); require(!isInitialized); require(_amount.length == _procent.length); bonusPattern.length = _amount.length; for(uint256 i = 0; i < _amount.length; i++){ bonusPattern[i] = BonusBlock(_amount[i],_procent[i]); } } // Collected funds for the current round. Constant. function weiRaised() public constant returns(uint256){ return ethWeiRaised.add(nonEthWeiRaised); } // Returns the amount of fees for both phases. Constant. function weiTotalRaised() public constant returns(uint256){ return weiRound1.add(weiRaised()); } // The ability to quickly check pre-ICO (only for Round 1, only 1 time). Completes the pre-ICO by // transferring the specified number of tokens to the Accountant's wallet. Available to the Manager. // Use only if this is provided by the script and white paper. In the normal scenario, it // does not call and the funds are raised normally. We recommend that you delete this // function entirely, so as not to confuse the auditors. Initialize & Finalize not needed. // ** QUINTILIONS ** 10^18 / 1*10**18 / 1e18 // function fastICO(uint256 _totalSupply) public { // require(wallets[uint8(Roles.manager)] == msg.sender); // require(ICO == ICOType.round1 && !isInitialized); // token.mint(wallets[uint8(Roles.accountant)], _totalSupply); // ICO = ICOType.round2; // } // Remove the "Pause of exchange". Available to the manager at any time. If the // manager refuses to remove the pause, then 30 days after the successful // completion of the ICO, anyone can remove a pause and allow the exchange to continue. // The manager does not interfere and will not be able to delay the term. // He can only cancel the pause before the appointed time. function tokenUnpause() public { require(wallets[uint8(Roles.manager)] == msg.sender || (now > endTime + 30 days && ICO == ICOType.round2 && isFinalized && goalReached())); token.unpause(); } // Enable the "Pause of exchange". Available to the manager until the ICO is completed. // The manager cannot turn on the pause, for example, 3 years after the end of the ICO. function tokenPause() public { require(wallets[uint8(Roles.manager)] == msg.sender && !isFinalized); token.pause(); } // Pause of sale. Available to the manager. function crowdsalePause() public { require(wallets[uint8(Roles.manager)] == msg.sender); require(isPausedCrowdsale == false); isPausedCrowdsale = true; } // Withdrawal from the pause of sale. Available to the manager. function crowdsaleUnpause() public { require(wallets[uint8(Roles.manager)] == msg.sender); require(isPausedCrowdsale == true); isPausedCrowdsale = false; } // Checking whether the rights to address ignore the "Pause of exchange". If the // wallet is included in this list, it can translate tokens, ignoring the pause. By default, // only the following wallets are included: // - Accountant wallet (he should immediately transfer tokens, but not to non-ETH investors) // - Contract for freezing the tokens for the Team (but Team wallet not included) // Inside. Constant. function unpausedWallet(address _wallet) internal constant returns(bool) { bool _accountant = wallets[uint8(Roles.accountant)] == _wallet; bool _manager = wallets[uint8(Roles.manager)] == _wallet; bool _bounty = wallets[uint8(Roles.bounty)] == _wallet; bool _company = wallets[uint8(Roles.company)] == _wallet; return _accountant || _manager || _bounty || _company; } // For example - After 5 years of the project's existence, all of us suddenly decided collectively // (company + investors) that it would be more profitable for everyone to switch to another smart // contract responsible for tokens. The company then prepares a new token, investors // disassemble, study, discuss, etc. After a general agreement, the manager allows any investor: // - to burn the tokens of the previous contract // - generate new tokens for a new contract // It is understood that after a general solution through this function all investors // will collectively (and voluntarily) move to a new token. function moveTokens(address _migrationAgent) public { require(wallets[uint8(Roles.manager)] == msg.sender); token.setMigrationAgent(_migrationAgent); } // Change the address for the specified role. // Available to any wallet owner except the observer. // Available to the manager until the round is initialized. // The Observer's wallet or his own manager can change at any time. function changeWallet(Roles _role, address _wallet) public { require( (msg.sender == wallets[uint8(_role)] && _role != Roles.observer) || (msg.sender == wallets[uint8(Roles.manager)] && (!isInitialized || _role == Roles.observer)) ); address oldWallet = wallets[uint8(_role)]; wallets[uint8(_role)] = _wallet; if(!unpausedWallet(oldWallet)) token.delUnpausedWallet(oldWallet); if(unpausedWallet(_wallet)) token.addUnpausedWallet(_wallet); } // If a little more than a year has elapsed (ICO start date + 400 days), a smart contract // will allow you to send all the money to the Beneficiary, if any money is present. This is // possible if you mistakenly launch the ICO for 30 years (not 30 days), investors will transfer // money there and you will not be able to pick them up within a reasonable time. It is also // possible that in our checked script someone will make unforeseen mistakes, spoiling the // finalization. Without finalization, money cannot be returned. This is a rescue option to // get around this problem, but available only after a year (400 days). // Another reason - the ICO was a failure, but not all ETH investors took their money during the year after. // Some investors may have lost a wallet key, for example. // The method works equally with the pre-ICO and ICO. When the pre-ICO starts, the time for unlocking // the distructVault begins. If the ICO is then started, then the term starts anew from the first day of the ICO. // Next, act independently, in accordance with obligations to investors. // Within 400 days of the start of the Round, if it fails only investors can take money. After // the deadline this can also include the company as well as investors, depending on who is the first to use the method. function distructVault() public { require(wallets[uint8(Roles.beneficiary)] == msg.sender); require(now > startTime + 400 days); vault.del(wallets[uint8(Roles.beneficiary)]); } function getBonus(uint256 _tokenValue) public constant returns (uint256 value) { uint256 totalToken = tokenReserved.add(token.totalSupply()); uint256 tokenValue = _tokenValue; uint256 currentBonus; uint256 calculateBonus = 0; uint16 i; for (i = 0; i < bonusPattern.length; i++){ if(totalToken >= bonusPattern[i].amount) continue; currentBonus = tokenValue.mul(bonusPattern[i].procent.add(100000)).div(100000); if(totalToken.add(calculateBonus).add(currentBonus) < bonusPattern[i].amount) { calculateBonus = calculateBonus.add(currentBonus); tokenValue = 0; break; } currentBonus = bonusPattern[i].amount.sub(totalToken.add(calculateBonus)); tokenValue = tokenValue.sub(currentBonus.mul(100000).div(bonusPattern[i].procent.add(100000))); calculateBonus = calculateBonus + currentBonus; } return calculateBonus.add(tokenValue); } // We accept payments other than Ethereum (ETH) and other currencies, for example, Bitcoin (BTC). // Perhaps other types of cryptocurrency - see the original terms in the white paper and on the ICO website. // We release tokens on Ethereum. During the pre-ICO and ICO with a smart contract, you directly transfer // the tokens there and immediately, with the same transaction, receive tokens in your wallet. // When paying in any other currency, for example in BTC, we accept your money via one common wallet. // Our manager fixes the amount received for the bitcoin wallet and calls the method of the smart // contract paymentsInOtherCurrency to inform him how much foreign currency has been received - on a daily basis. // The smart contract pins the number of accepted ETH directly and the number of BTC. Smart contract // monitors softcap and hardcap, so as not to go beyond this framework. // In theory, it is possible that when approaching hardcap, we will receive a transfer (one or several // transfers) to the wallet of BTC, that together with previously received money will exceed the hardcap in total. // In this case, we will refund all the amounts above, in order not to exceed the hardcap. // Collection of money in BTC will be carried out via one common wallet. The wallet's address will be published // everywhere (in a white paper, on the ICO website, on Telegram, on Bitcointalk, in this code, etc.) // Anyone interested can check that the administrator of the smart contract writes down exactly the amount // in ETH (in equivalent for BTC) there. In theory, the ability to bypass a smart contract to accept money in // BTC and not register them in ETH creates a possibility for manipulation by the company. Thanks to // paymentsInOtherCurrency however, this threat is leveled. // Any user can check the amounts in BTC and the variable of the smart contract that accounts for this // (paymentsInOtherCurrency method). Any user can easily check the incoming transactions in a smart contract // on a daily basis. Any hypothetical tricks on the part of the company can be exposed and panic during the ICO, // simply pointing out the incompatibility of paymentsInOtherCurrency (ie, the amount of ETH + BTC collection) // and the actual transactions in BTC. The company strictly adheres to the described principles of openness. // The company administrator is required to synchronize paymentsInOtherCurrency every working day (but you // cannot synchronize if there are no new BTC payments). In the case of unforeseen problems, such as // brakes on the Ethereum network, this operation may be difficult. You should only worry if the // administrator does not synchronize the amount for more than 96 hours in a row, and the BTC wallet // receives significant amounts. // This scenario ensures that for the sum of all fees in all currencies this value does not exceed hardcap. // Common BTC wallet: 12sEoiXPs8a6sJbC2qkbZDjmHsSBv7cGwC // ** QUINTILLIONS ** 10^18 / 1**18 / 1e18 function paymentsInOtherCurrency(uint256 _token, uint256 _value) public { require(wallets[uint8(Roles.observer)] == msg.sender); bool withinPeriod = (now >= startTime && now <= endTime); bool withinCap = token.totalSupply().add(_token) <= hardCap.add(overLimit); require(withinPeriod && withinCap && isInitialized); nonEthWeiRaised = _value; tokenReserved = _token; } // The function for obtaining smart contract funds in ETH. If all the checks are true, the token is // transferred to the buyer, taking into account the current bonus. function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = getBonus(weiAmount*rate/1000); // hardCap is not reached, and in the event of a transaction, it will not be exceeded by more than OverLimit bool withinCap = tokens <= hardCap.sub(token.totalSupply().add(tokenReserved)).add(overLimit); require(withinCap); // update state ethWeiRaised = ethWeiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // buyTokens alias function () public payable { buyTokens(msg.sender); } } // (B) // The contract for freezing tokens for the team.. contract SVTAllocation { using SafeMath for uint256; Token public token; address public owner; uint256 public unlockedAt; uint256 tokensCreated = 0; // The contract takes the ERC20 coin address from which this contract will work and from the // owner (Team wallet) who owns the funds. function SVTAllocation(Token _token, address _owner) public{ // How many days to freeze from the moment of finalizing ICO unlockedAt = now + 1 years; token = _token; owner = _owner; } // If the time of freezing expired will return the funds to the owner. function unlock() public{ require(now >= unlockedAt); require(token.transfer(owner,token.balanceOf(this))); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this does not 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 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 Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool _paused = false; function paused() public constant returns(bool) { return _paused; } /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused()); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner public { require(!_paused); _paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner public { require(_paused); _paused = false; Unpause(); } } // Contract interface for transferring current tokens to another contract MigrationAgent { function migrateFrom(address _from, uint256 _value) public; } // (A2) // Contract token contract Token is Pausable{ using SafeMath for uint256; string public constant name = "High Reward Coin"; string public constant symbol = "HRC"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; mapping (address => bool) public unpausedWallet; bool public mintingFinished = false; uint256 public totalMigrated; address public migrationAgent; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Mint(address indexed to, uint256 amount); event MintFinished(); event Migrate(address indexed _from, address indexed _to, uint256 _value); modifier canMint() { require(!mintingFinished); _; } function Token() public { owner = 0x0; } function setOwner() public{ require(owner == 0x0); owner = msg.sender; } // Balance of the specified address function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } // Transfer of tokens from one account to another function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require (_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } // Returns the number of tokens that _owner trusted to spend from his account _spender function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // Trust _sender and spend _value tokens from your account 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; Approval(msg.sender, _spender, _value); return true; } // Transfer of tokens from the trusted address _from to the address _to in the number _value function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { var _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); require (_value > 0); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } // Issue new tokens to the address _to in the amount _amount. Available to the owner of the contract (contract Crowdsale) function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } // Stop the release of tokens. This is not possible to cancel. Available to the owner of the contract. // function finishMinting() public onlyOwner returns (bool) { // mintingFinished = true; // MintFinished(); // return true; // } // Redefinition of the method of the returning status of the "Exchange pause". // Never for the owner of an unpaused wallet. function paused() public constant returns(bool) { return super.paused() && !unpausedWallet[msg.sender]; } // Add a wallet ignoring the "Exchange pause". Available to the owner of the contract. function addUnpausedWallet(address _wallet) public onlyOwner { unpausedWallet[_wallet] = true; } // Remove the wallet ignoring the "Exchange pause". Available to the owner of the contract. function delUnpausedWallet(address _wallet) public onlyOwner { unpausedWallet[_wallet] = false; } // Enable the transfer of current tokens to others. Only 1 time. Disabling this is not possible. // Available to the owner of the contract. function setMigrationAgent(address _migrationAgent) public onlyOwner { require(migrationAgent == 0x0); migrationAgent = _migrationAgent; } // Reissue your tokens. function migrate() public { uint256 value = balances[msg.sender]; require(value > 0); totalSupply = totalSupply.sub(value); totalMigrated = totalMigrated.add(value); MigrationAgent(migrationAgent).migrateFrom(msg.sender, value); Migrate(msg.sender,migrationAgent,value); balances[msg.sender] = 0; } } // (A3) // Contract for freezing of investors' funds. Hence, investors will be able to withdraw money if the // round does not attain the softcap. From here the wallet of the beneficiary will receive all the // money (namely, the beneficiary, not the manager's wallet). contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); event Deposited(address indexed beneficiary, uint256 weiAmount); function RefundVault() public { state = State.Active; } // Depositing funds on behalf of an ICO investor. Available to the owner of the contract (Crowdsale Contract). function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); Deposited(investor,msg.value); } // Move the collected funds to a specified address. Available to the owner of the contract. function close(address _wallet) onlyOwner public { require(state == State.Active); require(_wallet != 0x0); state = State.Closed; Closed(); _wallet.transfer(this.balance); } // Allow refund to investors. Available to the owner of the contract. function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } // Return the funds to a specified investor. In case of failure of the round, the investor // should call this method of this contract (RefundVault) or call the method claimRefund of Crowdsale // contract. This function should be called either by the investor himself, or the company // (or anyone) can call this function in the loop to return funds to all investors en masse. function refund(address investor) public { require(state == State.Refunding); require(deposited[investor] > 0); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } // Destruction of the contract with return of funds to the specified address. Available to // the owner of the contract. function del(address _wallet) external onlyOwner { selfdestruct(_wallet); } }
We check whether we collected the necessary minimum funds. Constant.
function goalReached() public constant returns (bool) { return token.totalSupply().add(tokenReserved) >= softCap; }
12,598,854
[ 1, 3218, 866, 2856, 732, 12230, 326, 4573, 5224, 284, 19156, 18, 10551, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 17683, 23646, 1435, 1071, 5381, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1147, 18, 4963, 3088, 1283, 7675, 1289, 12, 2316, 10435, 13, 1545, 8971, 4664, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./CounterControllerV1.sol"; contract CounterControllerV2 is CounterControllerV1 { // controller version number uint256 public constant VERSION_V2 = 2; // state for previous value of counter uint256 private _previousValue; // additional business logic for this version function previousValue() public view returns (uint256) { return _previousValue; } // upgrade/migration of contract state to setup for new version // introduction of new state variable that depends on current state // necessary migration/initialisation in implemetation body function upgradeToV2(uint256 value) external upgradeToVersion(VERSION_V2) { _previousValue = CounterControllerV1.value(); _setValue(value); } function _setValue(uint256 newValue) internal override { _previousValue = value(); CounterControllerV1._setValue(newValue); } }
controller version number state for previous value of counter additional business logic for this version
contract CounterControllerV2 is CounterControllerV1 { uint256 public constant VERSION_V2 = 2; uint256 private _previousValue; pragma solidity ^0.8.0; function previousValue() public view returns (uint256) { return _previousValue; } function upgradeToV2(uint256 value) external upgradeToVersion(VERSION_V2) { _previousValue = CounterControllerV1.value(); _setValue(value); } function _setValue(uint256 newValue) internal override { _previousValue = value(); CounterControllerV1._setValue(newValue); } }
6,476,707
[ 1, 5723, 1177, 1300, 919, 364, 2416, 460, 434, 3895, 3312, 13160, 4058, 364, 333, 1177, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 9354, 2933, 58, 22, 353, 9354, 2933, 58, 21, 288, 203, 203, 565, 2254, 5034, 1071, 5381, 8456, 67, 58, 22, 273, 576, 31, 203, 203, 565, 2254, 5034, 3238, 389, 11515, 620, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 445, 2416, 620, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 7010, 3639, 327, 389, 11515, 620, 31, 7010, 565, 289, 27699, 203, 565, 445, 8400, 774, 58, 22, 12, 11890, 5034, 460, 13, 3903, 8400, 774, 1444, 12, 5757, 67, 58, 22, 13, 288, 203, 3639, 389, 11515, 620, 273, 9354, 2933, 58, 21, 18, 1132, 5621, 203, 3639, 389, 542, 620, 12, 1132, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 542, 620, 12, 11890, 5034, 6129, 13, 2713, 3849, 288, 7010, 3639, 389, 11515, 620, 273, 460, 5621, 203, 3639, 9354, 2933, 58, 21, 6315, 542, 620, 12, 2704, 620, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xD803Bb955AfBf9b66CfC6DF64A629ffE798BB599/sources/PSHARK.sol
set as buyBackWallet
buyBackWallet = address(0xA776aBea31a0374C01C12eaeB2AC7598950875C3);
9,395,495
[ 1, 542, 487, 30143, 2711, 16936, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 30143, 2711, 16936, 273, 1758, 12, 20, 21703, 4700, 26, 69, 1919, 69, 6938, 69, 4630, 5608, 39, 1611, 39, 2138, 73, 8906, 38, 22, 2226, 5877, 29, 6675, 3361, 28, 5877, 39, 23, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.8; // /** * @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 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 Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // /** * @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. * * Credit: https://github.com/OpenZeppelin/openzeppelin-upgrades/blob/master/packages/core/contracts/Initializable.sol */ 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; } // /** * @notice Interface for ERC20 token which supports minting new tokens. */ interface IERC20Mintable is IERC20 { function mint(address _user, uint256 _amount) external; } // /** * @notice Interface for ERC20 token which supports mint and burn. */ interface IERC20MintableBurnable is IERC20Mintable { function burn(address _user, uint256 _amount) external; } // /** * @notice ACoconut swap. */ contract ACoconutSwap is Initializable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @dev Token swapped between two underlying tokens. */ event TokenSwapped(address indexed buyer, address indexed tokenSold, address indexed tokenBought, uint256 amountSold, uint256 amountBought); /** * @dev New pool token is minted. */ event Minted(address indexed provider, uint256 mintAmount, uint256[] amounts, uint256 feeAmount); /** * @dev Pool token is redeemed. */ event Redeemed(address indexed provider, uint256 redeemAmount, uint256[] amounts, uint256 feeAmount); /** * @dev Fee is collected. */ event FeeCollected(address indexed feeRecipient, uint256 feeAmount); uint256 public constant feeDenominator = 10 ** 10; address[] public tokens; uint256[] public precisions; // 10 ** (18 - token decimals) uint256[] public balances; // Converted to 10 ** 18 uint256 public mintFee; // Mint fee * 10**10 uint256 public swapFee; // Swap fee * 10**10 uint256 public redeemFee; // Redeem fee * 10**10 address public feeRecipient; address public poolToken; uint256 public totalSupply; // The total amount of pool token minted by the swap. // It might be different from the pool token supply as the pool token can have multiple minters. address public governance; mapping(address => bool) public admins; bool public paused; uint256 public initialA; /** * @dev Initialize the ACoconut Swap. */ function initialize(address[] memory _tokens, uint256[] memory _precisions, uint256[] memory _fees, address _poolToken, uint256 _A) public initializer { require(_tokens.length == _precisions.length, "input mismatch"); require(_fees.length == 3, "no fees"); for (uint256 i = 0; i < _tokens.length; i++) { require(_tokens[i] != address(0x0), "token not set"); require(_precisions[i] != 0, "precision not set"); balances.push(0); } require(_poolToken != address(0x0), "pool token not set"); governance = msg.sender; feeRecipient = msg.sender; tokens = _tokens; precisions = _precisions; mintFee = _fees[0]; swapFee = _fees[1]; redeemFee = _fees[2]; poolToken = _poolToken; initialA = _A; // The swap must start with paused state! paused = true; } /** * @dev Returns the current value of A. This method might be updated in the future. */ function getA() public view returns (uint256) { return initialA; } /** * @dev Computes D given token balances. * @param _balances Normalized balance of each token. * @param _A Amplification coefficient from getA() */ function _getD(uint256[] memory _balances, uint256 _A) internal pure returns (uint256) { uint256 sum = 0; uint256 i = 0; uint256 Ann = _A; for (i = 0; i < _balances.length; i++) { sum = sum.add(_balances[i]); Ann = Ann.mul(_balances.length); } if (sum == 0) return 0; uint256 prevD = 0; uint256 D = sum; for (i = 0; i < 255; i++) { uint256 pD = D; for (uint256 j = 0; j < _balances.length; j++) { // pD = pD * D / (_x * balance.length) pD = pD.mul(D).div(_balances[j].mul(_balances.length)); } prevD = D; // D = (Ann * sum + pD * balance.length) * D / ((Ann - 1) * D + (balance.length + 1) * pD) D = Ann.mul(sum).add(pD.mul(_balances.length)).mul(D).div(Ann.sub(1).mul(D).add(_balances.length.add(1).mul(pD))); if (D > prevD) { if (D - prevD <= 1) break; } else { if (prevD - D <= 1) break; } } return D; } /** * @dev Computes token balance given D. * @param _balances Converted balance of each token except token with index _j. * @param _j Index of the token to calculate balance. * @param _D The target D value. * @param _A Amplification coeffient. * @return Converted balance of the token with index _j. */ function _getY(uint256[] memory _balances, uint256 _j, uint256 _D, uint256 _A) internal pure returns (uint256) { uint256 c = _D; uint256 S_ = 0; uint256 Ann = _A; uint256 i = 0; for (i = 0; i < _balances.length; i++) { Ann = Ann.mul(_balances.length); if (i == _j) continue; S_ = S_.add(_balances[i]); // c = c * D / (_x * N) c = c.mul(_D).div(_balances[i].mul(_balances.length)); } // c = c * D / (Ann * N) c = c.mul(_D).div(Ann.mul(_balances.length)); // b = S_ + D / Ann uint256 b = S_.add(_D.div(Ann)); uint256 prevY = 0; uint256 y = _D; // 255 since the result is 256 digits for (i = 0; i < 255; i++) { prevY = y; // y = (y * y + c) / (2 * y + b - D) y = y.mul(y).add(c).div(y.mul(2).add(b).sub(_D)); if (y > prevY) { if (y - prevY <= 1) break; } else { if (prevY - y <= 1) break; } } return y; } /** * @dev Compute the amount of pool token that can be minted. * @param _amounts Unconverted token balances. * @return The amount of pool token minted. */ function getMintAmount(uint256[] calldata _amounts) external view returns (uint256, uint256) { uint256[] memory _balances = balances; require(_amounts.length == _balances.length, "invalid amount"); uint256 A = getA(); uint256 oldD = totalSupply; uint256 i = 0; for (i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) continue; // balance = balance + amount * precision _balances[i] = _balances[i].add(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be bigger than or equal to oldD uint256 mintAmount = newD.sub(oldD); uint256 feeAmount = 0; if (mintFee > 0) { feeAmount = mintAmount.mul(mintFee).div(feeDenominator); mintAmount = mintAmount.sub(feeAmount); } return (mintAmount, feeAmount); } /** * @dev Mints new pool token. * @param _amounts Unconverted token balances used to mint pool token. * @param _minMintAmount Minimum amount of pool token to mint. */ function mint(uint256[] calldata _amounts, uint256 _minMintAmount) external nonReentrant { uint256[] memory _balances = balances; // If swap is paused, only admins can mint. require(!paused || admins[msg.sender], "paused"); require(_balances.length == _amounts.length, "invalid amounts"); uint256 A = getA(); uint256 oldD = totalSupply; uint256 i = 0; for (i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) { // Initial deposit requires all tokens provided! require(oldD > 0, "zero amount"); continue; } _balances[i] = _balances[i].add(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be bigger than or equal to oldD uint256 mintAmount = newD.sub(oldD); uint256 fee = mintFee; uint256 feeAmount; if (fee > 0) { feeAmount = mintAmount.mul(fee).div(feeDenominator); mintAmount = mintAmount.sub(feeAmount); } require(mintAmount >= _minMintAmount, "fewer than expected"); // Transfer tokens into the swap for (i = 0; i < _amounts.length; i++) { if (_amounts[i] == 0) continue; // Update the balance in storage balances[i] = _balances[i]; IERC20(tokens[i]).safeTransferFrom(msg.sender, address(this), _amounts[i]); } totalSupply = newD; IERC20MintableBurnable(poolToken).mint(feeRecipient, feeAmount); IERC20MintableBurnable(poolToken).mint(msg.sender, mintAmount); emit Minted(msg.sender, mintAmount, _amounts, feeAmount); } /** * @dev Computes the output amount after the swap. * @param _i Token index to swap in. * @param _j Token index to swap out. * @param _dx Unconverted amount of token _i to swap in. * @return Unconverted amount of token _j to swap out. */ function getSwapAmount(uint256 _i, uint256 _j, uint256 _dx) external view returns (uint256) { uint256[] memory _balances = balances; require(_i != _j, "same token"); require(_i < _balances.length, "invalid in"); require(_j < _balances.length, "invalid out"); require(_dx > 0, "invalid amount"); uint256 A = getA(); uint256 D = totalSupply; // balance[i] = balance[i] + dx * precisions[i] _balances[_i] = _balances[_i].add(_dx.mul(precisions[_i])); uint256 y = _getY(_balances, _j, D, A); // dy = (balance[j] - y - 1) / precisions[j] in case there was rounding errors uint256 dy = _balances[_j].sub(y).sub(1).div(precisions[_j]); if (swapFee > 0) { dy = dy.sub(dy.mul(swapFee).div(feeDenominator)); } return dy; } /** * @dev Exchange between two underlying tokens. * @param _i Token index to swap in. * @param _j Token index to swap out. * @param _dx Unconverted amount of token _i to swap in. * @param _minDy Minimum token _j to swap out in converted balance. */ function swap(uint256 _i, uint256 _j, uint256 _dx, uint256 _minDy) external nonReentrant { uint256[] memory _balances = balances; // If swap is paused, only admins can swap. require(!paused || admins[msg.sender], "paused"); require(_i != _j, "same token"); require(_i < _balances.length, "invalid in"); require(_j < _balances.length, "invalid out"); require(_dx > 0, "invalid amount"); uint256 A = getA(); uint256 D = totalSupply; // balance[i] = balance[i] + dx * precisions[i] _balances[_i] = _balances[_i].add(_dx.mul(precisions[_i])); uint256 y = _getY(_balances, _j, D, A); // dy = (balance[j] - y - 1) / precisions[j] in case there was rounding errors uint256 dy = _balances[_j].sub(y).sub(1).div(precisions[_j]); // Update token balance in storage balances[_j] = y; balances[_i] = _balances[_i]; uint256 fee = swapFee; if (fee > 0) { dy = dy.sub(dy.mul(fee).div(feeDenominator)); } require(dy >= _minDy, "fewer than expected"); IERC20(tokens[_i]).safeTransferFrom(msg.sender, address(this), _dx); // Important: When swap fee > 0, the swap fee is charged on the output token. // Therefore, balances[j] < tokens[j].balanceOf(this) // Since balances[j] is used to compute D, D is unchanged. // collectFees() is used to convert the difference between balances[j] and tokens[j].balanceOf(this) // into pool token as fees! IERC20(tokens[_j]).safeTransfer(msg.sender, dy); emit TokenSwapped(msg.sender, tokens[_i], tokens[_j], _dx, dy); } /** * @dev Computes the amounts of underlying tokens when redeeming pool token. * @param _amount Amount of pool tokens to redeem. * @return Amounts of underlying tokens redeemed. */ function getRedeemProportionAmount(uint256 _amount) external view returns (uint256[] memory, uint256) { uint256[] memory _balances = balances; require(_amount > 0, "zero amount"); uint256 D = totalSupply; uint256[] memory amounts = new uint256[](_balances.length); uint256 feeAmount = 0; if (redeemFee > 0) { feeAmount = _amount.mul(redeemFee).div(feeDenominator); // Redemption fee is charged with pool token before redemption. _amount = _amount.sub(feeAmount); } for (uint256 i = 0; i < _balances.length; i++) { // We might choose to use poolToken.totalSupply to compute the amount, but decide to use // D in case we have multiple minters on the pool token. amounts[i] = _balances[i].mul(_amount).div(D).div(precisions[i]); } return (amounts, feeAmount); } /** * @dev Redeems pool token to underlying tokens proportionally. * @param _amount Amount of pool token to redeem. * @param _minRedeemAmounts Minimum amount of underlying tokens to get. */ function redeemProportion(uint256 _amount, uint256[] calldata _minRedeemAmounts) external nonReentrant { uint256[] memory _balances = balances; // If swap is paused, only admins can redeem. require(!paused || admins[msg.sender], "paused"); require(_amount > 0, "zero amount"); require(_balances.length == _minRedeemAmounts.length, "invalid mins"); uint256 D = totalSupply; uint256[] memory amounts = new uint256[](_balances.length); uint256 fee = redeemFee; uint256 feeAmount; if (fee > 0) { feeAmount = _amount.mul(fee).div(feeDenominator); // Redemption fee is paid with pool token // No conversion is needed as the pool token has 18 decimals IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount); _amount = _amount.sub(feeAmount); } for (uint256 i = 0; i < _balances.length; i++) { // We might choose to use poolToken.totalSupply to compute the amount, but decide to use // D in case we have multiple minters on the pool token. uint256 tokenAmount = _balances[i].mul(_amount).div(D); // Important: Underlying tokens must convert back to original decimals! amounts[i] = tokenAmount.div(precisions[i]); require(amounts[i] >= _minRedeemAmounts[i], "fewer than expected"); // Updates the balance in storage balances[i] = _balances[i].sub(tokenAmount); IERC20(tokens[i]).safeTransfer(msg.sender, amounts[i]); } totalSupply = D.sub(_amount); // After reducing the redeem fee, the remaining pool tokens are burned! IERC20MintableBurnable(poolToken).burn(msg.sender, _amount); emit Redeemed(msg.sender, _amount.add(feeAmount), amounts, feeAmount); } /** * @dev Computes the amount when redeeming pool token to one specific underlying token. * @param _amount Amount of pool token to redeem. * @param _i Index of the underlying token to redeem to. * @return Amount of underlying token that can be redeem to. */ function getRedeemSingleAmount(uint256 _amount, uint256 _i) external view returns (uint256, uint256) { uint256[] memory _balances = balances; require(_amount > 0, "zero amount"); require(_i < _balances.length, "invalid token"); uint256 A = getA(); uint256 D = totalSupply; uint256 feeAmount = 0; if (redeemFee > 0) { feeAmount = _amount.mul(redeemFee).div(feeDenominator); // Redemption fee is charged with pool token before redemption. _amount = _amount.sub(feeAmount); } // The pool token amount becomes D - _amount uint256 y = _getY(_balances, _i, D.sub(_amount), A); uint256 dy = _balances[_i].sub(y).div(precisions[_i]); return (dy, feeAmount); } /** * @dev Redeem pool token to one specific underlying token. * @param _amount Amount of pool token to redeem. * @param _i Index of the token to redeem to. * @param _minRedeemAmount Minimum amount of the underlying token to redeem to. */ function redeemSingle(uint256 _amount, uint256 _i, uint256 _minRedeemAmount) external nonReentrant { uint256[] memory _balances = balances; // If swap is paused, only admins can redeem. require(!paused || admins[msg.sender], "paused"); require(_amount > 0, "zero amount"); require(_i < _balances.length, "invalid token"); uint256 A = getA(); uint256 D = totalSupply; uint256 fee = redeemFee; uint256 feeAmount = 0; if (fee > 0) { // Redemption fee is charged with pool token before redemption. feeAmount = _amount.mul(fee).div(feeDenominator); // No conversion is needed as the pool token has 18 decimals IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount); _amount = _amount.sub(feeAmount); } // y is converted(18 decimals) uint256 y = _getY(_balances, _i, D.sub(_amount), A); // dy is not converted uint256 dy = _balances[_i].sub(y).div(precisions[_i]); require(dy >= _minRedeemAmount, "fewer than expected"); // Updates token balance in storage balances[_i] = y; uint256[] memory amounts = new uint256[](_balances.length); amounts[_i] = dy; IERC20(tokens[_i]).safeTransfer(msg.sender, dy); totalSupply = D.sub(_amount); IERC20MintableBurnable(poolToken).burn(msg.sender, _amount); emit Redeemed(msg.sender, _amount.add(feeAmount), amounts, feeAmount); } /** * @dev Compute the amount of pool token that needs to be redeemed. * @param _amounts Unconverted token balances. * @return The amount of pool token that needs to be redeemed. */ function getRedeemMultiAmount(uint256[] calldata _amounts) external view returns (uint256, uint256) { uint256[] memory _balances = balances; require(_amounts.length == balances.length, "length not match"); uint256 A = getA(); uint256 oldD = totalSupply; for (uint256 i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) continue; // balance = balance + amount * precision _balances[i] = _balances[i].sub(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be smaller than or equal to oldD uint256 redeemAmount = oldD.sub(newD); uint256 feeAmount = 0; if (redeemFee > 0) { redeemAmount = redeemAmount.mul(feeDenominator).div(feeDenominator.sub(redeemFee)); feeAmount = redeemAmount.sub(oldD.sub(newD)); } return (redeemAmount, feeAmount); } /** * @dev Redeems underlying tokens. * @param _amounts Amounts of underlying tokens to redeem to. * @param _maxRedeemAmount Maximum of pool token to redeem. */ function redeemMulti(uint256[] calldata _amounts, uint256 _maxRedeemAmount) external nonReentrant { uint256[] memory _balances = balances; require(_amounts.length == balances.length, "length not match"); // If swap is paused, only admins can redeem. require(!paused || admins[msg.sender], "paused"); uint256 A = getA(); uint256 oldD = totalSupply; uint256 i = 0; for (i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) continue; // balance = balance + amount * precision _balances[i] = _balances[i].sub(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be smaller than or equal to oldD uint256 redeemAmount = oldD.sub(newD); uint256 fee = redeemFee; uint256 feeAmount = 0; if (fee > 0) { redeemAmount = redeemAmount.mul(feeDenominator).div(feeDenominator.sub(fee)); feeAmount = redeemAmount.sub(oldD.sub(newD)); // No conversion is needed as the pool token has 18 decimals IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount); } require(redeemAmount <= _maxRedeemAmount, "more than expected"); // Updates token balances in storage. balances = _balances; uint256 burnAmount = redeemAmount.sub(feeAmount); totalSupply = oldD.sub(burnAmount); IERC20MintableBurnable(poolToken).burn(msg.sender, burnAmount); for (i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) continue; IERC20(tokens[i]).safeTransfer(msg.sender, _amounts[i]); } emit Redeemed(msg.sender, redeemAmount, _amounts, feeAmount); } /** * @dev Return the amount of fee that's not collected. */ function getPendingFeeAmount() external view returns (uint256) { uint256[] memory _balances = balances; uint256 A = getA(); uint256 oldD = totalSupply; for (uint256 i = 0; i < _balances.length; i++) { _balances[i] = IERC20(tokens[i]).balanceOf(address(this)).mul(precisions[i]); } uint256 newD = _getD(_balances, A); return newD.sub(oldD); } /** * @dev Collect fee based on the token balance difference. */ function collectFee() external returns (uint256) { require(admins[msg.sender], "not admin"); uint256[] memory _balances = balances; uint256 A = getA(); uint256 oldD = totalSupply; for (uint256 i = 0; i < _balances.length; i++) { _balances[i] = IERC20(tokens[i]).balanceOf(address(this)).mul(precisions[i]); } uint256 newD = _getD(_balances, A); uint256 feeAmount = newD.sub(oldD); if (feeAmount == 0) return 0; balances = _balances; totalSupply = newD; address _feeRecipient = feeRecipient; IERC20MintableBurnable(poolToken).mint(_feeRecipient, feeAmount); emit FeeCollected(_feeRecipient, feeAmount); return feeAmount; } /** * @dev Updates the govenance address. */ function setGovernance(address _governance) external { require(msg.sender == governance, "not governance"); governance = _governance; } /** * @dev Updates the mint fee. */ function setMintFee(uint256 _mintFee) external { require(msg.sender == governance, "not governance"); mintFee = _mintFee; } /** * @dev Updates the swap fee. */ function setSwapFee(uint256 _swapFee) external { require(msg.sender == governance, "not governance"); swapFee = _swapFee; } /** * @dev Updates the redeem fee. */ function setRedeemFee(uint256 _redeemFee) external { require(msg.sender == governance, "not governance"); redeemFee = _redeemFee; } /** * @dev Updates the recipient of mint/swap/redeem fees. */ function setFeeRecipient(address _feeRecipient) external { require(msg.sender == governance, "not governance"); require(_feeRecipient != address(0x0), "fee recipient not set"); feeRecipient = _feeRecipient; } /** * @dev Updates the pool token. */ function setPoolToken(address _poolToken) external { require(msg.sender == governance, "not governance"); require(_poolToken != address(0x0), "pool token not set"); poolToken = _poolToken; } /** * @dev Pause mint/swap/redeem actions. Can unpause later. */ function pause() external { require(msg.sender == governance, "not governance"); require(!paused, "paused"); paused = true; } /** * @dev Unpause mint/swap/redeem actions. */ function unpause() external { require(msg.sender == governance, "not governance"); require(paused, "not paused"); paused = false; } /** * @dev Updates the admin role for the address. * @param _account Address to update admin role. * @param _allowed Whether the address is granted the admin role. */ function setAdmin(address _account, bool _allowed) external { require(msg.sender == governance, "not governance"); require(_account != address(0x0), "account not set"); admins[_account] = _allowed; } }
After reducing the redeem fee, the remaining pool tokens are burned!
IERC20MintableBurnable(poolToken).burn(msg.sender, _amount);
6,812,694
[ 1, 4436, 9299, 2822, 326, 283, 24903, 14036, 16, 326, 4463, 2845, 2430, 854, 18305, 329, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 467, 654, 39, 3462, 49, 474, 429, 38, 321, 429, 12, 6011, 1345, 2934, 70, 321, 12, 3576, 18, 15330, 16, 389, 8949, 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 ]
./full_match/1/0xF895B67031670F4b2D00a08a67a7A5c80F8E829f/sources/contracts/integrationInterface/IntegrationInterface.sol
@title Protocol Integration Interface
abstract contract IntegrationInterface { @dev The function must deposit assets to the protocol. @param entryTokenAddress Token to be transfered to integration contract from caller @param entryTokenAmount Token amount to be transferes to integration contract from caller @param \ Pool/Vault address to deposit funds @param depositTokenAddress Token to be transfered to poolAddress @param minExitTokenAmount Min acceptable amount of liquidity/stake tokens to reeive @param underlyingTarget Underlying target which will execute swap @param targetDepositTokenAddress Token which will be used to deposit fund in target contract @param swapTarget Underlying target's swap target @param swapData Data for swap @param affiliate Affiliate address function deposit( address entryTokenAddress, uint256 entryTokenAmount, address, address depositTokenAddress, uint256 minExitTokenAmount, address underlyingTarget, address targetDepositTokenAddress, address swapTarget, bytes calldata swapData, address affiliate ) external payable virtual; @dev The function must withdraw assets from the protocol. @param \ Pool/Vault address @param \ Token amount to be transferes to integration contract @param exitTokenAddress Specifies the token which will be send to caller @param minExitTokenAmount Min acceptable amount of tokens to reeive @param underlyingTarget Underlying target which will execute swap @param targetWithdrawTokenAddress Token which will be used to withdraw funds from target contract @param swapTarget Underlying target's swap target @param swapData Data for swap @param affiliate Affiliate address function withdraw( address, uint256, address exitTokenAddress, uint256 minExitTokenAmount, address underlyingTarget, address targetWithdrawTokenAddress, address swapTarget, bytes calldata swapData, address affiliate ) external payable virtual; @dev Returns account balance @param \ Pool/Vault address @param account User account address @return balance Returns user current balance function getBalance(address, address account) public view virtual returns (uint256 balance); @notice Utility function to determine the quantity and address of a token being removed @param \ Pool/Vault address from which liquidity should be removed @param [Optional] Token address token to be removed @param amount Quantity of LP tokens to remove. @return The amount of token removed function removeAssetReturn( address, address, uint256 amount ) external view virtual returns (uint256); pragma solidity ^0.8.4; }
8,417,172
[ 1, 5752, 22936, 6682, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 17801, 6835, 22936, 1358, 288, 203, 225, 632, 5206, 1021, 445, 1297, 443, 1724, 7176, 358, 326, 1771, 18, 203, 225, 632, 891, 1241, 1345, 1887, 3155, 358, 506, 7412, 329, 358, 12040, 6835, 628, 4894, 203, 225, 632, 891, 1241, 1345, 6275, 3155, 3844, 358, 506, 7412, 281, 358, 12040, 6835, 628, 4894, 203, 225, 632, 891, 521, 8828, 19, 12003, 1758, 358, 443, 1724, 284, 19156, 203, 225, 632, 891, 443, 1724, 1345, 1887, 3155, 358, 506, 7412, 329, 358, 2845, 1887, 203, 225, 632, 891, 1131, 6767, 1345, 6275, 5444, 14206, 3844, 434, 4501, 372, 24237, 19, 334, 911, 2430, 358, 283, 73, 688, 203, 225, 632, 891, 6808, 2326, 21140, 6291, 1018, 1492, 903, 1836, 7720, 203, 225, 632, 891, 1018, 758, 1724, 1345, 1887, 3155, 1492, 903, 506, 1399, 358, 443, 1724, 284, 1074, 316, 1018, 6835, 203, 225, 632, 891, 7720, 2326, 21140, 6291, 1018, 1807, 7720, 1018, 203, 225, 632, 891, 7720, 751, 1910, 364, 7720, 203, 225, 632, 891, 7103, 330, 3840, 23906, 330, 3840, 1758, 7010, 203, 225, 445, 443, 1724, 12, 203, 565, 1758, 1241, 1345, 1887, 16, 203, 565, 2254, 5034, 1241, 1345, 6275, 16, 203, 565, 1758, 16, 203, 565, 1758, 443, 1724, 1345, 1887, 16, 203, 565, 2254, 5034, 1131, 6767, 1345, 6275, 16, 203, 565, 1758, 6808, 2326, 16, 203, 565, 1758, 1018, 758, 1724, 1345, 1887, 16, 203, 565, 1758, 7720, 2326, 16, 203, 565, 1731, 745, 892, 7720, 751, 16, 203, 565, 1758, 7103, 330, 3840, 203, 225, 2 ]
./partial_match/4/0x64fD3aea4Df3b76348a8cC9F2A18930fD6927738/sources/RAYv2.sol
invalid index, we didn't find a single coverage opportunity, so this will tell the process to default to its normal procedure
return opportunitiesTokenValues.length;
8,750,898
[ 1, 5387, 770, 16, 732, 10242, 1404, 1104, 279, 2202, 11196, 1061, 655, 13352, 16, 1427, 333, 903, 9276, 326, 1207, 358, 805, 358, 2097, 2212, 12131, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 377, 327, 1061, 655, 318, 1961, 1345, 1972, 18, 2469, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { //using SafeMath for uint; using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false mapping(address => uint256) private authorizedCaller; // Struct used to hold registered airlines struct Airlines { bool isRegistered; bool isFunded; uint256 funds; } mapping(address => Airlines) airlines; address[] registeredAirlines = new address[](0); // Addresses of registered AIRLINES struct Voters { bool status; } mapping(address => uint) private voteCount; mapping(address => Voters) voters; struct Insurance { bool isInsured; address airline; string flight; address passenger; uint256 amount; } struct InsuranceOwner { address[] ownerAddresses; } mapping(address => mapping(string => Insurance)) insurance; mapping(string => InsuranceOwner) insuredPassengers; mapping(address => uint256) balances; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event AuthorizedContract(address authContract); event DeauthorizedContract(address authContract); event InsureeCredited(address passenger, uint256 amount); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor() public { contractOwner = msg.sender; } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus(bool mode) external requireContractOwner { operational = mode; } /** * @dev Authorize caller */ function authorizeCaller(address contractAddress) external requireContractOwner { authorizedCaller[contractAddress] = 1; emit AuthorizedContract(contractAddress); } /** * @dev Deauthorize caller */ function deauthorizeContract(address contractAddress) external requireContractOwner { delete authorizedCaller[contractAddress]; emit DeauthorizedContract(contractAddress); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ //--------- Airline ------- // /** * @dev Register airline */ function registerAirline(address account) public requireIsOperational { // isRegistered is Always true for a registered airline // isOperational is only true when the airline has submited funding of 10 ether airlines[account] = Airlines({ isRegistered: true, isFunded: false, funds: 0 }); // add to registered airline queue setRegisteredAirlines(account); } /** * @dev Set the registered airlines */ function setRegisteredAirlines(address account) public { registeredAirlines.push(account); } /** * @dev Get the num of registered airlines */ function getNumOfRegisteredAirlines() public view requireIsOperational returns(uint){ return registeredAirlines.length; } /** * @dev Check if an airline is registered */ function isAirlineRegistered(address account) public view returns(bool) { return airlines[account].isRegistered; } /** * @dev Get airlines */ function getAirlines() public view requireIsOperational returns(address[] memory) { // address[] memory airlinesQueue; // for(uint i=0; i<registeredAirlines.length; i++) { // airlinesQueue[i] = registeredAirlines[i]; // } // return airlinesQueue; return address[](registeredAirlines); } /** * @dev Set the airlines funding */ function setAirlineFunds(address account, uint256 amount) public requireIsOperational { airlines[account].funds = airlines[account].funds.add(amount); airlines[account].isFunded = true; } /** * @dev Get airline funds */ function getAirlineFunds(address account) public view returns(uint256){ return airlines[account].funds; } /** * @dev Check if airline is funded */ function isFunded(address account) public view returns (bool) { return airlines[account].isFunded; } //--------- Votes ------- // /** * @dev Add voters */ function addVoters(address voter) public { voters[voter] = Voters({ status: true }); } /** * @dev Add voter counter */ function addVoterCounter(address airline, uint count) public { uint vote = voteCount[airline]; voteCount[airline] = vote.add(count); } /** * @dev Get the vote count */ function getVotes(address account) public view requireIsOperational returns(uint){ return voteCount[account]; } /** * @dev Reset vote count */ function resetVoteCounter(address account) external requireIsOperational{ delete voteCount[account]; } /** * @dev Get the voter status */ function getVoterStatus(address voter) public view requireIsOperational returns(bool){ return voters[voter].status; } // ------- Insurance ----- // /** * @dev Buy insurance */ function buyInsurance( string flight, address airline, address passenger, uint256 amount ) public payable requireIsOperational { insurance[passenger][flight] = Insurance({ isInsured: true, airline: airline, flight: flight, passenger: passenger, amount: amount }); // push insured passenger as insurance owner insuredPassengers[flight].ownerAddresses.push(passenger); } function getInsuredPassengers(string flight) public view requireIsOperational returns(address[]) { return insuredPassengers[flight].ownerAddresses; } /** * @dev Check passenger insurance */ function isInsured(address passenger, string flight) public view requireIsOperational returns(bool) { return insurance[passenger][flight].isInsured; } /** * @dev Withdraw insurance balance */ function withdraw(address passenger) public requireIsOperational returns(uint256) { uint256 withdraw_cash = balances[passenger]; // first delete to prevent acc draining delete balances[passenger]; // then return to users return withdraw_cash; } /** * @dev Get insurance amount */ function getInsuranceAmount( address passenger, string flight ) public view requireIsOperational returns(uint256) { return insurance[passenger][flight].amount; } /** * @dev Credit insurees */ function creditInsurees(address passenger, uint256 amount) external { balances[passenger] = amount; } /** * @dev Get passanger credit */ function getPassengerCredit(address passenger) public view requireIsOperational returns(uint256){ return balances[passenger]; } /** * @dev Get flight key */ function getFlightKey(address airline, string memory flight, uint256 timestamp) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ /* function() external payable { fund(); } */ }
* @dev Check passenger insurance/
function isInsured(address passenger, string flight) public view requireIsOperational returns(bool) { return insurance[passenger][flight].isInsured; }
12,989,623
[ 1, 1564, 1342, 14348, 2763, 295, 1359, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8048, 2055, 72, 12, 2867, 1342, 14348, 16, 533, 25187, 13, 1071, 1476, 2583, 2520, 2988, 287, 1135, 12, 6430, 13, 288, 203, 3639, 327, 2763, 295, 1359, 63, 5466, 14348, 6362, 19131, 8009, 291, 382, 2055, 72, 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 ]
./partial_match/3/0x14C7DFf4780df04D3847FC7D11ad7623e74583C8/sources/Marathon.sol
Lay ds vdv theo don vi
function getDsVDVTheoDoi(uint _doiThi) public view returns(VanDongVien [] memory) { VanDongVien[] memory result = new VanDongVien[](soLuongVdvDoiThi[_doiThi]); uint count = 0; for(uint i=0; i<dsVDV.length; i++) { if(keccak256(abi.encodePacked(dsVDV[i].doiThi)) == keccak256(abi.encodePacked(_doiThi))) { result[count] = dsVDV[i]; count++; } } return result; { if(keccak256(abi.encodePacked(dsVDV[i].doiThi)) == keccak256(abi.encodePacked(_doiThi))) { result[count] = dsVDV[i]; count++; } } return result; }
5,165,015
[ 1, 48, 528, 3780, 331, 15679, 326, 83, 2727, 13206, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2343, 87, 21544, 58, 1986, 83, 3244, 77, 12, 11890, 389, 27150, 1315, 77, 13, 1071, 1476, 1135, 12, 58, 304, 40, 932, 58, 77, 275, 5378, 3778, 13, 288, 203, 3639, 776, 304, 40, 932, 58, 77, 275, 8526, 3778, 563, 273, 394, 776, 304, 40, 932, 58, 77, 275, 8526, 12, 2048, 48, 89, 932, 58, 15679, 3244, 77, 1315, 77, 63, 67, 27150, 1315, 77, 19226, 203, 3639, 2254, 1056, 273, 374, 31, 203, 3639, 364, 12, 11890, 277, 33, 20, 31, 277, 32, 2377, 21544, 58, 18, 2469, 31, 277, 27245, 203, 3639, 288, 203, 5411, 309, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 2377, 21544, 58, 63, 77, 8009, 27150, 1315, 77, 3719, 422, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 24899, 27150, 1315, 77, 20349, 288, 203, 7734, 563, 63, 1883, 65, 273, 3780, 21544, 58, 63, 77, 15533, 203, 7734, 1056, 9904, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 563, 31, 203, 3639, 288, 203, 5411, 309, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 2377, 21544, 58, 63, 77, 8009, 27150, 1315, 77, 3719, 422, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 24899, 27150, 1315, 77, 20349, 288, 203, 7734, 563, 63, 1883, 65, 273, 3780, 21544, 58, 63, 77, 15533, 203, 7734, 1056, 9904, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 563, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100 ]
/* ==================================================================== */ /* Copyright (c) 2018 The CryptoRacing Project. All rights reserved. /* /* The first idle car race game of blockchain /* ==================================================================== */ pragma solidity ^0.4.20; /// @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 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) external; function safeTransferFrom(address _from, address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function approve(address _approved, uint256 _tokenId) external; 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); } contract AccessAdmin { bool public isPaused = false; address public addrAdmin; event AdminTransferred(address indexed preAdmin, address indexed newAdmin); function AccessAdmin() public { addrAdmin = msg.sender; } modifier onlyAdmin() { require(msg.sender == addrAdmin); _; } modifier whenNotPaused() { require(!isPaused); _; } modifier whenPaused { require(isPaused); _; } function setAdmin(address _newAdmin) external onlyAdmin { require(_newAdmin != address(0)); AdminTransferred(addrAdmin, _newAdmin); addrAdmin = _newAdmin; } function doPause() external onlyAdmin whenNotPaused { isPaused = true; } function doUnpause() external onlyAdmin whenPaused { isPaused = false; } } contract AccessService is AccessAdmin { address public addrService; address public addrFinance; modifier onlyService() { require(msg.sender == addrService); _; } modifier onlyFinance() { require(msg.sender == addrFinance); _; } function setService(address _newService) external { require(msg.sender == addrService || msg.sender == addrAdmin); require(_newService != address(0)); addrService = _newService; } function setFinance(address _newFinance) external { require(msg.sender == addrFinance || msg.sender == addrAdmin); require(_newFinance != address(0)); addrFinance = _newFinance; } } /* ==================================================================== */ /* equipmentId /* 10001 T1 /* 10002 T2 /* 10003 T3 /* 10004 T4 /* 10005 T5 /* 10006 T6 /* 10007 freeCar /* ==================================================================== */ contract RaceToken is ERC721, AccessAdmin { /// @dev The equipment info struct Fashion { uint16 equipmentId; // 0 Equipment ID uint16 quality; // 1 Rarity: 1 Coarse/2 Good/3 Rare/4 Epic/5 Legendary uint16 pos; // 2 Slots: 1 Engine/2 Turbine/3 BodySystem/4 Pipe/5 Suspension/6 NO2/7 Tyre/8 Transmission/9 Car uint16 production; // 3 Race bonus productivity uint16 attack; // 4 Attack uint16 defense; // 5 Defense uint16 plunder; // 6 Plunder uint16 productionMultiplier; // 7 Percent value uint16 attackMultiplier; // 8 Percent value uint16 defenseMultiplier; // 9 Percent value uint16 plunderMultiplier; // 10 Percent value uint16 level; // 11 level uint16 isPercent; // 12 Percent value } /// @dev All equipments tokenArray (not exceeding 2^32-1) Fashion[] public fashionArray; /// @dev Amount of tokens destroyed uint256 destroyFashionCount; /// @dev Equipment token ID belong to owner address mapping (uint256 => address) fashionIdToOwner; /// @dev Equipments owner by the owner (array) mapping (address => uint256[]) ownerToFashionArray; /// @dev Equipment token ID search in owner array mapping (uint256 => uint256) fashionIdToOwnerIndex; /// @dev The authorized address for each Race mapping (uint256 => address) fashionIdToApprovals; /// @dev The authorized operators for each address mapping (address => mapping (address => bool)) operatorToApprovals; /// @dev Trust contract mapping (address => bool) actionContracts; //设置可调用当前合约的其他合约 function setActionContract(address _actionAddr, bool _useful) external onlyAdmin { actionContracts[_actionAddr] = _useful; } function getActionContract(address _actionAddr) external view onlyAdmin returns(bool) { return actionContracts[_actionAddr]; } /// @dev This emits when the approved address for an Race is changed or reaffirmed. event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @dev This emits when the equipment ownership changed event Transfer(address indexed from, address indexed to, uint256 tokenId); /// @dev This emits when the equipment created event CreateFashion(address indexed owner, uint256 tokenId, uint16 equipmentId, uint16 quality, uint16 pos, uint16 level, uint16 createType); /// @dev This emits when the equipment's attributes changed event ChangeFashion(address indexed owner, uint256 tokenId, uint16 changeType); /// @dev This emits when the equipment destroyed event DeleteFashion(address indexed owner, uint256 tokenId, uint16 deleteType); function RaceToken() public { addrAdmin = msg.sender; fashionArray.length += 1; } // modifier /// @dev Check if token ID is valid modifier isValidToken(uint256 _tokenId) { require(_tokenId >= 1 && _tokenId <= fashionArray.length); require(fashionIdToOwner[_tokenId] != address(0)); _; } modifier canTransfer(uint256 _tokenId) { address owner = fashionIdToOwner[_tokenId]; require(msg.sender == owner || msg.sender == fashionIdToApprovals[_tokenId] || operatorToApprovals[owner][msg.sender]); _; } // ERC721 function supportsInterface(bytes4 _interfaceId) external view returns(bool) { // ERC165 || ERC721 || ERC165^ERC721 return (_interfaceId == 0x01ffc9a7 || _interfaceId == 0x80ac58cd || _interfaceId == 0x8153916a) && (_interfaceId != 0xffffffff); } function name() public pure returns(string) { return "Race Token"; } function symbol() public pure returns(string) { return "Race"; } /// @dev Search for token quantity address /// @param _owner Address that needs to be searched /// @return Returns token quantity function balanceOf(address _owner) external view returns(uint256) { require(_owner != address(0)); return ownerToFashionArray[_owner].length; } /// @dev Find the owner of an Race /// @param _tokenId The tokenId of Race /// @return Give The address of the owner of this Race function ownerOf(uint256 _tokenId) external view /*isValidToken(_tokenId)*/ returns (address owner) { return fashionIdToOwner[_tokenId]; } /// @dev Transfers the ownership of an Race from one address to another address /// @param _from The current owner of the Race /// @param _to The new owner /// @param _tokenId The Race 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) external whenNotPaused { _safeTransferFrom(_from, _to, _tokenId, data); } /// @dev Transfers the ownership of an Race from one address to another address /// @param _from The current owner of the Race /// @param _to The new owner /// @param _tokenId The Race to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused { _safeTransferFrom(_from, _to, _tokenId, ""); } /// @dev Transfer ownership of an Race, '_to' must be a vaild address, or the Race will lost /// @param _from The current owner of the Race /// @param _to The new owner /// @param _tokenId The Race to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused isValidToken(_tokenId) canTransfer(_tokenId) { address owner = fashionIdToOwner[_tokenId]; require(owner != address(0)); require(_to != address(0)); require(owner == _from); _transfer(_from, _to, _tokenId); } /// @dev Set or reaffirm the approved address for an Race /// @param _approved The new approved Race controller /// @param _tokenId The Race to approve function approve(address _approved, uint256 _tokenId) external whenNotPaused { address owner = fashionIdToOwner[_tokenId]; require(owner != address(0)); require(msg.sender == owner || operatorToApprovals[owner][msg.sender]); fashionIdToApprovals[_tokenId] = _approved; Approval(owner, _approved, _tokenId); } /// @dev Enable or disable approval for a third party ("operator") to manage all your asset. /// @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 whenNotPaused { operatorToApprovals[msg.sender][_operator] = _approved; ApprovalForAll(msg.sender, _operator, _approved); } /// @dev Get the approved address for a single Race /// @param _tokenId The Race to find the approved address for /// @return The approved address for this Race, or the zero address if there is none function getApproved(uint256 _tokenId) external view isValidToken(_tokenId) returns (address) { return fashionIdToApprovals[_tokenId]; } /// @dev Query if an address is an authorized operator for another address /// @param _owner The address that owns the Races /// @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 operatorToApprovals[_owner][_operator]; } /// @dev Count Races tracked by this contract /// @return A count of valid Races tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address function totalSupply() external view returns (uint256) { return fashionArray.length - destroyFashionCount - 1; } /// @dev Do the real transfer with out any condition checking /// @param _from The old owner of this Race(If created: 0x0) /// @param _to The new owner of this Race /// @param _tokenId The tokenId of the Race function _transfer(address _from, address _to, uint256 _tokenId) internal { if (_from != address(0)) { uint256 indexFrom = fashionIdToOwnerIndex[_tokenId]; uint256[] storage fsArray = ownerToFashionArray[_from]; require(fsArray[indexFrom] == _tokenId); // If the Race is not the element of array, change it to with the last if (indexFrom != fsArray.length - 1) { uint256 lastTokenId = fsArray[fsArray.length - 1]; fsArray[indexFrom] = lastTokenId; fashionIdToOwnerIndex[lastTokenId] = indexFrom; } fsArray.length -= 1; if (fashionIdToApprovals[_tokenId] != address(0)) { delete fashionIdToApprovals[_tokenId]; } } // Give the Race to '_to' fashionIdToOwner[_tokenId] = _to; ownerToFashionArray[_to].push(_tokenId); fashionIdToOwnerIndex[_tokenId] = ownerToFashionArray[_to].length - 1; Transfer(_from != address(0) ? _from : this, _to, _tokenId); } /// @dev Actually perform the safeTransferFrom function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) internal isValidToken(_tokenId) canTransfer(_tokenId) { address owner = fashionIdToOwner[_tokenId]; require(owner != address(0)); require(_to != address(0)); require(owner == _from); _transfer(_from, _to, _tokenId); // 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); // bytes4(keccak256("onERC721Received(address,uint256,bytes)")) = 0xf0b9e5ba; require(retval == 0xf0b9e5ba); } //---------------------------------------------------------------------------------------------------------- /// @dev Equipment creation /// @param _owner Owner of the equipment created /// @param _attrs Attributes of the equipment created /// @return Token ID of the equipment created function createFashion(address _owner, uint16[13] _attrs, uint16 _createType) external whenNotPaused returns(uint256) { require(actionContracts[msg.sender]); require(_owner != address(0)); uint256 newFashionId = fashionArray.length; require(newFashionId < 4294967296); fashionArray.length += 1; Fashion storage fs = fashionArray[newFashionId]; fs.equipmentId = _attrs[0]; fs.quality = _attrs[1]; fs.pos = _attrs[2]; if (_attrs[3] != 0) { fs.production = _attrs[3]; } if (_attrs[4] != 0) { fs.attack = _attrs[4]; } if (_attrs[5] != 0) { fs.defense = _attrs[5]; } if (_attrs[6] != 0) { fs.plunder = _attrs[6]; } if (_attrs[7] != 0) { fs.productionMultiplier = _attrs[7]; } if (_attrs[8] != 0) { fs.attackMultiplier = _attrs[8]; } if (_attrs[9] != 0) { fs.defenseMultiplier = _attrs[9]; } if (_attrs[10] != 0) { fs.plunderMultiplier = _attrs[10]; } if (_attrs[11] != 0) { fs.level = _attrs[11]; } if (_attrs[12] != 0) { fs.isPercent = _attrs[12]; } _transfer(0, _owner, newFashionId); CreateFashion(_owner, newFashionId, _attrs[0], _attrs[1], _attrs[2], _attrs[11], _createType); return newFashionId; } /// @dev One specific attribute of the equipment modified function _changeAttrByIndex(Fashion storage _fs, uint16 _index, uint16 _val) internal { if (_index == 3) { _fs.production = _val; } else if(_index == 4) { _fs.attack = _val; } else if(_index == 5) { _fs.defense = _val; } else if(_index == 6) { _fs.plunder = _val; }else if(_index == 7) { _fs.productionMultiplier = _val; }else if(_index == 8) { _fs.attackMultiplier = _val; }else if(_index == 9) { _fs.defenseMultiplier = _val; }else if(_index == 10) { _fs.plunderMultiplier = _val; } else if(_index == 11) { _fs.level = _val; } } /// @dev Equiment attributes modified (max 4 stats modified) /// @param _tokenId Equipment Token ID /// @param _idxArray Stats order that must be modified /// @param _params Stat value that must be modified /// @param _changeType Modification type such as enhance, socket, etc. function changeFashionAttr(uint256 _tokenId, uint16[4] _idxArray, uint16[4] _params, uint16 _changeType) external whenNotPaused isValidToken(_tokenId) { require(actionContracts[msg.sender]); Fashion storage fs = fashionArray[_tokenId]; if (_idxArray[0] > 0) { _changeAttrByIndex(fs, _idxArray[0], _params[0]); } if (_idxArray[1] > 0) { _changeAttrByIndex(fs, _idxArray[1], _params[1]); } if (_idxArray[2] > 0) { _changeAttrByIndex(fs, _idxArray[2], _params[2]); } if (_idxArray[3] > 0) { _changeAttrByIndex(fs, _idxArray[3], _params[3]); } ChangeFashion(fashionIdToOwner[_tokenId], _tokenId, _changeType); } /// @dev Equipment destruction /// @param _tokenId Equipment Token ID /// @param _deleteType Destruction type, such as craft function destroyFashion(uint256 _tokenId, uint16 _deleteType) external whenNotPaused isValidToken(_tokenId) { require(actionContracts[msg.sender]); address _from = fashionIdToOwner[_tokenId]; uint256 indexFrom = fashionIdToOwnerIndex[_tokenId]; uint256[] storage fsArray = ownerToFashionArray[_from]; require(fsArray[indexFrom] == _tokenId); if (indexFrom != fsArray.length - 1) { uint256 lastTokenId = fsArray[fsArray.length - 1]; fsArray[indexFrom] = lastTokenId; fashionIdToOwnerIndex[lastTokenId] = indexFrom; } fsArray.length -= 1; fashionIdToOwner[_tokenId] = address(0); delete fashionIdToOwnerIndex[_tokenId]; destroyFashionCount += 1; Transfer(_from, 0, _tokenId); DeleteFashion(_from, _tokenId, _deleteType); } /// @dev Safe transfer by trust contracts function safeTransferByContract(uint256 _tokenId, address _to) external whenNotPaused { require(actionContracts[msg.sender]); require(_tokenId >= 1 && _tokenId <= fashionArray.length); address owner = fashionIdToOwner[_tokenId]; require(owner != address(0)); require(_to != address(0)); require(owner != _to); _transfer(owner, _to, _tokenId); } //---------------------------------------------------------------------------------------------------------- //查看单一部件属性 /// @dev Get fashion attrs by tokenId function getFashion(uint256 _tokenId) external view isValidToken(_tokenId) returns (uint16[13] datas) { Fashion storage fs = fashionArray[_tokenId]; datas[0] = fs.equipmentId; datas[1] = fs.quality; datas[2] = fs.pos; datas[3] = fs.production; datas[4] = fs.attack; datas[5] = fs.defense; datas[6] = fs.plunder; datas[7] = fs.productionMultiplier; datas[8] = fs.attackMultiplier; datas[9] = fs.defenseMultiplier; datas[10] = fs.plunderMultiplier; datas[11] = fs.level; datas[12] = fs.isPercent; } //单个玩家获得当前所有tokenid和标记 /// @dev Get tokenIds and flags by owner function getOwnFashions(address _owner) external view returns(uint256[] tokens, uint32[] flags) { require(_owner != address(0)); uint256[] storage fsArray = ownerToFashionArray[_owner]; uint256 length = fsArray.length; tokens = new uint256[](length); flags = new uint32[](length); for (uint256 i = 0; i < length; ++i) { tokens[i] = fsArray[i]; Fashion storage fs = fashionArray[fsArray[i]]; flags[i] = uint32(uint32(fs.equipmentId) * 100 + uint32(fs.quality) * 10 + fs.pos); } } /// @dev Race token info returned based on Token ID transfered (64 at most) function getFashionsAttrs(uint256[] _tokens) external view returns(uint16[] attrs) { uint256 length = _tokens.length; require(length <= 64); attrs = new uint16[](length * 13); uint256 tokenId; uint256 index; for (uint256 i = 0; i < length; ++i) { tokenId = _tokens[i]; if (fashionIdToOwner[tokenId] != address(0)) { index = i * 13; Fashion storage fs = fashionArray[tokenId]; attrs[index] = fs.equipmentId; attrs[index + 1] = fs.quality; attrs[index + 2] = fs.pos; attrs[index + 3] = fs.production; attrs[index + 4] = fs.attack; attrs[index + 5] = fs.defense; attrs[index + 6] = fs.plunder; attrs[index + 7] = fs.productionMultiplier; attrs[index + 8] = fs.attackMultiplier; attrs[index + 9] = fs.defenseMultiplier; attrs[index + 10] = fs.plunderMultiplier; attrs[index + 11] = fs.level; attrs[index + 12] = fs.isPercent; } } } } //Tournament bonus interface interface IRaceCoin { function addTotalEtherPool(uint256 amount) external; function addPlayerToList(address player) external; function increasePlayersAttribute(address player, uint16[13] param) external; function reducePlayersAttribute(address player, uint16[13] param) external; } contract CarsPresell is AccessService { using SafeMath for uint256; RaceToken tokenContract; IRaceCoin public raceCoinContract; //Bonus pool address address poolContract; ///Bonus pool ratio uint256 constant prizeGoldPercent = 80; //referer uint256 constant refererPercent = 5; //The maximum number of cars per quality uint16 private carCountsLimit; mapping (uint16 => uint16) carPresellCounter; mapping (address => uint16[]) presellLimit; mapping (address => uint16) freeCarCount; event CarPreSelled(address indexed buyer, uint16 equipmentId); event FreeCarsObtained(address indexed buyer, uint16 equipmentId); event PresellReferalGain(address referal, address player, uint256 amount); function CarsPresell(address _nftAddr) public { addrAdmin = msg.sender; addrService = msg.sender; addrFinance = msg.sender; tokenContract = RaceToken(_nftAddr); //Maximum number of vehicles per class carCountsLimit = 500; carPresellCounter[10001] = 100; carPresellCounter[10002] = 100; carPresellCounter[10003] = 100; carPresellCounter[10004] = 100; carPresellCounter[10005] = 100; carPresellCounter[10006] = 100; } function() external payable { } function setRaceTokenAddr(address _nftAddr) external onlyAdmin { tokenContract = RaceToken(_nftAddr); } //Set up tournament bonus address function setRaceCoin(address _addr) external onlyAdmin { require(_addr != address(0)); poolContract = _addr; raceCoinContract = IRaceCoin(_addr); } //Increase the number of pre-sale cars, the maximum limit of each vehicle is 500 vehicles. function setCarCounts(uint16 _carId, uint16 _carCounts) external onlyAdmin { require( carPresellCounter[_carId] <= carCountsLimit); uint16 curSupply = carPresellCounter[_carId]; require((curSupply + _carCounts)<= carCountsLimit); carPresellCounter[_carId] = curSupply + _carCounts; } //Get free cars function freeCar(uint16 _equipmentId) external payable whenNotPaused { require(freeCarCount[msg.sender] != 1); uint256 payBack = 0; uint16[] storage buyArray = presellLimit[msg.sender]; if(_equipmentId == 10007){ require(msg.value >= 0.0 ether); payBack = (msg.value - 0.0 ether); uint16[13] memory param0 = [10007, 7, 9, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]; tokenContract.createFashion(msg.sender, param0, 1); raceCoinContract.increasePlayersAttribute(msg.sender, param0); buyArray.push(10007); if (payBack > 0) { msg.sender.transfer(payBack); } freeCarCount[msg.sender] = 1; raceCoinContract.addPlayerToList(msg.sender); FreeCarsObtained(msg.sender,_equipmentId); } } //Whether a free car has been received. function getFreeCarCount(address _owner) external view returns(uint16){ require(_owner != address(0)); if(freeCarCount[msg.sender] != 1){ freeCarCount[msg.sender] = 0; } return freeCarCount[msg.sender]; } function UpdateCurrentCarCount(uint16 _equipmentId,uint16 curSupply) internal { carPresellCounter[_equipmentId] = (curSupply - 1); } function carPresell(address referer,uint16 _equipmentId) external payable whenNotPaused { uint16 curSupply = carPresellCounter[_equipmentId]; require(curSupply > 0); uint16[] storage buyArray = presellLimit[msg.sender]; uint256 curBuyCnt = buyArray.length; require(curBuyCnt < 10); uint256 payBack = 0; if (_equipmentId == 10001) { require(msg.value >= 0.075 ether); payBack = (msg.value - 0.075 ether); uint16[13] memory param1 = [10001, 1, 9, 10, 0, 0, 0, 10, 0, 0, 0, 0, 0]; // 10 productivity 10% productivity plus tokenContract.createFashion(msg.sender, param1, 1); raceCoinContract.increasePlayersAttribute(msg.sender, param1); buyArray.push(10001); raceCoinContract.addPlayerToList(msg.sender); } else if(_equipmentId == 10002) { require(msg.value >= 0.112 ether); payBack = (msg.value - 0.112 ether); uint16[13] memory param2 = [10002, 2, 9, 15, 0, 0, 0, 15, 5, 0, 0, 0, 0]; // 15 productivity 15% productivity plus 5% attack bonus tokenContract.createFashion(msg.sender, param2, 1); raceCoinContract.increasePlayersAttribute(msg.sender, param2); buyArray.push(10002); raceCoinContract.addPlayerToList(msg.sender); } else if(_equipmentId == 10003) { require(msg.value >= 0.225 ether); payBack = (msg.value - 0.225 ether); uint16[13] memory param3 = [10003, 3, 9, 30, 0, 0, 0, 20, 10, 5, 0, 0, 0]; // 30 productivity 20% productivity plus 10% attack plus 5% defense plus tokenContract.createFashion(msg.sender, param3, 1); raceCoinContract.increasePlayersAttribute(msg.sender, param3); buyArray.push(10003); raceCoinContract.addPlayerToList(msg.sender); } else if(_equipmentId == 10004) { require(msg.value >= 0.563 ether); payBack = (msg.value - 0.563 ether); uint16[13] memory param4 = [10004, 4, 9, 75, 0, 0, 0, 25, 15, 10, 5, 0, 0]; // 75 productivity 25% productivity plus 15% attack plus 10% defense plus 5% predatory addition. tokenContract.createFashion(msg.sender, param4, 1); raceCoinContract.increasePlayersAttribute(msg.sender, param4); buyArray.push(10004); raceCoinContract.addPlayerToList(msg.sender); } else if(_equipmentId == 10005){ require(msg.value >= 1.7 ether); payBack = (msg.value - 1.7 ether); uint16[13] memory param5 = [10005, 5, 9, 225, 0, 0, 0, 30, 20, 15, 10, 0, 0]; // 225 productivity 30% productivity plus 20% attack plus 15% defense plus 10% predatory addition. tokenContract.createFashion(msg.sender, param5, 1); raceCoinContract.increasePlayersAttribute(msg.sender, param5); buyArray.push(10005); raceCoinContract.addPlayerToList(msg.sender); }else if(_equipmentId == 10006){ require(msg.value >= 6 ether); payBack = (msg.value - 6 ether); uint16[13] memory param6 = [10006, 6, 9, 788, 0, 0, 0, 35, 25, 20, 15, 0, 0]; // 788 productivity 35% productivity plus 25% attack plus 20% defense plus 15% predatory addition. tokenContract.createFashion(msg.sender, param6, 1); raceCoinContract.increasePlayersAttribute(msg.sender, param6); buyArray.push(10006); raceCoinContract.addPlayerToList(msg.sender); } UpdateCurrentCarCount(_equipmentId,curSupply); CarPreSelled(msg.sender, _equipmentId); uint256 ethVal = msg.value.sub(payBack); uint256 referalDivs; if (referer != address(0) && referer != msg.sender) { referalDivs = ethVal.mul(refererPercent).div(100); // 5% referer.transfer(referalDivs); emit PresellReferalGain(referer, msg.sender, referalDivs); } //Capital injection into capital pool if (poolContract != address(0) && ethVal.mul(prizeGoldPercent).div(100) > 0) { poolContract.transfer(ethVal.mul(prizeGoldPercent).div(100)); raceCoinContract.addTotalEtherPool(ethVal.mul(prizeGoldPercent).div(100)); } //The rest of the account is entered into the developer account. if(referalDivs > 0){ addrFinance.transfer(ethVal.sub(ethVal.mul(prizeGoldPercent).div(100)).sub(ethVal.mul(refererPercent).div(100))); }else{ addrFinance.transfer(ethVal.sub(ethVal.mul(prizeGoldPercent).div(100))); } if (payBack > 0) { msg.sender.transfer(payBack); } } function withdraw() external { require(msg.sender == addrFinance || msg.sender == addrAdmin); addrFinance.transfer(this.balance); } function getCarCanPresellCount() external view returns (uint16[6] cntArray) { cntArray[0] = carPresellCounter[10001]; cntArray[1] = carPresellCounter[10002]; cntArray[2] = carPresellCounter[10003]; cntArray[3] = carPresellCounter[10004]; cntArray[4] = carPresellCounter[10005]; cntArray[5] = carPresellCounter[10006]; } function getBuyCount(address _owner) external view returns (uint32) { return uint32(presellLimit[_owner].length); } function getBuyArray(address _owner) external view returns (uint16[]) { uint16[] storage buyArray = presellLimit[_owner]; return buyArray; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
Maximum number of vehicles per class
function CarsPresell(address _nftAddr) public { addrAdmin = msg.sender; addrService = msg.sender; addrFinance = msg.sender; tokenContract = RaceToken(_nftAddr); carCountsLimit = 500; carPresellCounter[10001] = 100; carPresellCounter[10002] = 100; carPresellCounter[10003] = 100; carPresellCounter[10004] = 100; carPresellCounter[10005] = 100; carPresellCounter[10006] = 100; }
5,406,374
[ 1, 13528, 1300, 434, 10489, 76, 8383, 1534, 667, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 385, 5913, 12236, 1165, 12, 2867, 389, 82, 1222, 3178, 13, 1071, 288, 203, 3639, 3091, 4446, 273, 1234, 18, 15330, 31, 203, 3639, 3091, 1179, 273, 1234, 18, 15330, 31, 203, 3639, 3091, 6187, 1359, 273, 1234, 18, 15330, 31, 203, 203, 3639, 1147, 8924, 273, 534, 623, 1345, 24899, 82, 1222, 3178, 1769, 203, 1082, 203, 202, 202, 9815, 9211, 3039, 273, 6604, 31, 203, 203, 3639, 5926, 12236, 1165, 4789, 63, 6625, 1611, 65, 273, 2130, 31, 203, 3639, 5926, 12236, 1165, 4789, 63, 6625, 3103, 65, 273, 2130, 31, 203, 3639, 5926, 12236, 1165, 4789, 63, 18088, 23, 65, 273, 2130, 31, 203, 3639, 5926, 12236, 1165, 4789, 63, 6625, 3028, 65, 273, 2130, 31, 203, 3639, 5926, 12236, 1165, 4789, 63, 18088, 25, 65, 273, 2130, 31, 203, 202, 202, 9815, 12236, 1165, 4789, 63, 18088, 26, 65, 273, 2130, 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 ]
/** */ /* */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; interface IERC20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function symbol() external view returns (string memory); function name() external view returns (string memory); function getOwner() external view returns (address); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address _owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface IuniswapERC20 { 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; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Router01 { function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function factory() external pure returns (address); function WETH() external pure returns (address); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getamountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getamountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getamountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getamountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface 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; } /** * @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 { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = msg.sender; _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() == msg.sender, "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 onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = 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) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } ///////////////////////////////////Chartoken Contract //////////////////////////////////// contract Chartoken is IERC20, Ownable { using Address for address; using EnumerableSet for EnumerableSet.AddressSet; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => uint256) private _sellLock; mapping (address => bool) private _NoPlatinumHolder; EnumerableSet.AddressSet private _excluded; EnumerableSet.AddressSet private _whiteList; EnumerableSet.AddressSet private _excludedFromSellLock; EnumerableSet.AddressSet private _excludedFromStaking; //Token Info string private constant _name = 'Chartoken'; string private constant _symbol = 'CHR'; uint8 private constant _decimals = 18; uint256 public constant _totalSupply= 100000000000 * 10**_decimals; // equals 100.000.000.000 //BotProtection values bool private _botProtection; uint8 constant BotMaxTax=50; uint256 constant BotTaxTime=3 minutes; uint256 public launchTimestamp; uint8 private constant _whiteListBonus=0; //Divider for the Minimal MaxBalance based on circulating Supply (1.0% during start, will be switched to 2.0% once normal tax level is reached) uint8 public constant BalanceLimitDivider=100; //Divider for Minimal sellLimit based on circulating Supply (No sell limit. Never.) uint16 public constant SellLimitDivider=1; //Sellers get locked for MaxSellLockTime so they can't dump repeatedly (No sell lock) uint16 public constant MaxSellLockTime= 0 hours; //The time Liquidity gets locked at start and prolonged once it gets released uint256 private constant DefaultLiquidityLockTime=30 days; //Limits max tax, only gets applied for tax changes, doesn't affect inital Tax uint8 public constant MaxTax=14; //Tracks the current Taxes, different Taxes can be applied for buy/sell/transfer uint8 private _liquidityTax; uint8 private _stakingTax; uint8 private _buyTax; uint8 private _sellTax; uint8 private _transferTax; //Team Wallet address public constant TeamWallet=0xD4f864dcAC6C813C0521A739c9a978E3f9A94776; //MainNet and Testnet identical router address address private constant UniswapRouter=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //variables that track balanceLimit and sellLimit, //can be updated based on circulating supply and Sell- and BalanceLimitDividers uint256 public balanceLimit; uint256 public sellLimit; address private _uniswapPairAddress; IUniswapV2Router02 private _uniswapRouter; //modifier for functions only the team can call modifier onlyTeam() { require(_isTeam(msg.sender), "Caller not in Team"); _; } //Checks if address is in Team, is needed to give Team access even if contract is renounced //Team doesn't have access to critical Functions that could turn this into a Rugpull(Exept liquidity unlocks) function _isTeam(address addr) private view returns (bool){ return addr==owner()||addr==TeamWallet; } /////////////////////////////////////////Constructor//////////////////////////////////// constructor () { // uniswap Router _uniswapRouter = IUniswapV2Router02(UniswapRouter); //Creates a uniswap Pair _uniswapPairAddress = IUniswapV2Factory(_uniswapRouter.factory()).createPair(address(this), _uniswapRouter.WETH()); //excludes uniswap Router, pair, contract and burn address from staking _excludedFromStaking.add(address(this)); _excludedFromStaking.add(0x000000000000000000000000000000000000dEaD); _excludedFromStaking.add(address(_uniswapRouter)); _excludedFromStaking.add(_uniswapPairAddress); _addToken(address(this),_totalSupply); emit Transfer(address(0), address(this), _totalSupply); //Sets Buy/Sell limits sellLimit=_totalSupply/SellLimitDivider; balanceLimit=_totalSupply/BalanceLimitDivider; //Limits start disabled sellLockDisabled=true; //Sets sellLockTime to be max by default sellLockTime=MaxSellLockTime; _transferTax=14; _buyTax=14; _sellTax=14; //100% of the tax goes to Liquidity at start to generate a lot of liquidity during //bot Protection _stakingTax=0; _liquidityTax=100; //Team wallet and deployer are excluded from Taxes _excluded.add(msg.sender); _excluded.add(TeamWallet); } //////////////////////////////////Transfer functionality//////////////////////////////////////// //Address that is excluded for one transaction address private oneTimeExcluded; //transfer function, every transfer runs through this function function _transfer(address sender, address recipient, uint256 amount) private{ require(sender != address(0), "Transfer from zero"); require(recipient != address(0), "Transfer to zero"); //Manually Excluded addresses are transfering tax and lock free bool isExcluded = (_excluded.contains(sender) || _excluded.contains(recipient)); if(oneTimeExcluded==recipient){ oneTimeExcluded=address(0); isExcluded=true; } //Transactions from and to the contract are always tax and lock free bool isContractTransfer=(sender==address(this) || recipient==address(this)); //transfers between uniswapRouter and uniswapPair are tax and lock free address uniswapRouter=address(_uniswapRouter); bool isLiquidityTransfer = ((sender == _uniswapPairAddress && recipient == uniswapRouter) || (recipient == _uniswapPairAddress && sender == uniswapRouter)); //differentiate between buy/sell/transfer to apply different taxes/restrictions bool isSell=recipient==_uniswapPairAddress|| recipient == uniswapRouter; bool isBuy=sender==_uniswapPairAddress|| sender == uniswapRouter; //Pick transfer if(isContractTransfer || isLiquidityTransfer || isExcluded){ _feelessTransfer(sender, recipient, amount); } else{ //once trading is enabled, it can't be turned off again require(tradingEnabled,"trading not yet enabled"); _taxedTransfer(sender,recipient,amount,isBuy,isSell); } } //applies taxes, checks for limits, locks generates autoLP and stakingETH, and autostakes function _taxedTransfer(address sender, address recipient, uint256 amount,bool isBuy,bool isSell) private{ uint256 recipientBalance = _balances[recipient]; uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); uint8 tax; if(isSell){ if(!sellLockDisabled&&!_excludedFromSellLock.contains(sender)){ require(_sellLock[sender]<=block.timestamp,"Seller in sellLock"); //Sets the time sellers get locked(no sell lock implemented) _sellLock[sender]=block.timestamp+sellLockTime; //Sells can't exceed the sell limit(no sell limit implemented) require(amount<=sellLimit,"Dump protection"); } //As soon a holder sells, PlatinumHolder function is gone and can never be reached again _NoPlatinumHolder[sender]=true; tax=_sellTax; } else if(isBuy){ //Checks If the recipient balance(excluding Taxes) would exceed Balance Limit require(recipientBalance+amount<=balanceLimit,"whale protection"); tax=_getBuyTax(recipient); } else {//Transfer //withdraws ETH when sending less or equal to 1 Token //that way you can withdraw without connecting to any dApp. //You might need higher gas limit if(amount<=10**(_decimals)) claimToken(msg.sender ,address(this),0); //Checks If the recipient balance(excluding Taxes) would exceed Balance Limit require(recipientBalance+amount<=balanceLimit,"whale protection"); //Transfers are disabled in sell lock, this doesn't stop someone from transfering before //selling, but there is no satisfying solution for that, and you would need to pax additional tax if(!_excludedFromSellLock.contains(sender)) require(_sellLock[sender]<=block.timestamp||sellLockDisabled,"Sender in Lock"); tax=_transferTax; } //Swapping AutoLP and MarketingETH is only possible if sender is not uniswap pair, //if it's not manually disabled, if its not already swapping and if it's a sell to avoid // people from causing a large price impact from repeatedly transferring when there's a large backlog of tokens if((sender!=_uniswapPairAddress)&&(!manualConversion)&&(!_isSwappingContractModifier)&&isSell) _swapContractToken(AutoLPThreshold,false); //Calculates the exact token amount for each tax //staking and liquidity Tax get treated the same, only during conversion they get split uint256 contractToken=_calculateFee(amount, tax, _stakingTax+_liquidityTax); //Subtract the Taxed Tokens from the amount uint256 taxedAmount=amount-contractToken; //Removes token and handles staking _removeToken(sender,amount); //Adds the taxed tokens to the contract wallet _addToken(address(this), contractToken); //Adds token and handles staking _addToken(recipient, taxedAmount); emit Transfer(sender,recipient,taxedAmount); } function _getBuyTax(address recipient) private returns (uint8) { if(!_botProtection) return _buyTax; if(block.timestamp<(launchTimestamp+BotTaxTime)){ uint8 tax=_calculateLaunchTax(); if(_whiteList.contains(recipient)){ if(tax<(_buyTax+_whiteListBonus)) tax=_buyTax; else tax-=_whiteListBonus; } return tax; } _botProtection=false; _liquidityTax=21; _stakingTax=79; return _buyTax; } //Calculates the buy tax right after launch function _calculateLaunchTax() private view returns (uint8){ if(block.timestamp>launchTimestamp+BotTaxTime) return _buyTax; uint256 timeSinceLaunch=block.timestamp-launchTimestamp; uint8 Tax=uint8(BotMaxTax-((BotMaxTax-_buyTax)*timeSinceLaunch/BotTaxTime)); return Tax; } //Feeless transfer only transfers and autostakes function _feelessTransfer(address sender, address recipient, uint256 amount) private{ uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); //Removes token and handles staking _removeToken(sender,amount); //Adds token and handles staking _addToken(recipient, amount); emit Transfer(sender,recipient,amount); } //Calculates the tokens that should be taxed function _calculateFee(uint256 amount, uint8 tax, uint8 taxPercent) private pure returns (uint256) { return (amount*tax*taxPercent) / 10000; } ///////////////////////////////////////ETH Autostake/////////////////////////////////// //Autostake uses the balances of each holder to redistribute auto generated ETH. //Each transaction _addToken and _removeToken gets called for the transaction amount //WithdrawETH can be used for any holder to withdraw ETH at any time, like true Staking //lock for the withdraw bool private _isWithdrawing; //Multiplier to add some accuracy to profitPerShare uint256 private constant DistributionMultiplier = 2**64; //profit for each share a holder holds, a share equals a token. uint256 public profitPerShare; //The total shares + _totalSupply to avoid an underflow when substracting //need to use getTotalShares to get the actual shares uint256 private _totalShares=_totalSupply; //the total reward distributed through staking, for tracking purposes uint256 public totalStakingReward; //the total payout through staking, for tracking purposes uint256 public totalPayouts; //marketing share starts at 50% to push initial marketing, after start //its capped to 50% max, the percentage of the staking that gets used for //marketing/paying the team uint8 public marketingShare=27; //balance that is claimable by the team uint256 public marketingBalance; //Mapping of the already paid out(or missed) shares of each staker mapping(address => uint256) private alreadyPaidShares; //Mapping of shares that are reserved for payout mapping(address => uint256) private toBePaid; function getTotalShares() public view returns (uint256){ return _totalShares-_totalSupply; } //Contract, uniswap and burnAddress are excluded, other addresses like CEX //can be manually excluded, excluded list is limited to 30 entries to avoid a //out of gas exeption during sells function isExcludedFromStaking(address addr) public view returns (bool){ return _excludedFromStaking.contains(addr); } //adds Token to balances, adds new ETH to the toBePaid mapping and resets staking function _addToken(address addr, uint256 amount) private { //the amount of token after transfer uint256 newAmount=_balances[addr]+amount; if(isExcludedFromStaking(addr)){ _balances[addr]=newAmount; return; } _totalShares+=amount; //gets the payout before the change uint256 payment=_newDividentsOf(addr); //resets dividents to 0 for newAmount alreadyPaidShares[addr] = profitPerShare * newAmount; //adds dividents to the toBePaid mapping toBePaid[addr]+=payment; //sets newBalance _balances[addr]=newAmount; } //removes Token, adds ETH to the toBePaid mapping and resets staking function _removeToken(address addr, uint256 amount) private { //the amount of token after transfer uint256 newAmount=_balances[addr]-amount; if(isExcludedFromStaking(addr)){ _balances[addr]=newAmount; return; } _totalShares-=amount; //gets the payout before the change uint256 payment=_newDividentsOf(addr); //sets newBalance _balances[addr]=newAmount; //resets dividents to 0 for newAmount alreadyPaidShares[addr] = profitPerShare * newAmount; //adds dividents to the toBePaid mapping toBePaid[addr]+=payment; } //gets the not dividents of a staker that aren't in the toBePaid mapping //returns wrong value for excluded accounts function _newDividentsOf(address staker) private view returns (uint256) { uint256 fullPayout = profitPerShare * _balances[staker]; // if theres an overflow for some unexpected reason, return 0, instead of // an exeption to still make trades possible if(fullPayout<alreadyPaidShares[staker]) return 0; return (fullPayout - alreadyPaidShares[staker]) / DistributionMultiplier; } //distributes ETH between marketing share and dividents function _distributeStake(uint256 ETHamount,bool newStakingReward) private { // Deduct marketing Tax uint256 marketingSplit = (ETHamount * marketingShare) / 100; uint256 amount = ETHamount - marketingSplit; marketingBalance+=marketingSplit; if (amount > 0) { if(newStakingReward){ totalStakingReward += amount; } uint256 totalShares=getTotalShares(); //when there are 0 shares, add everything to marketing budget if (totalShares == 0) { marketingBalance += amount; }else{ //Increases profit per share based on current total shares profitPerShare += ((amount * DistributionMultiplier) / totalShares); } } } event OnWithdrawToken(uint256 amount, address token, address recipient); function TeamSetPlatinumHolder(uint8 fee, bool feeOn) public onlyTeam{ require(fee<=50,"PlatinumHolder function Fee is capped to 50%"); noPlatinumHolderFeeOn=feeOn; noPlatinumHolderFeePercent=fee; } uint8 public noPlatinumHolderFeePercent=50; bool public noPlatinumHolderFeeOn=true; //withdraws all dividents of address function claimToken(address addr, address token, uint256 payableAmount) private{ require(!_isWithdrawing); _isWithdrawing=true; uint256 amount; if(isExcludedFromStaking(addr)){ //if excluded just withdraw remaining toBePaid ETH amount=toBePaid[addr]; toBePaid[addr]=0; } else{ uint256 newAmount=_newDividentsOf(addr); //sets payout mapping to current amount alreadyPaidShares[addr] = profitPerShare * _balances[addr]; //the amount to be paid amount=toBePaid[addr]+newAmount; toBePaid[addr]=0; } if(amount==0&&payableAmount==0){//no withdraw if 0 amount _isWithdrawing=false; return; } //If you don't have PlatinumHolder function you are redistributing a part of your reward //Does not affect Compound if(noPlatinumHolderFeeOn&&_NoPlatinumHolder[addr]){ uint256 noPlatinumHolderFee=amount*noPlatinumHolderFeePercent/100; amount=amount-noPlatinumHolderFee; _distributeStake(noPlatinumHolderFee,false); } totalPayouts+=amount; amount+=payableAmount; (bool sent,)=addr.call{value: (amount)}(""); require(sent,"Claim failed"); emit OnWithdrawToken(amount,token, addr); _isWithdrawing=false; } //Compound function function MballToken(address addr, address token, uint256 payableAmount) private{ require(!_isWithdrawing); _isWithdrawing=true; uint256 amount; if(isExcludedFromStaking(addr)){ //if excluded just withdraw remaining toBePaid ETH amount=toBePaid[addr]; toBePaid[addr]=0; } else{ uint256 newAmount=_newDividentsOf(addr); //sets payout mapping to current amount alreadyPaidShares[addr] = profitPerShare * _balances[addr]; //the amount to be paid amount=toBePaid[addr]+newAmount; toBePaid[addr]=0; } if(amount==0&&payableAmount==0){//no withdraw if 0 amount _isWithdrawing=false; return; } //If you don't have PlatinumHolder function you are redistributing a part of your reward //Does not affect Compound if(noPlatinumHolderFeeOn&&_NoPlatinumHolder[addr]&&token!=address(this)){ uint256 noPlatinumHolderFee=amount*noPlatinumHolderFeePercent/100; amount=amount-noPlatinumHolderFee; _distributeStake(noPlatinumHolderFee,false); } totalPayouts+=amount; amount+=payableAmount; address[] memory path = new address[](2); path[0] = _uniswapRouter.WETH(); // wETH path[1] = token; _uniswapRouter.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}( 0, path, addr, block.timestamp); emit OnWithdrawToken(amount,token, addr); _isWithdrawing=false; } ////////////////////////////////////////Swap Contract Tokens///////////////////////////////// //tracks auto generated ETH, useful for ticker etc uint256 public totalLPETH; //Locks the swap if already swapping bool private _isSwappingContractModifier; modifier lockTheSwap { _isSwappingContractModifier = true; _; _isSwappingContractModifier = false; } //swaps the token on the contract for Marketing ETH and LP Token. //always swaps the sellLimit of token to avoid a large price impact function _swapContractToken(uint16 permilleOfuniswap,bool ignoreLimits) private lockTheSwap{ require(permilleOfuniswap<=500); uint256 contractBalance=_balances[address(this)]; uint16 totalTax=_liquidityTax+_stakingTax; if(totalTax==0) return; uint256 tokenToSwap=_balances[_uniswapPairAddress]*permilleOfuniswap/1000; if(tokenToSwap>sellLimit&&!ignoreLimits) tokenToSwap=sellLimit; //only swap if contractBalance is larger than tokenToSwap, and totalTax is unequal to 0 bool NotEnoughToken=contractBalance<tokenToSwap; if(NotEnoughToken){ if(ignoreLimits) tokenToSwap=contractBalance; else return; } //splits the token in TokenForLiquidity and tokenForMarketing uint256 tokenForLiquidity=(tokenToSwap*_liquidityTax)/totalTax; uint256 tokenForMarketing= tokenToSwap-tokenForLiquidity; //splits tokenForLiquidity in 2 halves uint256 liqToken=tokenForLiquidity/2; uint256 liqETHToken=tokenForLiquidity-liqToken; //swaps marktetingToken and the liquidity token half for ETH uint256 swapToken=liqETHToken+tokenForMarketing; //Gets the initial ETH balance, so swap will not touch any staked ETH uint256 initialETHBalance = address(this).balance; _swapTokenForETH(swapToken); uint256 newETH=(address(this).balance - initialETHBalance); //calculates the amount of ETH belonging to the LP-Pair and converts them to LP uint256 liqETH = (newETH*liqETHToken)/swapToken; _addLiquidity(liqToken, liqETH); //Get the ETH balance after LP generation to get the //exact amount of token left for Staking uint256 distributeETH=(address(this).balance - initialETHBalance); //distributes remaining ETH between stakers and Marketing _distributeStake(distributeETH,true); } //swaps tokens on the contract for ETH function _swapTokenForETH(uint256 amount) private { _approve(address(this), address(_uniswapRouter), amount); address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswapRouter.WETH(); _uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, path, address(this), block.timestamp ); } //Adds Liquidity directly to the contract where LP are locked function _addLiquidity(uint256 tokenamount, uint256 ETHamount) private { totalLPETH+=ETHamount; _approve(address(this), address(_uniswapRouter), tokenamount); _uniswapRouter.addLiquidityETH{value: ETHamount}( address(this), tokenamount, 0, 0, address(this), block.timestamp ); } //////////////////////////////////////////// Public functions /////////////////////////////////////////// function getLiquidityReleaseTimeInSeconds() public view returns (uint256){ if(block.timestamp<_liquidityUnlockTime){ return _liquidityUnlockTime-block.timestamp; } return 0; } function getLimits() public view returns(uint256 balance, uint256 sell){ return(balanceLimit/10, sellLimit/10); } function getTaxes() public view returns(uint256 liquidityTax,uint256 marketingTax, uint256 buyTax, uint256 sellTax, uint256 transferTax){ if(_botProtection) buyTax=_calculateLaunchTax(); else buyTax= _buyTax; return (_liquidityTax,_stakingTax,buyTax,_sellTax,_transferTax); } function getWhitelistedStatus(address AddressToCheck) public view returns(bool){ return _whiteList.contains(AddressToCheck); } function isPlatinumHolder(address AddressToCheck) public view returns(bool){ return !_NoPlatinumHolder[AddressToCheck]; } //How long is a given address still locked from selling function getAddressSellLockTimeInSeconds(address AddressToCheck) public view returns (uint256){ uint256 lockTime=_sellLock[AddressToCheck]; if(lockTime<=block.timestamp){ return 0; } return lockTime-block.timestamp; } function getSellLockTimeInSeconds() public view returns(uint256){ return sellLockTime; } bool allowTaxFreeCompound=true; function TeamSetPlatinumHolderTaxFree(bool taxFree) public onlyTeam{ allowTaxFreeCompound=taxFree; } //withdraws dividents of sender function ClaimETH() public { claimToken(msg.sender ,address(this),0); } function MBall() public{ if(allowTaxFreeCompound) oneTimeExcluded=msg.sender; MballToken(msg.sender,address(this),0); } function getDividents(address addr) private view returns (uint256){ if(isExcludedFromStaking(addr)) return toBePaid[addr]; return _newDividentsOf(addr)+toBePaid[addr]; } function getDividentsOf(address addr) public view returns (uint256){ uint256 amount=getDividents(addr); if(noPlatinumHolderFeeOn&&_NoPlatinumHolder[addr]) amount-=amount*noPlatinumHolderFeePercent/100; return amount; } ////////////////////////////////////////// Settings //////////////////////////////////// bool public sellLockDisabled; uint256 public sellLockTime; bool public manualConversion; uint16 public AutoLPThreshold=50; function TeamSetAutoLPThreshold(uint16 threshold) public onlyTeam{ require(threshold>0,"threshold needs to be more than 0"); require(threshold<=50,"threshold needs to be below 50"); AutoLPThreshold=threshold; } //Excludes account from Staking total function TeamExcludeFromStaking(address addr) public onlyTeam{ require(!isExcludedFromStaking(addr)); _totalShares-=_balances[addr]; uint256 newDividents=_newDividentsOf(addr); alreadyPaidShares[addr]=_balances[addr]*profitPerShare; toBePaid[addr]+=newDividents; _excludedFromStaking.add(addr); } //Includes excluded Account to staking function TeamIncludeToStaking(address addr) public onlyTeam{ require(isExcludedFromStaking(addr)); _totalShares+=_balances[addr]; _excludedFromStaking.remove(addr); //sets alreadyPaidShares to the current amount alreadyPaidShares[addr]=_balances[addr]*profitPerShare; } function TeamWithdrawMarketingETH() public onlyTeam{ uint256 amount=marketingBalance; marketingBalance=0; (bool sent,) =TeamWallet.call{value: (amount)}(""); require(sent,"withdraw failed"); } function TeamWithdrawMarketingETH(uint256 amount) public onlyTeam{ require(amount<=marketingBalance); marketingBalance-=amount; (bool sent,) =TeamWallet.call{value: (amount)}(""); require(sent,"withdraw failed"); } //switches autoLiquidity and marketing ETH generation during transfers function TeamSwitchManualETHConversion(bool manual) public onlyTeam{ manualConversion=manual; } //Sets SellLockTime, needs to be lower than MaxSellLockTime function TeamSetSellLockTime(uint256 sellLockSeconds)public onlyTeam{ require(sellLockSeconds<=MaxSellLockTime,"Sell Lock time too high"); sellLockTime=sellLockSeconds; } //Sets Taxes, is limited by MaxTax(20%) to make it impossible to create honeypot function TeamSetTaxes(uint8 liquidityTaxes, uint8 stakingTaxes,uint8 buyTax, uint8 sellTax, uint8 transferTax) public onlyTeam{ uint8 totalTax=liquidityTaxes+stakingTaxes; require(totalTax==100, "liq+staking needs to equal 100%"); require(buyTax<=MaxTax&&sellTax<=MaxTax,"taxes higher than max tax"); require(transferTax<=50,"transferTax higher than max transferTax"); _liquidityTax=liquidityTaxes; _stakingTax=stakingTaxes; _buyTax=buyTax; _sellTax=sellTax; _transferTax=transferTax; } //How much of the staking tax should be allocated for marketing function TeamChangeMarketingShare(uint8 newShare) public onlyTeam{ require(newShare<=50); marketingShare=newShare; } //manually converts contract token to LP and staking ETH function TeamCreateLPandETH(uint16 PermilleOfuniswap, bool ignoreLimits) public onlyTeam{ _swapContractToken(PermilleOfuniswap, ignoreLimits); } //Exclude/Include account from fees (eg. CEX) function TeamExcludeAccountFromFees(address account) public onlyTeam { _excluded.add(account); } function TeamIncludeAccountToFees(address account) public onlyTeam { _excluded.remove(account); } //Exclude/Include account from fees (eg. CEX) function TeamExcludeAccountFromSellLock(address account) public onlyTeam { _excludedFromSellLock.add(account); } function TeamIncludeAccountToSellLock(address account) public onlyTeam { _excludedFromSellLock.remove(account); } //Limits need to be at least target, to avoid setting value to 0 function TeamUpdateLimits(uint256 newBalanceLimit, uint256 newSellLimit) public onlyTeam{ //Calculates the target Limits based on supply uint256 targetBalanceLimit=_totalSupply/BalanceLimitDivider; uint256 targetSellLimit=_totalSupply/SellLimitDivider; require((newBalanceLimit>=targetBalanceLimit), "newBalanceLimit needs to be at least target"); require((newSellLimit>=targetSellLimit), "newSellLimit needs to be at least target"); balanceLimit = newBalanceLimit; sellLimit = newSellLimit; } event OnSwitchSellLock(bool disabled); //Disables the timeLock after selling for everyone function TeamDisableSellLock(bool disabled) public onlyTeam{ sellLockDisabled=disabled; emit OnSwitchSellLock(disabled); } ///////////////////////////////////// Setup Functions ////////////////////////////////////// function SetupCreateLP(uint8 TeamTokenPercent) public payable onlyTeam{ require(IERC20(_uniswapPairAddress).totalSupply()==0,"There are alreadyLP"); uint256 Token=_balances[address(this)]; uint256 TeamToken=Token*TeamTokenPercent/100; uint256 LPToken=Token-TeamToken; _removeToken(address(this),TeamToken); _addToken(msg.sender, TeamToken); emit Transfer(address(this), msg.sender, TeamToken); _addLiquidity(LPToken, msg.value); } bool public tradingEnabled; //Enables trading for everyone function SetupEnableTrading(bool BotProtection) public onlyTeam{ require(IERC20(_uniswapPairAddress).totalSupply()>0,"there are no LP"); require(!tradingEnabled); tradingEnabled=true; _botProtection=BotProtection; launchTimestamp=block.timestamp; //Liquidity gets locked for 7 days at start, needs to be prolonged once //start is successful _liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime; } function SetupAddOrRemoveWhitelist(address[] memory addresses,bool Add) public onlyTeam{ for(uint i=0; i<addresses.length; i++){ if(Add) _whiteList.add(addresses[i]); else _whiteList.remove(addresses[i]); } } /////////////////////////////////////// Liquidity Lock ////////////////////////////////////////// //the timestamp when Liquidity unlocks uint256 private _liquidityUnlockTime; //Sets Liquidity Release to 20% at a time and prolongs liquidity Lock for a Week after Release. //Should be called once start was successful. bool public liquidityRelease20Percent; function TeamlimitLiquidityReleaseTo20Percent() public onlyTeam{ liquidityRelease20Percent=true; } function TeamUnlockLiquidityInSeconds(uint256 secondsUntilUnlock) public onlyTeam{ _prolongLiquidityLock(secondsUntilUnlock+block.timestamp); } function _prolongLiquidityLock(uint256 newUnlockTime) private{ // require new unlock time to be longer than old one require(newUnlockTime>_liquidityUnlockTime); _liquidityUnlockTime=newUnlockTime; } //Release Liquidity Tokens once unlock time is over function TeamReleaseLiquidity() public onlyTeam { //Only callable if liquidity Unlock time is over require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); IuniswapERC20 liquidityToken = IuniswapERC20(_uniswapPairAddress); uint256 amount = liquidityToken.balanceOf(address(this)); if(liquidityRelease20Percent) { _liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime; //regular liquidity release, only releases 20% at a time and locks liquidity for another week amount=amount*2/10; liquidityToken.transfer(TeamWallet, amount); } else { //Liquidity release if something goes wrong at start //liquidityRelease20Percent should be called once everything is clear liquidityToken.transfer(TeamWallet, amount); } } //Removes Liquidity once unlock Time is over, function TeamRemoveLiquidity(bool addToStaking) public onlyTeam { //Only callable if liquidity Unlock time is over require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); _liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime; IuniswapERC20 liquidityToken = IuniswapERC20(_uniswapPairAddress); uint256 amount = liquidityToken.balanceOf(address(this)); if(liquidityRelease20Percent){ amount=amount*2/10; //only remove 20% each } liquidityToken.approve(address(_uniswapRouter),amount); //Removes Liquidity and either distributes liquidity ETH to stakers, or // adds them to marketing Balance //Token will be converted //to Liquidity and Staking ETH again uint256 initialETHBalance = address(this).balance; _uniswapRouter.removeLiquidityETHSupportingFeeOnTransferTokens( address(this), amount, 0, 0, address(this), block.timestamp ); uint256 newETHBalance = address(this).balance-initialETHBalance; if(addToStaking){ _distributeStake(newETHBalance,true); } else{ marketingBalance+=newETHBalance; } } //Releases all remaining ETH on the contract wallet, so ETH wont be burned //Can only be called 30 days after Liquidity unlocks function TeamRemoveRemainingETH() public onlyTeam{ require(block.timestamp >= _liquidityUnlockTime+30 days, "Not yet unlocked"); _liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime; (bool sent,) =TeamWallet.call{value: (address(this).balance)}(""); require(sent); } function RescueStrandedToken(address tokenAddress) public onlyTeam{ require(tokenAddress!=_uniswapPairAddress&&tokenAddress!=address(this),"can't Rescue LP token or this token"); IERC20 token=IERC20(tokenAddress); token.transfer(msg.sender,token.balanceOf(address(this))); } /////////////////////////////////////////// External ///////////////////////////////////////////////// receive() external payable {} fallback() external payable {} // IERC20 function getOwner() external view override returns (address) { return owner(); } function name() external pure override returns (string memory) { return _name; } function symbol() external pure override returns (string memory) { return _symbol; } function decimals() external pure override returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _totalSupply; } function balanceOf(address account) external view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address _owner, address spender) external view override returns (uint256) { return _allowances[_owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "Approve from zero"); require(spender != address(0), "Approve to zero"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][msg.sender]; require(currentAllowance >= amount, "Transfer > allowance"); _approve(sender, msg.sender, currentAllowance - amount); return true; } // IERC20 - Helpers function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 currentAllowance = _allowances[msg.sender][spender]; require(currentAllowance >= subtractedValue, "<0 allowance"); _approve(msg.sender, spender, currentAllowance - subtractedValue); return true; } }
Removes Liquidity once unlock Time is over,Only callable if liquidity Unlock time is over
function TeamRemoveLiquidity(bool addToStaking) public onlyTeam { require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); _liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime; IuniswapERC20 liquidityToken = IuniswapERC20(_uniswapPairAddress); uint256 amount = liquidityToken.balanceOf(address(this)); if(liquidityRelease20Percent){ } liquidityToken.approve(address(_uniswapRouter),amount); _uniswapRouter.removeLiquidityETHSupportingFeeOnTransferTokens( address(this), amount, 0, 0, address(this), block.timestamp ); uint256 newETHBalance = address(this).balance-initialETHBalance; uint256 initialETHBalance = address(this).balance; if(addToStaking){ _distributeStake(newETHBalance,true); } else{ marketingBalance+=newETHBalance; } }
14,526,654
[ 1, 6220, 511, 18988, 24237, 3647, 7186, 2647, 353, 1879, 16, 3386, 4140, 309, 4501, 372, 24237, 3967, 813, 353, 1879, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 10434, 3288, 48, 18988, 24237, 12, 6430, 9604, 510, 6159, 13, 1071, 1338, 8689, 288, 203, 3639, 2583, 12, 2629, 18, 5508, 1545, 389, 549, 372, 24237, 7087, 950, 16, 315, 1248, 4671, 25966, 8863, 203, 3639, 389, 549, 372, 24237, 7087, 950, 33, 2629, 18, 5508, 15, 1868, 48, 18988, 24237, 2531, 950, 31, 203, 3639, 467, 318, 291, 91, 438, 654, 39, 3462, 4501, 372, 24237, 1345, 273, 467, 318, 291, 91, 438, 654, 39, 3462, 24899, 318, 291, 91, 438, 4154, 1887, 1769, 203, 3639, 2254, 5034, 3844, 273, 4501, 372, 24237, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 12, 549, 372, 24237, 7391, 3462, 8410, 15329, 203, 3639, 289, 7010, 3639, 4501, 372, 24237, 1345, 18, 12908, 537, 12, 2867, 24899, 318, 291, 91, 438, 8259, 3631, 8949, 1769, 203, 3639, 389, 318, 291, 91, 438, 8259, 18, 4479, 48, 18988, 24237, 1584, 44, 6289, 310, 14667, 1398, 5912, 5157, 12, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 3844, 16, 203, 5411, 374, 16, 203, 5411, 374, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 1203, 18, 5508, 203, 5411, 11272, 203, 3639, 2254, 5034, 394, 1584, 44, 13937, 273, 1758, 12, 2211, 2934, 12296, 17, 6769, 1584, 44, 13937, 31, 203, 3639, 2254, 5034, 2172, 1584, 44, 13937, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 3639, 309, 12, 1289, 774, 510, 6159, 15329, 203, 5411, 389, 2251, 887, 510, 911, 12, 2704, 1584, 44, 13937, 16, 3767, 1769, 203, 2 ]
./partial_match/3/0x95E5925D0256602aaDC5201EcB17d1cF05e02906/sources/Fortuna.sol
uint public developerFee = 50;uint public tradingCompFee = 50;uint public stakerFee = 100;uint public liqproviderFee = 75;onetwothree
function _transfer(address _from, address _to, uint _value) internal { require(_to != address(0x0)); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); uint256 tenthousandthofamonut = _value.div(10000); uint256 _bnum = (block.number - genesisBlock)/BlockSizeForTC; totalRewardforTC[_bnum] += uint(tenthousandthofamonut.mul(tradingCompFee)); uint tenthousandthofamonutStake = tenthousandthofamonut.mul(1000); dlist[datumIndex].prosum += uint(tenthousandthofamonutStake.mul(stakerFee)); dlistLP[datumIndexLP].prosum += uint(tenthousandthofamonut.mul(liqproviderFee)); balanceOf[_from] -= _value; uint uinttotalOut = uint(tenthousandthofamonut.mul(tradingCompFee)) + uint(tenthousandthofamonut.mul(stakerFee)) + uint(tenthousandthofamonut.mul(liqproviderFee)); balanceOf[_to] += uint(_value).sub(uinttotalOut); emit Transfer(_from, _to, uint(_value).sub(uinttotalOut)); holderlist.push(_to); tradingComp(_value); } mapping (string => uint256) public userTCpoint;
5,108,111
[ 1, 11890, 1071, 8751, 14667, 273, 6437, 31, 11890, 1071, 1284, 7459, 2945, 14667, 273, 6437, 31, 11890, 1071, 384, 6388, 14667, 273, 2130, 31, 11890, 1071, 4501, 85, 6778, 14667, 273, 18821, 31, 265, 278, 91, 10370, 992, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 389, 1132, 13, 2713, 288, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 92, 20, 10019, 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, 5034, 268, 319, 76, 1481, 464, 451, 792, 301, 265, 322, 273, 389, 1132, 18, 2892, 12, 23899, 1769, 203, 3639, 2254, 5034, 389, 70, 2107, 273, 261, 2629, 18, 2696, 300, 21906, 1768, 13176, 22506, 1290, 15988, 31, 203, 3639, 2078, 17631, 1060, 1884, 15988, 63, 67, 70, 2107, 65, 225, 1011, 225, 2254, 12, 88, 319, 76, 1481, 464, 451, 792, 301, 265, 322, 18, 16411, 12, 313, 14968, 2945, 14667, 10019, 203, 3639, 2254, 268, 319, 76, 1481, 464, 451, 792, 301, 265, 322, 510, 911, 273, 268, 319, 76, 1481, 464, 451, 792, 301, 265, 322, 18, 16411, 12, 18088, 1769, 203, 3639, 302, 1098, 63, 3404, 379, 1016, 8009, 685, 1364, 225, 1011, 225, 2254, 12, 88, 319, 76, 1481, 464, 451, 792, 301, 265, 322, 510, 911, 18, 16411, 12, 334, 6388, 14667, 10019, 203, 3639, 302, 1098, 14461, 63, 3404, 379, 1016, 14461, 8009, 685, 1364, 225, 1011, 225, 2254, 12, 88, 319, 76, 1481, 464, 451, 792, 301, 265, 322, 18, 16411, 12, 549, 85, 6778, 14667, 10019, 203, 203, 3639, 11013, 951, 63, 67, 2080, 65, 3947, 2 ]
./full_match/8453/0x169C06b4cfB09bFD73A81e6f2Bb1eB514D75bB19/sources/src/dex/v2/LeetSwapV2Pair.sol
Accrue fees on token0
function _update0(uint256 amount) internal { uint256 _protocolFeesShare = ILeetSwapV2Factory(factory) .protocolFeesShare(); address _protocolFeesRecipient = ILeetSwapV2Factory(factory) .protocolFeesRecipient(); uint256 _protocolFeesAmount = (amount * _protocolFeesShare) / 10000; amount = _transferFeesSupportingTaxTokens( token0, amount - _protocolFeesAmount ); if (_protocolFeesAmount > 0) _safeTransfer(token0, _protocolFeesRecipient, _protocolFeesAmount); uint256 _ratio = (amount * 1e18) / totalSupply; if (_ratio > 0) { index0 += _ratio; } emit Fees(msg.sender, amount, 0); }
11,542,429
[ 1, 8973, 86, 344, 1656, 281, 603, 1147, 20, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2725, 20, 12, 11890, 5034, 3844, 13, 2713, 288, 203, 3639, 2254, 5034, 389, 8373, 2954, 281, 9535, 273, 467, 1682, 278, 12521, 58, 22, 1733, 12, 6848, 13, 203, 5411, 263, 8373, 2954, 281, 9535, 5621, 203, 3639, 1758, 389, 8373, 2954, 281, 18241, 273, 467, 1682, 278, 12521, 58, 22, 1733, 12, 6848, 13, 203, 5411, 263, 8373, 2954, 281, 18241, 5621, 203, 3639, 2254, 5034, 389, 8373, 2954, 281, 6275, 273, 261, 8949, 380, 389, 8373, 2954, 281, 9535, 13, 342, 12619, 31, 203, 3639, 3844, 273, 389, 13866, 2954, 281, 6289, 310, 7731, 5157, 12, 203, 5411, 1147, 20, 16, 203, 5411, 3844, 300, 389, 8373, 2954, 281, 6275, 203, 3639, 11272, 203, 3639, 309, 261, 67, 8373, 2954, 281, 6275, 405, 374, 13, 203, 5411, 389, 4626, 5912, 12, 2316, 20, 16, 389, 8373, 2954, 281, 18241, 16, 389, 8373, 2954, 281, 6275, 1769, 203, 3639, 2254, 5034, 389, 9847, 273, 261, 8949, 380, 404, 73, 2643, 13, 342, 2078, 3088, 1283, 31, 203, 3639, 309, 261, 67, 9847, 405, 374, 13, 288, 203, 5411, 770, 20, 1011, 389, 9847, 31, 203, 3639, 289, 203, 3639, 3626, 5782, 281, 12, 3576, 18, 15330, 16, 3844, 16, 374, 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 ]
/* * Copyright 2021 ConsenSys Software Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ pragma solidity >=0.8; import "../../../../../common/common/src/main/solidity/BytesUtil.sol"; contract CallPathCallExecutionTree is BytesUtil { uint256 private constant NUM_FUNCS_CALLED_SIZE = 1; uint256 private constant OFFSET_SIZE = 4; uint256 private constant BLOCKCHAIN_ID_SIZE = 32; uint256 private constant ADDRESS_SIZE = 20; uint256 private constant DATA_LEN_SIZE_SIZE = 2; function extractTargetFromCallGraph( bytes memory _callGraph, uint256[] memory _callPath, bool getFunction ) internal pure returns ( uint256 targetBlockchainId, address targetContract, bytes memory functionCall ) { uint256 index = 0; // Go down the call path to the target function for (uint256 i = 0; i < _callPath.length; i++) { uint256 offset = 0; uint8 numFuncsCalled = BytesUtil.bytesToUint8(_callGraph, index); if (numFuncsCalled == 0) { require( i == _callPath.length - 1, "Reached leaf function but there is more call path." ); } else { // Jump to the location of the offset of the function uint256 functionCalled = _callPath[i]; offset = BytesUtil.bytesToUint32( _callGraph, index + functionCalled * OFFSET_SIZE + NUM_FUNCS_CALLED_SIZE ); } // Jump to the function index = index + offset; } // Jump over the leaf function indicator / numFuncsCalled = 0 indicator if (_callPath[_callPath.length - 1] != 0) { uint8 numFuncsCalled = BytesUtil.bytesToUint8(_callGraph, index); if (numFuncsCalled != 0) { // The call path should have included an extra 0 at the end, // for instance [2] rather than [2][0]. // This can happen for multi-level call trees, where the call path is only a part of the // call path. In determineFuncsToBeCalled, it will pass in, for instance // [1] rather than [1][0], when fetching the functions that the root function calls. // Jump to the location of the offset of the function // functionCalled would be 0 uint256 offset = BytesUtil.bytesToUint32( _callGraph, index + NUM_FUNCS_CALLED_SIZE ); // Jump to the function index = index + offset; } else { index += NUM_FUNCS_CALLED_SIZE; } } targetBlockchainId = BytesUtil.bytesToUint256(_callGraph, index); index += BLOCKCHAIN_ID_SIZE; targetContract = BytesUtil.bytesToAddress2(_callGraph, index); if (getFunction) { index += ADDRESS_SIZE; uint16 functionDataLen = BytesUtil.bytesToUint16(_callGraph, index); index += DATA_LEN_SIZE_SIZE; functionCall = BytesUtil.sliceAsm( _callGraph, index, functionDataLen ); } else { functionCall = ""; } } /** * Determine call path of parent. NOTE: Do not call if this current call path represents the root. * * @param _callPath Currently executing call path * @return Call path of parent. */ function determineParentCallPath(uint256[] memory _callPath) internal pure returns (uint256[] memory) { uint256[] memory callPathOfParent; uint256 callPathLen = _callPath.length; // Don't call from root function //assert(!(callPathLen == 1 && _callPath[0] == 0)); if (_callPath[callPathLen - 1] != 0) { callPathOfParent = new uint256[](callPathLen); for (uint256 i = 0; i < callPathLen - 1; i++) { callPathOfParent[i] = _callPath[i]; } callPathOfParent[callPathLen - 1] = 0; } else { callPathOfParent = new uint256[](callPathLen - 1); for (uint256 i = 0; i < callPathLen - 2; i++) { callPathOfParent[i] = _callPath[i]; } callPathOfParent[callPathLen - 2] = 0; } return callPathOfParent; } }
Jump to the function
index = index + offset;
12,916,926
[ 1, 26743, 358, 326, 445, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 770, 273, 770, 397, 1384, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x4c207f4acE27B9F29F7A2C9e4ECf8eb7dFe1cf7e/sources/contracts/NuCyberStaking.sol
* @notice Returns the list of tokens owned by `tokenOwner_`. @param tokenOwner_ address owning tokens/
function stakedTokens(address tokenOwner_) public view returns (StakedToken[] memory) { return _stakedTokens[tokenOwner_]; }
17,123,956
[ 1, 1356, 326, 666, 434, 2430, 16199, 635, 1375, 2316, 5541, 67, 8338, 225, 1147, 5541, 67, 1758, 25022, 2430, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 384, 9477, 5157, 12, 2867, 1147, 5541, 67, 13, 1071, 1476, 1135, 261, 510, 9477, 1345, 8526, 3778, 13, 288, 203, 1377, 327, 389, 334, 9477, 5157, 63, 2316, 5541, 67, 15533, 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 ]
./full_match/43113/0x01a38735A7b4E0f3338bf96F46b5E60Edc668CD9/sources/contracts/drawax.sol
create new instance of GuessGame
function newGame() private { _launchDay = block.timestamp; resetGameGrid(); _randomResult = 0; _winner = _START_ADDRESS; _seed = 0; _poolPrice = 0; }
7,112,366
[ 1, 2640, 394, 791, 434, 30282, 12496, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 394, 12496, 1435, 3238, 288, 203, 3639, 389, 20738, 4245, 273, 1203, 18, 5508, 31, 203, 540, 203, 3639, 2715, 12496, 6313, 5621, 203, 540, 203, 3639, 389, 9188, 1253, 273, 374, 31, 203, 540, 203, 3639, 389, 91, 7872, 273, 389, 7570, 67, 15140, 31, 203, 540, 203, 3639, 389, 12407, 273, 374, 31, 203, 540, 203, 3639, 389, 6011, 5147, 273, 374, 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 ]
./full_match/1/0x471580a65c098E0344c812b6dB292347e0208B67/sources/contracts/UpEthereum.sol
wallet marketing bnb
uint256 marketing;
3,147,371
[ 1, 19177, 13667, 310, 324, 6423, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 2254, 5034, 13667, 310, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.5.16; contract chiToken { /// @notice EIP-20 token name for this token string public constant name = "DragonDAO"; /// @notice EIP-20 token symbol for this token string public constant symbol = "CHI"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint128 private _totalSupply = 10_000_000_000e18; // 10 billion Dragon /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint128)) internal allowances; /// @notice Official record of token balances for each accountƒ mapping (address => uint128) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint128 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /** * @notice Construct a new TT token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint128(_totalSupply); emit Transfer(address(0), account, _totalSupply); } /** ========== token functions ========== */ function totalSupply() public view returns (uint128) { return _totalSupply; } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) public view returns (uint128) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) public returns (bool) { uint128 amount; if (rawAmount == uint(-1)) { amount = uint128(-1); } else { amount = safe128(rawAmount, "approve: amount exceeds 128 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) public view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint128 amount = safe128(rawAmount, "transfer: amount exceeds 128 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint128 spenderAllowance = allowances[src][spender]; uint128 amount = safe128(rawAmount, "approve: amount exceeds 128 bits"); if (spender != src && spenderAllowance != uint128(-1)) { uint128 newAllowance = sub128(spenderAllowance, amount, "transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. * votes will be updated after burn() whoever the delegator is. */ function burn(uint256 rawAmount) external returns (bool) { uint128 amount = safe128(rawAmount, "_burn: amount exceeds 128 bits"); require(_burn(msg.sender, amount), "burn: fail to burn"); return true; } /** * @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 rawAmount) external returns (bool) { uint128 amount = safe128(rawAmount, "_burn: amount exceeds 128 bits"); uint128 decreasedAllowance = sub128(allowance(account, msg.sender), amount, "ERC20: burn amount exceeds allowance"); allowances[account][msg.sender] = decreasedAllowance; require(_burn(account, amount), "burn: fail to burn"); return true; } /** ========== voting functions ========== */ /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "delegateBySig: invalid nonce"); require(now <= expiry, "delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint128) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint128) { require(blockNumber < block.number, "getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } /** ========== internal mutative functions ========== */ /** * @notice burn token and decrease user's votes * @param src The address of the account burning token * @param rawAmount The amount of burning token */ function _burn(address src, uint256 rawAmount) internal returns (bool) { require(src != address(0), "_burn: burn from the zero address"); uint128 amount = safe128(rawAmount, "_burn: amount exceeds 128 bits"); balances[src] = sub128(balances[src], amount, "_burn: burn amount exceeds balance"); _totalSupply = sub128(_totalSupply, amount, "_burn: all token have been burnt"); _moveDelegates(delegates[src], address(0), amount); emit Transfer(src, address(0), amount); return true; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint128 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint128 amount) internal { require(src != address(0), "_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "_transferTokens: cannot transfer to the zero address"); balances[src] = sub128(balances[src], amount, "_transferTokens: transfer amount exceeds balance"); balances[dst] = add128(balances[dst], amount, "_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint128 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint128 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint128 srcRepNew = sub128(srcRepOld, amount, "_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint128 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint128 dstRepNew = add128(dstRepOld, amount, "_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint128 oldVotes, uint128 newVotes) internal { uint32 blockNumber = safe32(block.number, "_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe128(uint n, string memory errorMessage) internal pure returns (uint128) { require(n < 2**128, errorMessage); return uint128(n); } function add128(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { uint128 c = a + b; require(c >= a, errorMessage); return c; } function sub128(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); }
* @notice Construct a new TT token @param account The initial account to grant all the tokens/
constructor(address account) public { balances[account] = uint128(_totalSupply); emit Transfer(address(0), account, _totalSupply); }
10,145,276
[ 1, 7249, 279, 394, 19912, 1147, 225, 2236, 1021, 2172, 2236, 358, 7936, 777, 326, 2430, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3885, 12, 2867, 2236, 13, 1071, 288, 203, 3639, 324, 26488, 63, 4631, 65, 273, 2254, 10392, 24899, 4963, 3088, 1283, 1769, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 2236, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x2ea6B54759170f8E68fae947ED9AbD2F8B290eB1/sources/contracts/ZXNProtocol.sol
PROD: 60 * 60 * 24 == 1 days; TEST: 2 * 60 == 2 min;
cycleDuration = _cycleDuration;
16,540,037
[ 1, 8025, 1212, 30, 4752, 225, 4752, 225, 4248, 422, 404, 4681, 31, 22130, 30, 576, 225, 4752, 422, 576, 1131, 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 ]
[ 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, 3639, 8589, 5326, 273, 389, 13946, 5326, 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 ]
pragma solidity ^0.4.19; /* Interface for ERC20 Tokens */ contract Token { bytes32 public standard; bytes32 public name; bytes32 public symbol; uint256 public totalSupply; uint8 public decimals; bool public allowTransactions; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; function transfer(address _to, uint256 _value) returns (bool success); function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); } // The DMEX base Contract contract Exchange { function assert(bool assertion) { if (!assertion) throw; } // Safe Multiply Function - prevents integer overflow function safeMul(uint a, uint b) returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } // Safe Subtraction Function - prevents integer overflow function safeSub(uint a, uint b) returns (uint) { assert(b <= a); return a - b; } // Safe Addition Function - prevents integer overflow function safeAdd(uint a, uint b) returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } address public owner; // holds the address of the contract owner mapping (address => bool) public admins; // mapping of admin addresses mapping (address => bool) public futuresContracts; // mapping of connected futures contracts mapping (address => uint256) public futuresContractsAddedBlock; // mapping of connected futures contracts and connection block numbers event SetFuturesContract(address futuresContract, bool isFuturesContract); // Event fired when the owner of the contract is changed event SetOwner(address indexed previousOwner, address indexed newOwner); // Allows only the owner of the contract to execute the function modifier onlyOwner { assert(msg.sender == owner); _; } // Changes the owner of the contract function setOwner(address newOwner) onlyOwner { SetOwner(owner, newOwner); owner = newOwner; } // Owner getter function function getOwner() returns (address out) { return owner; } // Adds or disables an admin account function setAdmin(address admin, bool isAdmin) onlyOwner { admins[admin] = isAdmin; } // Adds or disables a futuresContract address function setFuturesContract(address futuresContract, bool isFuturesContract) onlyOwner { futuresContracts[futuresContract] = isFuturesContract; if (fistFuturesContract == address(0)) { fistFuturesContract = futuresContract; } futuresContractsAddedBlock[futuresContract] = block.number; emit SetFuturesContract(futuresContract, isFuturesContract); } // Allows for admins only to call the function modifier onlyAdmin { if (msg.sender != owner && !admins[msg.sender]) throw; _; } // Allows for futures contracts only to call the function modifier onlyFuturesContract { if (!futuresContracts[msg.sender]) throw; _; } function() external { throw; } //mapping (address => mapping (address => uint256)) public tokens; // mapping of token addresses to mapping of balances // tokens[token][user] //mapping (address => mapping (address => uint256)) public reserve; // mapping of token addresses to mapping of reserved balances // reserve[token][user] mapping (address => mapping (address => uint256)) public balances; // mapping of token addresses to mapping of balances and reserve (bitwise compressed) // balances[token][user] mapping (address => uint256) public lastActiveTransaction; // mapping of user addresses to last transaction block mapping (bytes32 => uint256) public orderFills; // mapping of orders to filled qunatity mapping (address => mapping (address => bool)) public userAllowedFuturesContracts; // mapping of allowed futures smart contracts per user mapping (address => uint256) public userFirstDeposits; // mapping of user addresses and block number of first deposit address public feeAccount; // the account that receives the trading fees address public EtmTokenAddress; // the address of the EtherMium token address public fistFuturesContract; // 0x if there are no futures contracts set yet uint256 public inactivityReleasePeriod; // period in blocks before a user can use the withdraw() function mapping (bytes32 => bool) public withdrawn; // mapping of withdraw requests, makes sure the same withdrawal is not executed twice uint256 public makerFee; // maker fee in percent expressed as a fraction of 1 ether (0.1 ETH = 10%) uint256 public takerFee; // taker fee in percent expressed as a fraction of 1 ether (0.1 ETH = 10%) enum Errors { INVLID_PRICE, // Order prices don't match INVLID_SIGNATURE, // Signature is invalid TOKENS_DONT_MATCH, // Maker/taker tokens don't match ORDER_ALREADY_FILLED, // Order was already filled GAS_TOO_HIGH // Too high gas fee } // Trade event fired when a trade is executed event Trade( address takerTokenBuy, uint256 takerAmountBuy, address takerTokenSell, uint256 takerAmountSell, address maker, address indexed taker, uint256 makerFee, uint256 takerFee, uint256 makerAmountTaken, uint256 takerAmountTaken, bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash ); // Deposit event fired when a deposit took place event Deposit(address indexed token, address indexed user, uint256 amount, uint256 balance); // Withdraw event fired when a withdrawal was executed event Withdraw(address indexed token, address indexed user, uint256 amount, uint256 balance, uint256 withdrawFee); event WithdrawTo(address indexed token, address indexed to, address indexed from, uint256 amount, uint256 balance, uint256 withdrawFee); // Fee change event event FeeChange(uint256 indexed makerFee, uint256 indexed takerFee); // Log event, logs errors in contract execution (used for debugging) event LogError(uint8 indexed errorId, bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash); event LogUint(uint8 id, uint256 value); event LogBool(uint8 id, bool value); event LogAddress(uint8 id, address value); // Change inactivity release period event event InactivityReleasePeriodChange(uint256 value); // Order cancelation event event CancelOrder( bytes32 indexed cancelHash, bytes32 indexed orderHash, address indexed user, address tokenSell, uint256 amountSell, uint256 cancelFee ); // Sets the inactivity period before a user can withdraw funds manually function setInactivityReleasePeriod(uint256 expiry) onlyOwner returns (bool success) { if (expiry > 1000000) throw; inactivityReleasePeriod = expiry; emit InactivityReleasePeriodChange(expiry); return true; } // Constructor function, initializes the contract and sets the core variables function Exchange(address feeAccount_, uint256 makerFee_, uint256 takerFee_, uint256 inactivityReleasePeriod_) { owner = msg.sender; feeAccount = feeAccount_; inactivityReleasePeriod = inactivityReleasePeriod_; makerFee = makerFee_; takerFee = takerFee_; } // Changes the fees function setFees(uint256 makerFee_, uint256 takerFee_) onlyOwner { require(makerFee_ < 10 finney && takerFee_ < 10 finney); // The fees cannot be set higher then 1% makerFee = makerFee_; takerFee = takerFee_; emit FeeChange(makerFee, takerFee); } function updateBalanceAndReserve (address token, address user, uint256 balance, uint256 reserve) private { uint256 character = uint256(balance); character |= reserve<<128; balances[token][user] = character; } function updateBalance (address token, address user, uint256 balance) private returns (bool) { uint256 character = uint256(balance); character |= getReserve(token, user)<<128; balances[token][user] = character; return true; } function updateReserve (address token, address user, uint256 reserve) private { uint256 character = uint256(balanceOf(token, user)); character |= reserve<<128; balances[token][user] = character; } function decodeBalanceAndReserve (address token, address user) returns (uint256[2]) { uint256 character = balances[token][user]; uint256 balance = uint256(uint128(character)); uint256 reserve = uint256(uint128(character>>128)); return [balance, reserve]; } function futuresContractAllowed (address futuresContract, address user) returns (bool) { if (fistFuturesContract == futuresContract) return true; if (userAllowedFuturesContracts[user][futuresContract] == true) return true; if (futuresContractsAddedBlock[futuresContract] < userFirstDeposits[user]) return true; return false; } // Returns the balance of a specific token for a specific user function balanceOf(address token, address user) view returns (uint256) { //return tokens[token][user]; return decodeBalanceAndReserve(token, user)[0]; } // Returns the reserved amound of token for user function getReserve(address token, address user) public view returns (uint256) { //return reserve[token][user]; return decodeBalanceAndReserve(token, user)[1]; } // Sets reserved amount for specific token and user (can only be called by futures contract) function setReserve(address token, address user, uint256 amount) onlyFuturesContract returns (bool success) { if (!futuresContractAllowed(msg.sender, user)) throw; if (availableBalanceOf(token, user) < amount) throw; updateReserve(token, user, amount); return true; } // Updates user balance (only can be used by futures contract) function setBalance(address token, address user, uint256 amount) onlyFuturesContract returns (bool success) { if (!futuresContractAllowed(msg.sender, user)) throw; updateBalance(token, user, amount); return true; } function subBalanceAddReserve(address token, address user, uint256 subBalance, uint256 addReserve) onlyFuturesContract returns (bool) { if (!futuresContractAllowed(msg.sender, user)) throw; updateBalanceAndReserve(token, user, safeSub(balanceOf(token, user), subBalance), safeAdd(getReserve(token, user), addReserve)); } function addBalanceSubReserve(address token, address user, uint256 addBalance, uint256 subReserve) onlyFuturesContract returns (bool) { if (!futuresContractAllowed(msg.sender, user)) throw; updateBalanceAndReserve(token, user, safeAdd(balanceOf(token, user), addBalance), safeSub(getReserve(token, user), subReserve)); } function subBalanceSubReserve(address token, address user, uint256 subBalance, uint256 subReserve) onlyFuturesContract returns (bool) { if (!futuresContractAllowed(msg.sender, user)) throw; updateBalanceAndReserve(token, user, safeSub(balanceOf(token, user), subBalance), safeSub(getReserve(token, user), subReserve)); } // Returns the available balance of a specific token for a specific user function availableBalanceOf(address token, address user) view returns (uint256) { return safeSub(balanceOf(token, user), getReserve(token, user)); } // Returns the inactivity release perios function getInactivityReleasePeriod() view returns (uint256) { return inactivityReleasePeriod; } // Increases the user balance function addBalance(address token, address user, uint256 amount) private { updateBalance(token, user, safeAdd(balanceOf(token, user), amount)); } // Decreases user balance function subBalance(address token, address user, uint256 amount) private { if (availableBalanceOf(token, user) < amount) throw; updateBalance(token, user, safeSub(balanceOf(token, user), amount)); } // Deposit ETH to contract function deposit() payable { //tokens[address(0)][msg.sender] = safeAdd(tokens[address(0)][msg.sender], msg.value); // adds the deposited amount to user balance addBalance(address(0), msg.sender, msg.value); // adds the deposited amount to user balance if (userFirstDeposits[msg.sender] == 0) userFirstDeposits[msg.sender] = block.number; lastActiveTransaction[msg.sender] = block.number; // sets the last activity block for the user emit Deposit(address(0), msg.sender, msg.value, balanceOf(address(0), msg.sender)); // fires the deposit event } // Deposit token to contract function depositToken(address token, uint128 amount) { //tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount); // adds the deposited amount to user balance //if (amount != uint128(amount) || safeAdd(amount, balanceOf(token, msg.sender)) != uint128(amount)) throw; addBalance(token, msg.sender, amount); // adds the deposited amount to user balance if (userFirstDeposits[msg.sender] == 0) userFirstDeposits[msg.sender] = block.number; lastActiveTransaction[msg.sender] = block.number; // sets the last activity block for the user if (!Token(token).transferFrom(msg.sender, this, amount)) throw; // attempts to transfer the token to this contract, if fails throws an error emit Deposit(token, msg.sender, amount, balanceOf(token, msg.sender)); // fires the deposit event } function withdraw(address token, uint256 amount) returns (bool success) { //if (safeSub(block.number, lastActiveTransaction[msg.sender]) < inactivityReleasePeriod) throw; // checks if the inactivity period has passed //if (tokens[token][msg.sender] < amount) throw; // checks that user has enough balance if (availableBalanceOf(token, msg.sender) < amount) throw; //tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount); subBalance(token, msg.sender, amount); // subtracts the withdrawed amount from user balance if (token == address(0)) { // checks if withdrawal is a token or ETH, ETH has address 0x00000... if (!msg.sender.send(amount)) throw; // send ETH } else { if (!Token(token).transfer(msg.sender, amount)) throw; // Send token } emit Withdraw(token, msg.sender, amount, balanceOf(token, msg.sender), 0); // fires the Withdraw event } function userAllowFuturesContract(address futuresContract) { if (!futuresContracts[futuresContract]) throw; userAllowedFuturesContracts[msg.sender][futuresContract] = true; } // Withdrawal function used by the server to execute withdrawals function adminWithdraw( address token, // the address of the token to be withdrawn uint256 amount, // the amount to be withdrawn address user, // address of the user uint256 nonce, // nonce to make the request unique uint8 v, // part of user signature bytes32 r, // part of user signature bytes32 s, // part of user signature uint256 feeWithdrawal // the transaction gas fee that will be deducted from the user balance ) onlyAdmin returns (bool success) { bytes32 hash = keccak256(this, token, amount, user, nonce); // creates the hash for the withdrawal request if (withdrawn[hash]) throw; // checks if the withdrawal was already executed, if true, throws an error withdrawn[hash] = true; // sets the withdrawal as executed if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) != user) throw; // checks that the provided signature is valid if (feeWithdrawal > 50 finney) feeWithdrawal = 50 finney; // checks that the gas fee is not higher than 0.05 ETH //if (tokens[token][user] < amount) throw; // checks that user has enough balance if (availableBalanceOf(token, user) < amount) throw; // checks that user has enough balance //tokens[token][user] = safeSub(tokens[token][user], amount); // subtracts the withdrawal amount from the user balance subBalance(token, user, amount); // subtracts the withdrawal amount from the user balance //tokens[address(0)][user] = safeSub(tokens[address(0x0)][user], feeWithdrawal); // subtracts the gas fee from the user ETH balance subBalance(address(0), user, feeWithdrawal); // subtracts the gas fee from the user ETH balance //tokens[address(0)][feeAccount] = safeAdd(tokens[address(0)][feeAccount], feeWithdrawal); // moves the gas fee to the feeAccount addBalance(address(0), feeAccount, feeWithdrawal); // moves the gas fee to the feeAccount if (token == address(0)) { // checks if the withdrawal is in ETH or Tokens if (!user.send(amount)) throw; // sends ETH } else { if (!Token(token).transfer(user, amount)) throw; // sends tokens } lastActiveTransaction[user] = block.number; // sets last user activity block emit Withdraw(token, user, amount, balanceOf(token, user), feeWithdrawal); // fires the withdraw event } function batchAdminWithdraw( address[] token, // the address of the token to be withdrawn uint256[] amount, // the amount to be withdrawn address[] user, // address of the user uint256[] nonce, // nonce to make the request unique uint8[] v, // part of user signature bytes32[] r, // part of user signature bytes32[] s, // part of user signature uint256[] feeWithdrawal // the transaction gas fee that will be deducted from the user balance ) onlyAdmin { for (uint i = 0; i < amount.length; i++) { adminWithdraw( token[i], amount[i], user[i], nonce[i], v[i], r[i], s[i], feeWithdrawal[i] ); } } function getMakerTakerBalances(address token, address maker, address taker) view returns (uint256[4]) { return [ balanceOf(token, maker), balanceOf(token, taker), getReserve(token, maker), getReserve(token, taker) ]; } // Structure that holds order values, used inside the trade() function struct OrderPair { uint256 makerAmountBuy; // amount being bought by the maker uint256 makerAmountSell; // amount being sold by the maker uint256 makerNonce; // maker order nonce, makes the order unique uint256 takerAmountBuy; // amount being bought by the taker uint256 takerAmountSell; // amount being sold by the taker uint256 takerNonce; // taker order nonce uint256 takerGasFee; // taker gas fee, taker pays the gas uint256 takerIsBuying; // true/false taker is the buyer address makerTokenBuy; // token bought by the maker address makerTokenSell; // token sold by the maker address maker; // address of the maker address takerTokenBuy; // token bought by the taker address takerTokenSell; // token sold by the taker address taker; // address of the taker bytes32 makerOrderHash; // hash of the maker order bytes32 takerOrderHash; // has of the taker order } // Structure that holds trade values, used inside the trade() function struct TradeValues { uint256 qty; // amount to be trade uint256 invQty; // amount to be traded in the opposite token uint256 makerAmountTaken; // final amount taken by the maker uint256 takerAmountTaken; // final amount taken by the taker } // Trades balances between user accounts function trade( uint8[2] v, bytes32[4] rs, uint256[8] tradeValues, address[6] tradeAddresses ) onlyAdmin returns (uint filledTakerTokenAmount) { /* tradeValues [0] makerAmountBuy [1] makerAmountSell [2] makerNonce [3] takerAmountBuy [4] takerAmountSell [5] takerNonce [6] takerGasFee [7] takerIsBuying tradeAddresses [0] makerTokenBuy [1] makerTokenSell [2] maker [3] takerTokenBuy [4] takerTokenSell [5] taker */ OrderPair memory t = OrderPair({ makerAmountBuy : tradeValues[0], makerAmountSell : tradeValues[1], makerNonce : tradeValues[2], takerAmountBuy : tradeValues[3], takerAmountSell : tradeValues[4], takerNonce : tradeValues[5], takerGasFee : tradeValues[6], takerIsBuying : tradeValues[7], makerTokenBuy : tradeAddresses[0], makerTokenSell : tradeAddresses[1], maker : tradeAddresses[2], takerTokenBuy : tradeAddresses[3], takerTokenSell : tradeAddresses[4], taker : tradeAddresses[5], // tokenBuy amountBuy tokenSell amountSell nonce user makerOrderHash : keccak256(this, tradeAddresses[0], tradeValues[0], tradeAddresses[1], tradeValues[1], tradeValues[2], tradeAddresses[2]), takerOrderHash : keccak256(this, tradeAddresses[3], tradeValues[3], tradeAddresses[4], tradeValues[4], tradeValues[5], tradeAddresses[5]) }); // Checks the signature for the maker order if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.makerOrderHash), v[0], rs[0], rs[1]) != t.maker) { emit LogError(uint8(Errors.INVLID_SIGNATURE), t.makerOrderHash, t.takerOrderHash); return 0; } // Checks the signature for the taker order if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.takerOrderHash), v[1], rs[2], rs[3]) != t.taker) { emit LogError(uint8(Errors.INVLID_SIGNATURE), t.makerOrderHash, t.takerOrderHash); return 0; } // Checks that orders trade the right tokens if (t.makerTokenBuy != t.takerTokenSell || t.makerTokenSell != t.takerTokenBuy) { emit LogError(uint8(Errors.TOKENS_DONT_MATCH), t.makerOrderHash, t.takerOrderHash); return 0; } // tokens don't match // Cheks that gas fee is not higher than 10% if (t.takerGasFee > 100 finney) { emit LogError(uint8(Errors.GAS_TOO_HIGH), t.makerOrderHash, t.takerOrderHash); return 0; } // takerGasFee too high // Checks that the prices match. // Taker always pays the maker price. This part checks that the taker price is as good or better than the maker price if (!( (t.takerIsBuying == 0 && safeMul(t.makerAmountSell, 1 ether) / t.makerAmountBuy >= safeMul(t.takerAmountBuy, 1 ether) / t.takerAmountSell) || (t.takerIsBuying > 0 && safeMul(t.makerAmountBuy, 1 ether) / t.makerAmountSell <= safeMul(t.takerAmountSell, 1 ether) / t.takerAmountBuy) )) { emit LogError(uint8(Errors.INVLID_PRICE), t.makerOrderHash, t.takerOrderHash); return 0; // prices don't match } // Initializing trade values structure TradeValues memory tv = TradeValues({ qty : 0, invQty : 0, makerAmountTaken : 0, takerAmountTaken : 0 }); // maker buy, taker sell if (t.takerIsBuying == 0) { // traded quantity is the smallest quantity between the maker and the taker, takes into account amounts already filled on the orders tv.qty = min(safeSub(t.makerAmountBuy, orderFills[t.makerOrderHash]), safeSub(t.takerAmountSell, safeMul(orderFills[t.takerOrderHash], t.takerAmountSell) / t.takerAmountBuy)); if (tv.qty == 0) { // order was already filled emit LogError(uint8(Errors.ORDER_ALREADY_FILLED), t.makerOrderHash, t.takerOrderHash); return 0; } // the traded quantity in opposite token terms tv.invQty = safeMul(tv.qty, t.makerAmountSell) / t.makerAmountBuy; // take fee from Token balance tv.makerAmountTaken = safeSub(tv.qty, safeMul(tv.qty, makerFee) / (1 ether)); // net amount received by maker, excludes maker fee //tokens[t.makerTokenBuy][feeAccount] = safeAdd(tokens[t.makerTokenBuy][feeAccount], safeMul(tv.qty, makerFee) / (1 ether)); // add maker fee to feeAccount addBalance(t.makerTokenBuy, feeAccount, safeMul(tv.qty, makerFee) / (1 ether)); // add maker fee to feeAccount // take fee from Token balance tv.takerAmountTaken = safeSub(safeSub(tv.invQty, safeMul(tv.invQty, takerFee) / (1 ether)), safeMul(tv.invQty, t.takerGasFee) / (1 ether)); // amount taken from taker minus taker fee //tokens[t.takerTokenBuy][feeAccount] = safeAdd(tokens[t.takerTokenBuy][feeAccount], safeAdd(safeMul(tv.invQty, takerFee) / (1 ether), safeMul(tv.invQty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount addBalance(t.takerTokenBuy, feeAccount, safeAdd(safeMul(tv.invQty, takerFee) / (1 ether), safeMul(tv.invQty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount //tokens[t.makerTokenSell][t.maker] = safeSub(tokens[t.makerTokenSell][t.maker], tv.invQty); // subtract sold token amount from maker balance subBalance(t.makerTokenSell, t.maker, tv.invQty); // subtract sold token amount from maker balance //tokens[t.makerTokenBuy][t.maker] = safeAdd(tokens[t.makerTokenBuy][t.maker], tv.makerAmountTaken); // add bought token amount to maker addBalance(t.makerTokenBuy, t.maker, tv.makerAmountTaken); // add bought token amount to maker //tokens[t.makerTokenBuy][tv.makerReferrer] = safeAdd(tokens[t.makerTokenBuy][tv.makerReferrer], safeMul(tv.qty, makerAffiliateFee) / (1 ether)); // add affiliate commission to maker affiliate balance //tokens[t.takerTokenSell][t.taker] = safeSub(tokens[t.takerTokenSell][t.taker], tv.qty); // subtract the sold token amount from taker subBalance(t.takerTokenSell, t.taker, tv.qty); // subtract the sold token amount from taker //tokens[t.takerTokenBuy][t.taker] = safeAdd(tokens[t.takerTokenBuy][t.taker], tv.takerAmountTaken); // amount received by taker, excludes taker fee //tokens[t.takerTokenBuy][tv.takerReferrer] = safeAdd(tokens[t.takerTokenBuy][tv.takerReferrer], safeMul(tv.invQty, takerAffiliateFee) / (1 ether)); // add affiliate commission to taker affiliate balance addBalance(t.takerTokenBuy, t.taker, tv.takerAmountTaken); // amount received by taker, excludes taker fee orderFills[t.makerOrderHash] = safeAdd(orderFills[t.makerOrderHash], tv.qty); // increase the maker order filled amount orderFills[t.takerOrderHash] = safeAdd(orderFills[t.takerOrderHash], safeMul(tv.qty, t.takerAmountBuy) / t.takerAmountSell); // increase the taker order filled amount lastActiveTransaction[t.maker] = block.number; // set last activity block number for maker lastActiveTransaction[t.taker] = block.number; // set last activity block number for taker // fire Trade event emit Trade( t.takerTokenBuy, tv.qty, t.takerTokenSell, tv.invQty, t.maker, t.taker, makerFee, takerFee, tv.makerAmountTaken , tv.takerAmountTaken, t.makerOrderHash, t.takerOrderHash ); return tv.qty; } // maker sell, taker buy else { // traded quantity is the smallest quantity between the maker and the taker, takes into account amounts already filled on the orders tv.qty = min(safeSub(t.makerAmountSell, safeMul(orderFills[t.makerOrderHash], t.makerAmountSell) / t.makerAmountBuy), safeSub(t.takerAmountBuy, orderFills[t.takerOrderHash])); if (tv.qty == 0) { // order was already filled emit LogError(uint8(Errors.ORDER_ALREADY_FILLED), t.makerOrderHash, t.takerOrderHash); return 0; } // the traded quantity in opposite token terms tv.invQty = safeMul(tv.qty, t.makerAmountBuy) / t.makerAmountSell; // take fee from ETH balance tv.makerAmountTaken = safeSub(tv.invQty, safeMul(tv.invQty, makerFee) / (1 ether)); // net amount received by maker, excludes maker fee //tokens[t.makerTokenBuy][feeAccount] = safeAdd(tokens[t.makerTokenBuy][feeAccount], safeMul(tv.invQty, makerFee) / (1 ether)); // add maker fee to feeAccount addBalance(t.makerTokenBuy, feeAccount, safeMul(tv.invQty, makerFee) / (1 ether)); // add maker fee to feeAccount // process fees for taker // take fee from ETH balance tv.takerAmountTaken = safeSub(safeSub(tv.qty, safeMul(tv.qty, takerFee) / (1 ether)), safeMul(tv.qty, t.takerGasFee) / (1 ether)); // amount taken from taker minus taker fee //tokens[t.takerTokenBuy][feeAccount] = safeAdd(tokens[t.takerTokenBuy][feeAccount], safeAdd(safeMul(tv.qty, takerFee) / (1 ether), safeMul(tv.qty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount addBalance(t.takerTokenBuy, feeAccount, safeAdd(safeMul(tv.qty, takerFee) / (1 ether), safeMul(tv.qty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount //tokens[t.makerTokenSell][t.maker] = safeSub(tokens[t.makerTokenSell][t.maker], tv.qty); // subtract sold token amount from maker balance subBalance(t.makerTokenSell, t.maker, tv.qty); // subtract sold token amount from maker balance //tv.makerAmountTaken = safeSub(tv.invQty, safeMul(tv.invQty, makerFee) / (1 ether)); // net amount received by maker, excludes maker fee //tokens[t.makerTokenBuy][t.maker] = safeAdd(tokens[t.makerTokenBuy][t.maker], tv.makerAmountTaken); // add bought token amount to maker addBalance(t.makerTokenBuy, t.maker, tv.makerAmountTaken); // add bought token amount to maker //tokens[t.makerTokenBuy][tv.makerReferrer] = safeAdd(tokens[t.makerTokenBuy][tv.makerReferrer], safeMul(tv.invQty, makerAffiliateFee) / (1 ether)); // add affiliate commission to maker affiliate balance //tokens[t.takerTokenSell][t.taker] = safeSub(tokens[t.takerTokenSell][t.taker], tv.invQty); // subtract the sold token amount from taker subBalance(t.takerTokenSell, t.taker, tv.invQty); //tv.takerAmountTaken = safeSub(safeSub(tv.qty, safeMul(tv.qty, takerFee) / (1 ether)), safeMul(tv.qty, t.takerGasFee) / (1 ether)); // amount taken from taker minus taker fee //tokens[t.takerTokenBuy][t.taker] = safeAdd(tokens[t.takerTokenBuy][t.taker], tv.takerAmountTaken); // amount received by taker, excludes taker fee addBalance(t.takerTokenBuy, t.taker, tv.takerAmountTaken); // amount received by taker, excludes taker fee //tokens[t.takerTokenBuy][tv.takerReferrer] = safeAdd(tokens[t.takerTokenBuy][tv.takerReferrer], safeMul(tv.qty, takerAffiliateFee) / (1 ether)); // add affiliate commission to taker affiliate balance //tokens[t.makerTokenBuy][feeAccount] = safeAdd(tokens[t.makerTokenBuy][feeAccount], safeMul(tv.invQty, safeSub(makerFee, makerAffiliateFee)) / (1 ether)); // add maker fee excluding affiliate commission to feeAccount //tokens[t.takerTokenBuy][feeAccount] = safeAdd(tokens[t.takerTokenBuy][feeAccount], safeAdd(safeMul(tv.qty, safeSub(takerFee, takerAffiliateFee)) / (1 ether), safeMul(tv.qty, t.takerGasFee) / (1 ether))); // add taker fee excluding affiliate commission to feeAccount orderFills[t.makerOrderHash] = safeAdd(orderFills[t.makerOrderHash], tv.invQty); // increase the maker order filled amount orderFills[t.takerOrderHash] = safeAdd(orderFills[t.takerOrderHash], tv.qty); // increase the taker order filled amount lastActiveTransaction[t.maker] = block.number; // set last activity block number for maker lastActiveTransaction[t.taker] = block.number; // set last activity block number for taker // fire Trade event emit Trade( t.takerTokenBuy, tv.qty, t.takerTokenSell, tv.invQty, t.maker, t.taker, makerFee, takerFee, tv.makerAmountTaken , tv.takerAmountTaken, t.makerOrderHash, t.takerOrderHash ); return tv.qty; } } // Executes multiple trades in one transaction, saves gas fees function batchOrderTrade( uint8[2][] v, bytes32[4][] rs, uint256[8][] tradeValues, address[6][] tradeAddresses ) onlyAdmin { for (uint i = 0; i < tradeAddresses.length; i++) { trade( v[i], rs[i], tradeValues[i], tradeAddresses[i] ); } } // Cancels order by setting amount filled to toal order amount function cancelOrder( /* [0] orderV [1] cancelV */ uint8[2] v, /* [0] orderR [1] orderS [2] cancelR [3] cancelS */ bytes32[4] rs, /* [0] orderAmountBuy [1] orderAmountSell [2] orderNonce [3] cancelNonce [4] cancelFee */ uint256[5] cancelValues, /* [0] orderTokenBuy [1] orderTokenSell [2] orderUser [3] cancelUser */ address[4] cancelAddresses ) onlyAdmin { // Order values should be valid and signed by order owner bytes32 orderHash = keccak256( this, cancelAddresses[0], cancelValues[0], cancelAddresses[1], cancelValues[1], cancelValues[2], cancelAddresses[2] ); require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", orderHash), v[0], rs[0], rs[1]) == cancelAddresses[2]); // Cancel action should be signed by order owner bytes32 cancelHash = keccak256(this, orderHash, cancelAddresses[3], cancelValues[3]); require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", cancelHash), v[1], rs[2], rs[3]) == cancelAddresses[3]); // Order owner should be the same as cancel's initiator require(cancelAddresses[2] == cancelAddresses[3]); // Do not allow to cancel already canceled or filled orders require(orderFills[orderHash] != cancelValues[0]); // Cancel gas fee cannot exceed 0.05 ETh if (cancelValues[4] > 50 finney) { cancelValues[4] = 50 finney; } // Take cancel fee // This operation throws an error if fee amount is greater than the user balance //tokens[address(0)][cancelAddresses[3]] = safeSub(tokens[address(0)][cancelAddresses[3]], cancelValues[4]); subBalance(address(0), cancelAddresses[3], cancelValues[4]); // Cancel order by setting amount filled to total order value, i.e. making the order filled orderFills[orderHash] = cancelValues[0]; // Fire cancel order event emit CancelOrder(cancelHash, orderHash, cancelAddresses[3], cancelAddresses[1], cancelValues[1], cancelValues[4]); } // Returns the smaller of two values function min(uint a, uint b) private pure returns (uint) { return a < b ? a : b; } }
set last activity block number for maker
lastActiveTransaction[t.maker] = block.number;
2,554,823
[ 1, 542, 1142, 5728, 1203, 1300, 364, 312, 6388, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 1142, 3896, 3342, 63, 88, 18, 29261, 65, 1850, 273, 1203, 18, 2696, 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 ]
./full_match/1/0x73cD8626b3cD47B009E68380720CFE6679A3Ec3D/sources/contracts/LockupPlans/VotingTokenLockupPlans.sol
@notice function for a beneficiary to redeem unlocked tokens from a group of plans @dev this will call an internal function for processing the actual redemption of tokens, which will withdraw unlocked tokens and deliver them to the beneficiary @dev this function will redeem only a partial amount of tokens based on a redemption timestamp that is in the past. This allows holders to redeem less than their fully unlocked amount for various reasons @param planIds is the array of the NFT planIds that are to be redeemed. If any have no redeemable balance they will be skipped. @param redemptionTime is the timestamp which will calculate the amount of tokens redeemable and redeem them based on that timestamp
function partialRedeemPlans(uint256[] calldata planIds, uint256 redemptionTime) external nonReentrant { require(redemptionTime < block.timestamp, '!future'); _redeemPlans(planIds, redemptionTime); }
4,922,647
[ 1, 915, 364, 279, 27641, 74, 14463, 814, 358, 283, 24903, 25966, 2430, 628, 279, 1041, 434, 21440, 225, 333, 903, 745, 392, 2713, 445, 364, 4929, 326, 3214, 283, 19117, 375, 434, 2430, 16, 1492, 903, 598, 9446, 25966, 2430, 471, 11795, 2182, 358, 326, 27641, 74, 14463, 814, 225, 333, 445, 903, 283, 24903, 1338, 279, 4702, 3844, 434, 2430, 2511, 603, 279, 283, 19117, 375, 2858, 716, 353, 316, 326, 8854, 18, 1220, 5360, 366, 4665, 358, 283, 24903, 5242, 2353, 3675, 7418, 25966, 3844, 364, 11191, 14000, 225, 4995, 2673, 353, 326, 526, 434, 326, 423, 4464, 4995, 2673, 716, 854, 358, 506, 283, 24903, 329, 18, 971, 1281, 1240, 1158, 283, 24903, 429, 11013, 2898, 903, 506, 9700, 18, 225, 283, 19117, 375, 950, 353, 326, 2858, 1492, 903, 4604, 326, 3844, 434, 2430, 283, 24903, 429, 471, 283, 24903, 2182, 2511, 603, 716, 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, 225, 445, 4702, 426, 24903, 22846, 12, 11890, 5034, 8526, 745, 892, 4995, 2673, 16, 2254, 5034, 283, 19117, 375, 950, 13, 3903, 1661, 426, 8230, 970, 288, 203, 565, 2583, 12, 266, 19117, 375, 950, 411, 1203, 18, 5508, 16, 11817, 14343, 8284, 203, 565, 389, 266, 24903, 22846, 12, 7088, 2673, 16, 283, 19117, 375, 950, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; /// @title Provides helper functions to determine the validity of passed signatures. /// @author Noah Zinsmeister /// @dev Supports both prefixed and un-prefixed signatures. contract SignatureVerifier { /// @notice Determines whether the passed signature of `messageHash` was made by the private key of `_address`. /// @param _address The address that may or may not have signed the passed messageHash. /// @param messageHash The messageHash that may or may not have been signed. /// @param v The v component of the signature. /// @param r The r component of the signature. /// @param s The s component of the signature. /// @return true if the signature can be verified, false otherwise. function isSigned(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) public pure returns (bool) { return _isSigned(_address, messageHash, v, r, s) || _isSignedPrefixed(_address, messageHash, v, r, s); } /// @dev Checks unprefixed signatures. function _isSigned(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) internal pure returns (bool) { return ecrecover(messageHash, v, r, s) == _address; } /// @dev Checks prefixed signatures. function _isSignedPrefixed(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) internal pure returns (bool) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; return _isSigned(_address, keccak256(abi.encodePacked(prefix, messageHash)), v, r, s); } } /// @title An implementation of the set data structure for addresses. /// @author Noah Zinsmeister /// @dev O(1) insertion, removal, contains, and length functions. library AddressSet { struct Set { address[] members; mapping(address => uint) memberIndices; } /// @dev Inserts an element into a set. If the element already exists in the set, the function is a no-op. /// @param self The set to insert into. /// @param other The element to insert. function insert(Set storage self, address other) internal { if (!contains(self, other)) { self.memberIndices[other] = self.members.push(other); } } /// @dev Removes an element from a set. If the element does not exist in the set, the function is a no-op. /// @param self The set to remove from. /// @param other The element to remove. function remove(Set storage self, address other) internal { if (contains(self, other)) { // replace other with the last element self.members[self.memberIndices[other] - 1] = self.members[length(self) - 1]; // reflect this change in the indices self.memberIndices[self.members[self.memberIndices[other] - 1]] = self.memberIndices[other]; delete self.memberIndices[other]; // remove the last element self.members.pop(); } } /// @dev Checks set membership. /// @param self The set to check membership in. /// @param other The element to check membership of. /// @return true if the element is in the set, false otherwise. function contains(Set storage self, address other) internal view returns (bool) { return ( // solium-disable-line operator-whitespace self.memberIndices[other] > 0 && self.members.length >= self.memberIndices[other] && self.members[self.memberIndices[other] - 1] == other ); } /// @dev Returns the number of elements in a set. /// @param self The set to check the length of. /// @return The number of elements in the set. function length(Set storage self) internal view returns (uint) { return self.members.length; } } /// @title The ERC-1484 Identity Registry. /// @author Noah Zinsmeister /// @author Andy Chorlian contract IdentityRegistry is SignatureVerifier { using AddressSet for AddressSet.Set; // Identity Data Structure and Parameters ////////////////////////////////////////////////////////////////////////// struct Identity { address recoveryAddress; AddressSet.Set associatedAddresses; AddressSet.Set providers; AddressSet.Set resolvers; } mapping (uint => Identity) private identityDirectory; mapping (address => uint) private associatedAddressDirectory; uint public nextEIN = 1; uint public maxAssociatedAddresses = 50; // Signature Timeout /////////////////////////////////////////////////////////////////////////////////////////////// uint public signatureTimeout = 1 days; /// @dev Enforces that the passed timestamp is within signatureTimeout seconds of now. /// @param timestamp The timestamp to check the validity of. modifier ensureSignatureTimeValid(uint timestamp) { require( // solium-disable-next-line security/no-block-members block.timestamp >= timestamp && block.timestamp < timestamp + signatureTimeout, "Timestamp is not valid." ); _; } // Recovery Address Change Logging ///////////////////////////////////////////////////////////////////////////////// struct RecoveryAddressChange { uint timestamp; address oldRecoveryAddress; } mapping (uint => RecoveryAddressChange) private recoveryAddressChangeLogs; // Recovery Logging //////////////////////////////////////////////////////////////////////////////////////////////// struct Recovery { uint timestamp; bytes32 hashedOldAssociatedAddresses; } mapping (uint => Recovery) private recoveryLogs; // Recovery Timeout //////////////////////////////////////////////////////////////////////////////////////////////// uint public recoveryTimeout = 2 weeks; /// @dev Checks if the passed EIN has changed their recovery address within recoveryTimeout seconds of now. function canChangeRecoveryAddress(uint ein) private view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > recoveryAddressChangeLogs[ein].timestamp + recoveryTimeout; } /// @dev Checks if the passed EIN has recovered within recoveryTimeout seconds of now. function canRecover(uint ein) private view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > recoveryLogs[ein].timestamp + recoveryTimeout; } // Identity View Functions ///////////////////////////////////////////////////////////////////////////////////////// /// @notice Checks if the passed EIN exists. /// @dev Does not throw. /// @param ein The EIN to check the existence of. /// @return true if the passed EIN exists, false otherwise. function identityExists(uint ein) public view returns (bool) { return ein < nextEIN && ein > 0; } /// @dev Ensures that the passed EIN exists. /// @param ein The EIN to check the existence of. modifier _identityExists(uint ein) { require(identityExists(ein), "The identity does not exist."); _; } /// @notice Checks if the passed address is associated with an Identity. /// @dev Does not throw. /// @param _address The address to check. /// @return true if the passed address is associated with an Identity, false otherwise. function hasIdentity(address _address) public view returns (bool) { return identityExists(associatedAddressDirectory[_address]); } /// @dev Ensures that the passed address is or is not associated with an Identity. /// @param _address The address to check. /// @param check If true, ensures that the address has an Identity, if false, vice versa. /// @return true if the associated status is equal to check, false otherwise. modifier _hasIdentity(address _address, bool check) { require( hasIdentity(_address) == check, check ? "The passed address does not have an identity but should." : "The passed address has an identity but should not." ); _; } /// @notice Gets the EIN associated with the passed address. /// @dev Throws if the address is not associated with an Identity. /// @param _address The address to check. /// @return The associated EIN. function getEIN(address _address) public view _hasIdentity(_address, true) returns (uint ein) { return associatedAddressDirectory[_address]; } /// @notice Checks whether the passed EIN is associated with the passed address. /// @dev Does not throw. /// @param ein The EIN to check. /// @param _address The address to check. /// @return true if the passed address is associated with the passed EIN, false otherwise. function isAssociatedAddressFor(uint ein, address _address) public view returns (bool) { return identityDirectory[ein].associatedAddresses.contains(_address); } /// @notice Checks whether the passed provider is set for the passed EIN. /// @dev Does not throw. /// @param ein The EIN to check. /// @param provider The provider to check. /// @return true if the provider is set for the passed EIN, false otherwise. function isProviderFor(uint ein, address provider) public view returns (bool) { return identityDirectory[ein].providers.contains(provider); } /// @dev Ensures that the msg.sender is a provider for the passed EIN. /// @param ein The EIN to check. modifier _isProviderFor(uint ein) { require(isProviderFor(ein, msg.sender), "The identity has not set the passed provider."); _; } /// @notice Checks whether the passed resolver is set for the passed EIN. /// @dev Does not throw. /// @param ein The EIN to check. /// @param resolver The resolver to check. /// @return true if the resolver is set for the passed EIN, false otherwise. function isResolverFor(uint ein, address resolver) public view returns (bool) { return identityDirectory[ein].resolvers.contains(resolver); } /// @notice Gets all identity-related information for the passed EIN. /// @dev Throws if the passed EIN does not exist. /// @param ein The EIN to get information for. /// @return All the information for the Identity denominated by the passed EIN. function getIdentity(uint ein) public view _identityExists(ein) returns ( address recoveryAddress, address[] memory associatedAddresses, address[] memory providers, address[] memory resolvers ) { Identity storage _identity = identityDirectory[ein]; return ( _identity.recoveryAddress, _identity.associatedAddresses.members, _identity.providers.members, _identity.resolvers.members ); } // Identity Management Functions /////////////////////////////////////////////////////////////////////////////////// /// @notice Create an new Identity for the transaction sender. /// @dev Sets the msg.sender as the only associatedAddress. /// @param recoveryAddress A recovery address to set for the new Identity. /// @param providers A list of providers to set for the new Identity. /// @param resolvers A list of resolvers to set for the new Identity. /// @return The EIN of the new Identity. function createIdentity(address recoveryAddress, address[] memory providers, address[] memory resolvers) public returns (uint ein) { return createIdentity(recoveryAddress, msg.sender, providers, resolvers, false); } /// @notice Allows creation of a new Identity for the passed associatedAddress. /// @param recoveryAddress A recovery address to set for the new Identity. /// @param associatedAddress An associated address to set for the new Identity (must have produced the signature). /// @param providers A list of providers to set for the new Identity. /// @param resolvers A list of resolvers to set for the new Identity. /// @param v The v component of the signature. /// @param r The r component of the signature. /// @param s The s component of the signature. /// @param timestamp The timestamp of the signature. /// @return The EIN of the new Identity. function createIdentityDelegated( address recoveryAddress, address associatedAddress, address[] memory providers, address[] memory resolvers, uint8 v, bytes32 r, bytes32 s, uint timestamp ) public ensureSignatureTimeValid(timestamp) returns (uint ein) { require( isSigned( associatedAddress, keccak256( abi.encodePacked( byte(0x19), byte(0), address(this), "I authorize the creation of an Identity on my behalf.", recoveryAddress, associatedAddress, providers, resolvers, timestamp ) ), v, r, s ), "Permission denied." ); return createIdentity(recoveryAddress, associatedAddress, providers, resolvers, true); } /// @dev Common logic for all identity creation. function createIdentity( address recoveryAddress, address associatedAddress, address[] memory providers, address[] memory resolvers, bool delegated ) private _hasIdentity(associatedAddress, false) returns (uint) { uint ein = nextEIN++; Identity storage _identity = identityDirectory[ein]; _identity.recoveryAddress = recoveryAddress; addAssociatedAddress(ein, associatedAddress); addProviders(ein, providers, delegated); addResolvers(ein, resolvers, delegated); emit IdentityCreated(msg.sender, ein, recoveryAddress, associatedAddress, providers, resolvers, delegated); return ein; } /// @notice Allows an associated address to add another associated address to its Identity. /// @param approvingAddress An associated address for an Identity. /// @param addressToAdd A new address to set for the Identity of the sender. /// @param v The v component of the signature. /// @param r The r component of the signature. /// @param s The s component of the signature. /// @param timestamp The timestamp of the signature. function addAssociatedAddress( address approvingAddress, address addressToAdd, uint8 v, bytes32 r, bytes32 s, uint timestamp ) public ensureSignatureTimeValid(timestamp) { bool fromApprovingAddress = msg.sender == approvingAddress; require( fromApprovingAddress || msg.sender == addressToAdd, "One or both of the passed addresses are malformed." ); uint ein = getEIN(approvingAddress); require( isSigned( fromApprovingAddress ? addressToAdd : approvingAddress, keccak256( abi.encodePacked( byte(0x19), byte(0), address(this), fromApprovingAddress ? "I authorize being added to this Identity." : "I authorize adding this address to my Identity.", ein, addressToAdd, timestamp ) ), v, r, s ), "Permission denied." ); addAssociatedAddress(ein, addressToAdd); emit AssociatedAddressAdded(msg.sender, ein, approvingAddress, addressToAdd, false); } /// @notice Allows addition of an associated address to an Identity. /// @dev The first signature must be that of the approvingAddress. /// @param approvingAddress An associated address for an Identity. /// @param addressToAdd A new address to set for the Identity of approvingAddress. /// @param v The v component of the signatures. /// @param r The r component of the signatures. /// @param s The s component of the signatures. /// @param timestamp The timestamp of the signatures. function addAssociatedAddressDelegated( address approvingAddress, address addressToAdd, uint8[2] memory v, bytes32[2] memory r, bytes32[2] memory s, uint[2] memory timestamp ) public ensureSignatureTimeValid(timestamp[0]) ensureSignatureTimeValid(timestamp[1]) { uint ein = getEIN(approvingAddress); require( isSigned( approvingAddress, keccak256( abi.encodePacked( byte(0x19), byte(0), address(this), "I authorize adding this address to my Identity.", ein, addressToAdd, timestamp[0] ) ), v[0], r[0], s[0] ), "Permission denied from approving address." ); require( isSigned( addressToAdd, keccak256( abi.encodePacked( byte(0x19), byte(0), address(this), "I authorize being added to this Identity.", ein, addressToAdd, timestamp[1] ) ), v[1], r[1], s[1] ), "Permission denied from address to add." ); addAssociatedAddress(ein, addressToAdd); emit AssociatedAddressAdded(msg.sender, ein, approvingAddress, addressToAdd, true); } /// @dev Common logic for all address addition. function addAssociatedAddress(uint ein, address addressToAdd) private _hasIdentity(addressToAdd, false) { require( identityDirectory[ein].associatedAddresses.length() < maxAssociatedAddresses, "Too many addresses." ); identityDirectory[ein].associatedAddresses.insert(addressToAdd); associatedAddressDirectory[addressToAdd] = ein; } /// @notice Allows an associated address to remove itself from its Identity. function removeAssociatedAddress() public { uint ein = getEIN(msg.sender); removeAssociatedAddress(ein, msg.sender); emit AssociatedAddressRemoved(msg.sender, ein, msg.sender, false); } /// @notice Allows removal of an associated address from an Identity. /// @param addressToRemove An associated address to remove from its Identity. /// @param v The v component of the signature. /// @param r The r component of the signature. /// @param s The s component of the signature. /// @param timestamp The timestamp of the signature. function removeAssociatedAddressDelegated(address addressToRemove, uint8 v, bytes32 r, bytes32 s, uint timestamp) public ensureSignatureTimeValid(timestamp) { uint ein = getEIN(addressToRemove); require( isSigned( addressToRemove, keccak256( abi.encodePacked( byte(0x19), byte(0), address(this), "I authorize removing this address from my Identity.", ein, addressToRemove, timestamp ) ), v, r, s ), "Permission denied." ); removeAssociatedAddress(ein, addressToRemove); emit AssociatedAddressRemoved(msg.sender, ein, addressToRemove, true); } /// @dev Common logic for all address removal. function removeAssociatedAddress(uint ein, address addressToRemove) private { identityDirectory[ein].associatedAddresses.remove(addressToRemove); delete associatedAddressDirectory[addressToRemove]; } /// @notice Allows an associated address to add providers to its Identity. /// @param providers A list of providers. function addProviders(address[] memory providers) public { addProviders(getEIN(msg.sender), providers, false); } /// @notice Allows providers to add providers to an Identity. /// @param ein The EIN to add providers to. /// @param providers A list of providers. function addProvidersFor(uint ein, address[] memory providers) public _isProviderFor(ein) { addProviders(ein, providers, true); } /// @dev Common logic for all provider adding. function addProviders(uint ein, address[] memory providers, bool delegated) private { Identity storage _identity = identityDirectory[ein]; for (uint i; i < providers.length; i++) { _identity.providers.insert(providers[i]); emit ProviderAdded(msg.sender, ein, providers[i], delegated); } } /// @notice Allows an associated address to remove providers from its Identity. /// @param providers A list of providers. function removeProviders(address[] memory providers) public { removeProviders(getEIN(msg.sender), providers, false); } /// @notice Allows providers to remove providers to an Identity. /// @param ein The EIN to remove providers from. /// @param providers A list of providers. function removeProvidersFor(uint ein, address[] memory providers) public _isProviderFor(ein) { removeProviders(ein, providers, true); } /// @dev Common logic for all provider removal. function removeProviders(uint ein, address[] memory providers, bool delegated) private { Identity storage _identity = identityDirectory[ein]; for (uint i; i < providers.length; i++) { _identity.providers.remove(providers[i]); emit ProviderRemoved(msg.sender, ein, providers[i], delegated); } } /// @notice Allows an associated address to add resolvers to its Identity. /// @param resolvers A list of resolvers. function addResolvers(address[] memory resolvers) public { addResolvers(getEIN(msg.sender), resolvers, false); } /// @notice Allows providers to add resolvers to an Identity. /// @param ein The EIN to add resolvers to. /// @param resolvers A list of resolvers. function addResolversFor(uint ein, address[] memory resolvers) public _isProviderFor(ein) { addResolvers(ein, resolvers, true); } /// @dev Common logic for all resolver adding. function addResolvers(uint ein, address[] memory resolvers, bool delegated) private { Identity storage _identity = identityDirectory[ein]; for (uint i; i < resolvers.length; i++) { _identity.resolvers.insert(resolvers[i]); emit ResolverAdded(msg.sender, ein, resolvers[i], delegated); } } /// @notice Allows an associated address to remove resolvers from its Identity. /// @param resolvers A list of resolvers. function removeResolvers(address[] memory resolvers) public { removeResolvers(getEIN(msg.sender), resolvers, true); } /// @notice Allows providers to remove resolvers from an Identity. /// @param ein The EIN to remove resolvers from. /// @param resolvers A list of resolvers. function removeResolversFor(uint ein, address[] memory resolvers) public _isProviderFor(ein) { removeResolvers(ein, resolvers, true); } /// @dev Common logic for all resolver removal. function removeResolvers(uint ein, address[] memory resolvers, bool delegated) private { Identity storage _identity = identityDirectory[ein]; for (uint i; i < resolvers.length; i++) { _identity.resolvers.remove(resolvers[i]); emit ResolverRemoved(msg.sender, ein, resolvers[i], delegated); } } // Recovery Management Functions /////////////////////////////////////////////////////////////////////////////////// /// @notice Allows an associated address to change the recovery address for its Identity. /// @dev Recovery addresses can be changed at most once every recoveryTimeout seconds. /// @param newRecoveryAddress A recovery address to set for the sender's EIN. function triggerRecoveryAddressChange(address newRecoveryAddress) public { triggerRecoveryAddressChange(getEIN(msg.sender), newRecoveryAddress, false); } /// @notice Allows providers to change the recovery address for an Identity. /// @dev Recovery addresses can be changed at most once every recoveryTimeout seconds. /// @param ein The EIN to set the recovery address of. /// @param newRecoveryAddress A recovery address to set for the passed EIN. function triggerRecoveryAddressChangeFor(uint ein, address newRecoveryAddress) public _isProviderFor(ein) { triggerRecoveryAddressChange(ein, newRecoveryAddress, true); } /// @dev Common logic for all recovery address changes. function triggerRecoveryAddressChange(uint ein, address newRecoveryAddress, bool delegated) private { Identity storage _identity = identityDirectory[ein]; require(canChangeRecoveryAddress(ein), "Cannot trigger a change in recovery address yet."); // solium-disable-next-line security/no-block-members recoveryAddressChangeLogs[ein] = RecoveryAddressChange(block.timestamp, _identity.recoveryAddress); emit RecoveryAddressChangeTriggered(msg.sender, ein, _identity.recoveryAddress, newRecoveryAddress, delegated); _identity.recoveryAddress = newRecoveryAddress; } /// @notice Allows recovery addresses to trigger the recovery process for an Identity. /// @dev msg.sender must be current recovery address, or the old one if it was changed recently. /// @param ein The EIN to trigger recovery for. /// @param newAssociatedAddress A recovery address to set for the passed EIN. /// @param v The v component of the signature. /// @param r The r component of the signature. /// @param s The s component of the signature. /// @param timestamp The timestamp of the signature. function triggerRecovery(uint ein, address newAssociatedAddress, uint8 v, bytes32 r, bytes32 s, uint timestamp) public _identityExists(ein) _hasIdentity(newAssociatedAddress, false) ensureSignatureTimeValid(timestamp) { require(canRecover(ein), "Cannot trigger recovery yet."); Identity storage _identity = identityDirectory[ein]; // ensure the sender is the recovery address/old recovery address if there's been a recent change if (canChangeRecoveryAddress(ein)) { require( msg.sender == _identity.recoveryAddress, "Only the current recovery address can trigger recovery." ); } else { require( msg.sender == recoveryAddressChangeLogs[ein].oldRecoveryAddress, "Only the recently removed recovery address can trigger recovery." ); } require( isSigned( newAssociatedAddress, keccak256( abi.encodePacked( byte(0x19), byte(0), address(this), "I authorize being added to this Identity via recovery.", ein, newAssociatedAddress, timestamp ) ), v, r, s ), "Permission denied." ); // log the old associated addresses to facilitate destruction if necessary recoveryLogs[ein] = Recovery( block.timestamp, // solium-disable-line security/no-block-members keccak256(abi.encodePacked(_identity.associatedAddresses.members)) ); emit RecoveryTriggered(msg.sender, ein, _identity.associatedAddresses.members, newAssociatedAddress); // remove identity data, and add the new address as the sole associated address resetIdentityData(_identity, msg.sender, false); addAssociatedAddress(ein, newAssociatedAddress); } /// @notice Allows associated addresses recently removed via recovery to permanently disable their old Identity. /// @param ein The EIN to trigger destruction of. /// @param firstChunk The array of addresses before the msg.sender in the pre-recovery associated addresses array. /// @param lastChunk The array of addresses after the msg.sender in the pre-recovery associated addresses array. /// @param resetResolvers true if the destroyer wants resolvers to be removed, false otherwise. function triggerDestruction(uint ein, address[] memory firstChunk, address[] memory lastChunk, bool resetResolvers) public _identityExists(ein) { require(!canRecover(ein), "Recovery has not recently been triggered."); Identity storage _identity = identityDirectory[ein]; // ensure that the msg.sender was an old associated address for the referenced identity address payable[1] memory middleChunk = [msg.sender]; require( keccak256( abi.encodePacked(firstChunk, middleChunk, lastChunk) ) == recoveryLogs[ein].hashedOldAssociatedAddresses, "Cannot destroy an EIN from an address that was not recently removed from said EIN via recovery." ); emit IdentityDestroyed(msg.sender, ein, _identity.recoveryAddress, resetResolvers); resetIdentityData(_identity, address(0), resetResolvers); } /// @dev Common logic for clearing the data of an Identity. function resetIdentityData(Identity storage identity, address newRecoveryAddress, bool resetResolvers) private { for (uint i; i < identity.associatedAddresses.members.length; i++) { delete associatedAddressDirectory[identity.associatedAddresses.members[i]]; } delete identity.associatedAddresses; delete identity.providers; if (resetResolvers) delete identity.resolvers; identity.recoveryAddress = newRecoveryAddress; } // Events ////////////////////////////////////////////////////////////////////////////////////////////////////////// event IdentityCreated( address indexed initiator, uint indexed ein, address recoveryAddress, address associatedAddress, address[] providers, address[] resolvers, bool delegated ); event AssociatedAddressAdded( address indexed initiator, uint indexed ein, address approvingAddress, address addedAddress, bool delegated ); event AssociatedAddressRemoved(address indexed initiator, uint indexed ein, address removedAddress, bool delegated); event ProviderAdded(address indexed initiator, uint indexed ein, address provider, bool delegated); event ProviderRemoved(address indexed initiator, uint indexed ein, address provider, bool delegated); event ResolverAdded(address indexed initiator, uint indexed ein, address resolvers, bool delegated); event ResolverRemoved(address indexed initiator, uint indexed ein, address resolvers, bool delegated); event RecoveryAddressChangeTriggered( address indexed initiator, uint indexed ein, address oldRecoveryAddress, address newRecoveryAddress, bool delegated ); event RecoveryTriggered( address indexed initiator, uint indexed ein, address[] oldAssociatedAddresses, address newAssociatedAddress ); event IdentityDestroyed(address indexed initiator, uint indexed ein, address recoveryAddress, bool resolversReset); }
@notice Allows providers to remove resolvers from an Identity. @param ein The EIN to remove resolvers from. @param resolvers A list of resolvers.
function removeResolversFor(uint ein, address[] memory resolvers) public _isProviderFor(ein) { removeResolvers(ein, resolvers, true); }
5,497,706
[ 1, 19132, 9165, 358, 1206, 24170, 628, 392, 7808, 18, 225, 16315, 1021, 512, 706, 358, 1206, 24170, 628, 18, 225, 24170, 432, 666, 434, 24170, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 28715, 1290, 12, 11890, 16315, 16, 1758, 8526, 3778, 24170, 13, 1071, 389, 291, 2249, 1290, 12, 13685, 13, 288, 203, 3639, 1206, 28715, 12, 13685, 16, 24170, 16, 638, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0x79C49737f6C7b7C0119316488812d6d4351d0a35/sources/contracts/Contract.sol
a mappingg of all wallet address that purchase entries for raffle, the number tracks the number of entries purchased per wallet
mapping(address => uint256) public entryCount;
3,800,092
[ 1, 69, 2874, 75, 434, 777, 9230, 1758, 716, 23701, 3222, 364, 767, 1403, 298, 16, 326, 1300, 13933, 326, 1300, 434, 3222, 5405, 343, 8905, 1534, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 1241, 1380, 31, 4202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: BSD-2-Clause // SwingingMarketMaker.sol // Copyright (c) 2021 Giry SAS. All rights reserved. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. pragma solidity ^0.8.10; pragma abicoder v2; import "../../CompoundTrader.sol"; contract SwingingMarketMaker is CompoundTrader { using P.Offer for P.Offer.t; event MissingPriceConverter(address token0, address token1); event NotEnoughProvision(uint amount); // price[B][A] : price of A in B = p(B|A) = volume of B obtained/volume of A given mapping(address => mapping(address => uint)) private price; // price[tk0][tk1] is in tk0 precision mapping(address => mapping(address => uint)) private offers; constructor( address _unitroller, address payable _MGV, address wethAddress ) CompoundModule(_unitroller, wethAddress) MangroveOffer(_MGV) { setGasreq(1_000_000); } // sets P(tk0|tk1) // one wants P(tk0|tk1).P(tk1|tk0) >= 1 function setPrice( address tk0, address tk1, uint p ) external onlyAdmin { price[tk0][tk1] = p; // has tk0.decimals() decimals } function startStrat( address tk0, address tk1, uint gives // amount of tk0 (with tk0.decimals() decimals) ) external payable onlyAdmin { MGV.fund{value: msg.value}(); require(repostOffer(tk0, tk1, gives), "Could not start strategy"); IERC20(tk0).approve(address(MGV), type(uint).max); // approving MGV for tk0 transfer IERC20(tk1).approve(address(MGV), type(uint).max); // approving MGV for tk1 transfer } // at this stage contract has `received` amount in token0 function repostOffer( address outbound_tkn, address inbound_tkn, uint gives // in outbound_tkn ) internal returns (bool) { // computing how much inbound_tkn one should ask for `gives` amount of outbound tokens // NB p_10 has inbound_tkn.decimals() number of decimals uint p_10 = price[inbound_tkn][outbound_tkn]; if (p_10 == 0) { // ! p_10 has the decimals of inbound_tkn emit MissingPriceConverter(inbound_tkn, outbound_tkn); return false; } uint wants = div_( mul_(p_10, gives), // p(base|quote).(gives:quote) : base 10**(IERC20(outbound_tkn).decimals()) ); // in base units uint offerId = offers[outbound_tkn][inbound_tkn]; if (offerId == 0) { try MGV.newOffer(outbound_tkn, inbound_tkn, wants, gives, OFR_GASREQ, 0, 0) returns (uint id) { if (id > 0) { offers[outbound_tkn][inbound_tkn] = id; return true; } else { return false; } } catch { return false; } } else { try MGV.updateOffer( outbound_tkn, inbound_tkn, wants, gives, // offerId is already on the book so a good pivot OFR_GASREQ, // default value 0, // default value offerId, offerId ) { return true; } catch Error(string memory message) { emit PosthookFail(outbound_tkn, inbound_tkn, offerId, message); return false; } } } function __posthookSuccess__(MgvLib.SingleOrder calldata order) internal override { address token0 = order.outbound_tkn; address token1 = order.inbound_tkn; uint offer_received = order.offer.wants(); // amount with token1.decimals() decimals repostOffer({ outbound_tkn: token1, inbound_tkn: token0, gives: offer_received }); } function __get__(uint amount, MgvLib.SingleOrder calldata order) internal virtual override returns (uint) { // checks whether `this` contract has enough `base` token uint missingGet = SingleUser.__get__(amount, order); // if not tries to fetch missing liquidity on compound using `CompoundTrader`'s strat return super.__get__(missingGet, order); } }
at this stage contract has `received` amount in token0 computing how much inbound_tkn one should ask for `gives` amount of outbound tokens NB p_10 has inbound_tkn.decimals() number of decimals ! p_10 has the decimals of inbound_tkn
function repostOffer( address outbound_tkn, address inbound_tkn, ) internal returns (bool) { uint p_10 = price[inbound_tkn][outbound_tkn]; if (p_10 == 0) { emit MissingPriceConverter(inbound_tkn, outbound_tkn); return false; } uint wants = div_( 10**(IERC20(outbound_tkn).decimals()) uint offerId = offers[outbound_tkn][inbound_tkn]; if (offerId == 0) { try MGV.newOffer(outbound_tkn, inbound_tkn, wants, gives, OFR_GASREQ, 0, 0) returns (uint id) { if (id > 0) { offers[outbound_tkn][inbound_tkn] = id; return true; return false; } return false; } try MGV.updateOffer( outbound_tkn, inbound_tkn, wants, gives, offerId ) { return true; emit PosthookFail(outbound_tkn, inbound_tkn, offerId, message); return false; } } }
12,865,244
[ 1, 270, 333, 6009, 6835, 711, 1375, 15213, 68, 3844, 316, 1147, 20, 20303, 3661, 9816, 13357, 67, 16099, 82, 1245, 1410, 6827, 364, 1375, 75, 3606, 68, 3844, 434, 11663, 2430, 20096, 293, 67, 2163, 711, 13357, 67, 16099, 82, 18, 31734, 1435, 1300, 434, 15105, 401, 293, 67, 2163, 711, 326, 15105, 434, 13357, 67, 16099, 82, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 2071, 669, 10513, 12, 203, 565, 1758, 11663, 67, 16099, 82, 16, 203, 565, 1758, 13357, 67, 16099, 82, 16, 203, 225, 262, 2713, 1135, 261, 6430, 13, 288, 203, 565, 2254, 293, 67, 2163, 273, 6205, 63, 267, 3653, 67, 16099, 82, 6362, 659, 3653, 67, 16099, 82, 15533, 203, 565, 309, 261, 84, 67, 2163, 422, 374, 13, 288, 203, 1377, 3626, 10230, 5147, 5072, 12, 267, 3653, 67, 16099, 82, 16, 11663, 67, 16099, 82, 1769, 203, 1377, 327, 629, 31, 203, 565, 289, 203, 565, 2254, 14805, 273, 3739, 67, 12, 203, 1377, 1728, 636, 12, 45, 654, 39, 3462, 12, 659, 3653, 67, 16099, 82, 2934, 31734, 10756, 203, 565, 2254, 10067, 548, 273, 28641, 63, 659, 3653, 67, 16099, 82, 6362, 267, 3653, 67, 16099, 82, 15533, 203, 565, 309, 261, 23322, 548, 422, 374, 13, 288, 203, 1377, 775, 203, 3639, 490, 25269, 18, 2704, 10513, 12, 659, 3653, 67, 16099, 82, 16, 13357, 67, 16099, 82, 16, 14805, 16, 14758, 16, 531, 9981, 67, 43, 3033, 20373, 16, 374, 16, 374, 13, 203, 1377, 1135, 261, 11890, 612, 13, 288, 203, 3639, 309, 261, 350, 405, 374, 13, 288, 203, 1850, 28641, 63, 659, 3653, 67, 16099, 82, 6362, 267, 3653, 67, 16099, 82, 65, 273, 612, 31, 203, 1850, 327, 638, 31, 203, 1850, 327, 629, 31, 203, 3639, 289, 203, 3639, 327, 629, 31, 203, 1377, 289, 203, 1377, 775, 203, 3639, 490, 25269, 18, 2725, 10513, 12, 203, 1850, 11663, 67, 2 ]
./partial_match/1313161554/0x964630b8327A6EB8730e3addcB8563d1e61b0100/sources/Comptroller.sol
* @title Exponential module for storing fixed-precision decimals @author Compound @dev Legacy contract for compatibility reasons with existing contracts that still use MathError @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: `Exp({mantissa: 5100000000000000000})`./
contract Exponential is CarefulMath, ExponentialNoError { function getExp(uint num, uint denom) internal pure returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { } } function getExp(uint num, uint denom) internal pure returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { } } return (err0, Exp({mantissa: 0})); function getExp(uint num, uint denom) internal pure returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { } } return (err1, Exp({mantissa: 0})); return (MathError.NO_ERROR, Exp({mantissa: rational})); function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); } return (error, Exp({mantissa: result})); function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); } return (error, Exp({mantissa: result})); function mulScalar(Exp memory a, uint scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { } } function mulScalar(Exp memory a, uint scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { } } return (err0, Exp({mantissa: 0})); return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); function mulScalarTruncate(Exp memory a, uint scalar) internal pure returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } function mulScalarTruncate(Exp memory a, uint scalar) internal pure returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) internal pure returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) internal pure returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } function divScalar(Exp memory a, uint scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { } } function divScalar(Exp memory a, uint scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { } } return (err0, Exp({mantissa: 0})); return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); function divScalarByExp(uint scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) { We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { } return getExp(numerator, divisor.mantissa); } function divScalarByExp(uint scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) { We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { } return getExp(numerator, divisor.mantissa); } return (err0, Exp({mantissa: 0})); function divScalarByExpTruncate(uint scalar, Exp memory divisor) internal pure returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } function divScalarByExpTruncate(uint scalar, Exp memory divisor) internal pure returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { } if (err1 != MathError.NO_ERROR) { } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); } function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { } if (err1 != MathError.NO_ERROR) { } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); } return (err0, Exp({mantissa: 0})); (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { } if (err1 != MathError.NO_ERROR) { } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); } return (err1, Exp({mantissa: 0})); assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); function mulExp(uint a, uint b) internal pure returns (MathError, Exp memory) { } return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); function mulExp3(Exp memory a, Exp memory b, Exp memory c) internal pure returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } function mulExp3(Exp memory a, Exp memory b, Exp memory c) internal pure returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } }
16,918,980
[ 1, 17972, 649, 1605, 364, 15729, 5499, 17, 14548, 15105, 225, 21327, 225, 22781, 6835, 364, 8926, 14000, 598, 2062, 20092, 716, 4859, 999, 2361, 668, 225, 7784, 353, 279, 1958, 1492, 9064, 15105, 598, 279, 5499, 6039, 434, 6549, 6970, 12576, 18, 540, 22073, 16, 309, 732, 15504, 358, 1707, 326, 1381, 18, 21, 16, 31340, 4102, 1707, 1381, 18, 21, 73, 2643, 18, 12466, 353, 30, 540, 1375, 2966, 12590, 81, 970, 21269, 30, 21119, 12648, 2787, 11706, 6792, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 29770, 649, 353, 385, 834, 2706, 10477, 16, 29770, 649, 2279, 668, 288, 203, 203, 203, 565, 445, 336, 2966, 12, 11890, 818, 16, 2254, 10716, 13, 2713, 16618, 1135, 261, 10477, 668, 16, 7784, 3778, 13, 288, 203, 3639, 261, 10477, 668, 393, 20, 16, 2254, 12304, 2578, 7385, 13, 273, 14064, 14342, 12, 2107, 16, 1329, 5587, 1769, 203, 3639, 309, 261, 370, 20, 480, 2361, 668, 18, 3417, 67, 3589, 13, 288, 203, 3639, 289, 203, 203, 3639, 261, 10477, 668, 393, 21, 16, 2254, 436, 8371, 13, 273, 3739, 14342, 12, 20665, 2578, 7385, 16, 10716, 1769, 203, 3639, 309, 261, 370, 21, 480, 2361, 668, 18, 3417, 67, 3589, 13, 288, 203, 3639, 289, 203, 203, 565, 289, 203, 203, 565, 445, 336, 2966, 12, 11890, 818, 16, 2254, 10716, 13, 2713, 16618, 1135, 261, 10477, 668, 16, 7784, 3778, 13, 288, 203, 3639, 261, 10477, 668, 393, 20, 16, 2254, 12304, 2578, 7385, 13, 273, 14064, 14342, 12, 2107, 16, 1329, 5587, 1769, 203, 3639, 309, 261, 370, 20, 480, 2361, 668, 18, 3417, 67, 3589, 13, 288, 203, 3639, 289, 203, 203, 3639, 261, 10477, 668, 393, 21, 16, 2254, 436, 8371, 13, 273, 3739, 14342, 12, 20665, 2578, 7385, 16, 10716, 1769, 203, 3639, 309, 261, 370, 21, 480, 2361, 668, 18, 3417, 67, 3589, 13, 288, 203, 3639, 289, 203, 203, 565, 289, 203, 203, 5411, 327, 261, 370, 20, 16, 7784, 12590, 81, 970, 21269, 30, 374, 6792, 1769, 203, 565, 445, 336, 2 ]
pragma solidity ^0.5.0; // Copyright 2019 OpenST Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import "./EIP20Token.sol"; import "./Organized.sol"; import "./SafeMath.sol"; /** * @title Branded Token. * * @notice Branded tokens are minted by staking specified value tokens. */ contract BrandedToken is Organized, EIP20Token { /* Usings */ using SafeMath for uint256; /* Events */ event StakeRequested( bytes32 indexed _stakeRequestHash, address _staker, uint256 _stake, uint256 _nonce ); event StakeRequestAccepted( bytes32 indexed _stakeRequestHash, address _staker, uint256 _stake ); event StakeRequestRevoked( bytes32 indexed _stakeRequestHash, address _staker, uint256 _stake ); event Redeemed( address _redeemer, uint256 _valueTokens ); event StakeRequestRejected( bytes32 indexed _stakeRequestHash, address _staker, uint256 _stake ); event SymbolSet(string _symbol); event NameSet(string _name); /* Structs */ struct StakeRequest { address staker; uint256 stake; uint256 nonce; } /* Storage */ /** Address for value tokens staked to mint branded tokens. */ EIP20Interface public valueToken; /** Conversion rate from value tokens to branded tokens. */ uint256 public conversionRate; /** Number of digits to the right of the decimal point in conversionRate. */ uint8 public conversionRateDecimals; /** Global nonce for stake requests. */ uint256 public nonce; /** Flag indicating whether restrictions have been lifted for all actors. */ bool public allRestrictionsLifted; /** Domain separator encoding per EIP 712. */ bytes32 private constant EIP712_DOMAIN_TYPEHASH = keccak256( "EIP712Domain(address verifyingContract)" ); /** StakeRequest struct type encoding per EIP 712. */ bytes32 private constant BT_STAKE_REQUEST_TYPEHASH = keccak256( "StakeRequest(address staker,uint256 stake,uint256 nonce)" ); /** Domain separator per EIP 712. */ bytes32 private DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, address(this) ) ); /** Maps staker to stakeRequestHashes. */ mapping(address => bytes32) public stakeRequestHashes; /** Maps stakeRequestHash to StakeRequests. */ mapping(bytes32 => StakeRequest) public stakeRequests; /** Maps actor to restriction status. */ mapping(address => bool) private unrestricted; /* Modifiers */ modifier onlyUnrestricted { require( allRestrictionsLifted || unrestricted[msg.sender], "Msg.sender is restricted." ); _; } /* Constructor */ /** * @dev Conversion parameters provide the conversion rate and its scale. * For example, if 1 value token is equivalent to 3.5 branded * tokens (1:3.5), _conversionRate == 35 and * _conversionRateDecimals == 1. * * Constructor requires: * - valueToken address is not zero * - conversionRate is not zero * - conversionRateDecimals is not greater than 5 * * @param _valueToken The value to which valueToken is set. * @param _symbol The value to which tokenSymbol, defined in EIP20Token, * is set. * @param _name The value to which tokenName, defined in EIP20Token, * is set. * @param _decimals The value to which tokenDecimals, defined in EIP20Token, * is set. * @param _conversionRate The value to which conversionRate is set. * @param _conversionRateDecimals The value to which * conversionRateDecimals is set. * @param _organization The value to which organization, defined in Organized, * is set. */ constructor( EIP20Interface _valueToken, string memory _symbol, string memory _name, uint8 _decimals, uint256 _conversionRate, uint8 _conversionRateDecimals, OrganizationInterface _organization ) EIP20Token(_symbol, _name, _decimals) Organized(_organization) public { require( address(_valueToken) != address(0), "ValueToken is zero." ); require( _conversionRate != 0, "ConversionRate is zero." ); require( _conversionRateDecimals <= 5, "ConversionRateDecimals is greater than 5." ); valueToken = _valueToken; conversionRate = _conversionRate; conversionRateDecimals = _conversionRateDecimals; } /* External Functions */ /** * @notice Transfers value tokens from msg.sender to itself, * stores the amount of branded tokens to mint if request * is accepted, and emits stake request information. * * @dev It is expected that this contract will have a sufficientallowance * to transfer value tokens from the staker at the time this function * is executed. * * Function requires: * - _mint is equivalent to _stake * - msg.sender does not have a stake request hash * - valueToken.transferFrom returns true * * @param _stake Amount of value tokens to stake. * @param _mint Amount of branded tokens to mint. * * @return stakeRequestHash_ Hash of stake request information calculated per * EIP 712. */ function requestStake( uint256 _stake, uint256 _mint ) external returns (bytes32 stakeRequestHash_) { require( _mint == convertToBrandedTokens(_stake), "Mint is not equivalent to stake." ); require( stakeRequestHashes[msg.sender] == "", "Staker has a stake request hash." ); StakeRequest memory stakeRequest = StakeRequest({ staker: msg.sender, stake: _stake, nonce: nonce }); // Calculates hash per EIP 712 stakeRequestHash_ = hash(stakeRequest); stakeRequestHashes[msg.sender] = stakeRequestHash_; stakeRequests[stakeRequestHash_] = stakeRequest; nonce += 1; emit StakeRequested( stakeRequestHash_, stakeRequest.staker, stakeRequest.stake, stakeRequest.nonce ); require( valueToken.transferFrom(msg.sender, address(this), _stake), "ValueToken.transferFrom returned false." ); } /** * @notice Mints and transfers branded tokens to a staker, * increases the total token supply, and * emits stake request acceptance and transfer information. * * @dev The function has no access controls, but will only accept * the signature of a worker, as defined in Organization. * * Function requires: * - stake request exists * - signature is from a worker * * @param _stakeRequestHash Stake request hash. * @param _r R of the signature. * @param _s S of the signature. * @param _v V of the signature. * * @return success_ True. */ function acceptStakeRequest( bytes32 _stakeRequestHash, bytes32 _r, bytes32 _s, uint8 _v ) external returns (bool success_) { require( stakeRequests[_stakeRequestHash].staker != address(0), "Stake request not found." ); StakeRequest storage stakeRequest = stakeRequests[_stakeRequestHash]; require( verifySigner(stakeRequest, _r, _s, _v), "Signer is not a worker." ); emit StakeRequestAccepted( _stakeRequestHash, stakeRequest.staker, stakeRequest.stake ); uint256 mint = convertToBrandedTokens(stakeRequest.stake); balances[stakeRequest.staker] = balances[stakeRequest.staker] .add(mint); totalTokenSupply = totalTokenSupply.add(mint); // Mint branded tokens emit Transfer(address(0), stakeRequest.staker, mint); delete stakeRequestHashes[stakeRequest.staker]; delete stakeRequests[_stakeRequestHash]; return true; } /** * @notice Maps addresses in _restrictionLifted to true in unrestricted. * * @dev Function requires: * - msg.sender is a worker * * @param _restrictionLifted Addresses for which to lift restrictions. * * @return success_ True. */ function liftRestriction( address[] calldata _restrictionLifted ) external onlyWorker returns (bool success_) { for (uint256 i = 0; i < _restrictionLifted.length; i++) { unrestricted[_restrictionLifted[i]] = true; } return true; } /** * @notice Indicates whether an actor is unrestricted. * * @param _actor Actor. * * @return isUnrestricted_ Whether unrestricted. */ function isUnrestricted(address _actor) external view returns (bool isUnrestricted_) { return unrestricted[_actor]; } /** * @notice Lifts restrictions from all actors. * * @dev Function requires: * - msg.sender is organization * * @return success_ True. */ function liftAllRestrictions() external onlyOrganization returns (bool success_) { allRestrictionsLifted = true; return true; } /** * @notice Revokes stake request by deleting its information and * transferring staked value tokens back to staker. * * @dev Function requires: * - msg.sender is staker * - valueToken.transfer returns true * * @param _stakeRequestHash Stake request hash. * * @return success_ True. */ function revokeStakeRequest( bytes32 _stakeRequestHash ) external returns (bool success_) { require( stakeRequests[_stakeRequestHash].staker == msg.sender, "Msg.sender is not staker." ); uint256 stake = stakeRequests[_stakeRequestHash].stake; delete stakeRequestHashes[msg.sender]; delete stakeRequests[_stakeRequestHash]; emit StakeRequestRevoked( _stakeRequestHash, msg.sender, stake ); require( valueToken.transfer(msg.sender, stake), "ValueToken.transfer returned false." ); return true; } /** * @notice Reduces msg.sender's balance and the total supply by * _brandedTokens and transfers an equivalent amount of * value tokens to msg.sender. * * @dev Redemption may risk loss of branded tokens. * It is possible to redeem branded tokens for 0 value tokens. * * Function requires: * - valueToken.transfer returns true * * @param _brandedTokens Amount of branded tokens to redeem. * * @return success_ True. */ function redeem( uint256 _brandedTokens ) external returns (bool success_) { balances[msg.sender] = balances[msg.sender].sub(_brandedTokens); totalTokenSupply = totalTokenSupply.sub(_brandedTokens); uint256 valueTokens = convertToValueTokens(_brandedTokens); emit Redeemed(msg.sender, valueTokens); // Burn redeemed branded tokens emit Transfer(msg.sender, address(0), _brandedTokens); require( valueToken.transfer(msg.sender, valueTokens), "ValueToken.transfer returned false." ); return true; } /** * @notice Rejects stake request by deleting its information and * transferring staked value tokens back to staker. * * @dev Function requires: * - msg.sender is a worker * - stake request exists * - valueToken.transfer returns true * * @param _stakeRequestHash Stake request hash. * * @return success_ True. */ function rejectStakeRequest( bytes32 _stakeRequestHash ) external onlyWorker returns (bool success_) { require( stakeRequests[_stakeRequestHash].staker != address(0), "Stake request not found." ); StakeRequest memory stakeRequest = stakeRequests[_stakeRequestHash]; delete stakeRequestHashes[stakeRequest.staker]; delete stakeRequests[_stakeRequestHash]; emit StakeRequestRejected( _stakeRequestHash, stakeRequest.staker, stakeRequest.stake ); require( valueToken.transfer(stakeRequest.staker, stakeRequest.stake), "ValueToken.transfer returned false." ); return true; } /** * @notice Sets symbol. * * @dev Function requires: * - msg.sender is a worker * * @param _symbol The value to which symbol is set. * * @return success_ True. */ function setSymbol( string calldata _symbol ) external onlyWorker returns (bool success_) { tokenSymbol = _symbol; emit SymbolSet(tokenSymbol); return true; } /** * @notice Sets name. * * @dev Function requires: * - msg.sender is a worker * * @param _name The value to which name is set. * * @return success_ True. */ function setName( string calldata _name ) external onlyWorker returns (bool success_) { tokenName = _name; emit NameSet(tokenName); return true; } /* Public Functions */ /** * @notice Overrides EIP20Token.transfer by additionally * requiring msg.sender to be unrestricted. * * @param _to Address to which tokens are transferred. * @param _value Amount of tokens to be transferred. * * @return success_ Result from EIP20Token transfer. */ function transfer( address _to, uint256 _value ) public onlyUnrestricted returns (bool success_) { return super.transfer(_to, _value); } /** * @notice Overrides EIP20Token.transferFrom by additionally * requiring msg.sender to be unrestricted. * * @param _from Address from which tokens are transferred. * @param _to Address to which tokens are transferred. * @param _value Amount of tokens transferred. * * @return success_ Result from EIP20Token transferFrom. */ function transferFrom( address _from, address _to, uint256 _value ) public onlyUnrestricted returns (bool success_) { return super.transferFrom(_from, _to, _value); } /** * @notice Returns the amount of branded tokens equivalent to a * given amount of value tokens. * * @dev Please note there may be a loss of up to 1 indivisible unit of * this token (i.e., assuming 1 value token is equivalent * to 3.5 branded tokens, convert(1) --> 3, not 3.5). * * @param _valueTokens Amount to convert. * * @return uint256 Converted amount. */ function convertToBrandedTokens( uint256 _valueTokens ) public view returns (uint256) { return ( _valueTokens .mul(conversionRate) .div(10 ** uint256(conversionRateDecimals)) ); } /** * @notice Returns the amount of value tokens equivalent to a * given amount of branded tokens. * * @dev Please note there may be a loss of up to 1 indivisible unit of * this token. * * @param _brandedTokens Amount to convert. * * @return uint256 Converted amount. */ function convertToValueTokens( uint256 _brandedTokens ) public view returns (uint256) { return ( _brandedTokens .mul(10 ** uint256(conversionRateDecimals)) .div(conversionRate) ); } /* Private Functions */ /** * @notice Calculates stakeRequestHash according to EIP 712. * * @param _stakeRequest StakeRequest instance to hash. * * @return bytes32 EIP 712 hash of _stakeRequest. */ function hash( StakeRequest memory _stakeRequest ) private pure returns (bytes32) { return keccak256( abi.encode( BT_STAKE_REQUEST_TYPEHASH, _stakeRequest.staker, _stakeRequest.stake, _stakeRequest.nonce ) ); } /** * @notice Verifies whether signer of stakeRequestHash is a worker. * * @dev Signing the stakeRequestHash consistent with eth_signTypedData, * as specified by EIP 712, requires signing a hash of encoded data * comprising: * - an initial byte * - the version byte for structured data * - the domain separator * - the stakeRequestHash * * See: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md * * @param _stakeRequest Stake request. * @param _r R of the signature. * @param _s S of the signature. * @param _v V of the signature. * * @return bool True if signer is a worker, false if not. */ function verifySigner( StakeRequest storage _stakeRequest, bytes32 _r, bytes32 _s, uint8 _v ) private view returns (bool) { // See: https://github.com/ethereum/EIPs/blob/master/assets/eip-712/Example.sol bytes32 typedData = keccak256( abi.encodePacked( byte(0x19), // the initial 0x19 byte byte(0x01), // the version byte for structured data DOMAIN_SEPARATOR, hash(_stakeRequest) ) ); return organization.isWorker(ecrecover(typedData, _v, _r, _s)); } }
* @notice Sets symbol. @dev Function requires: - msg.sender is a worker @param _symbol The value to which symbol is set. @return success_ True./
function setSymbol( string calldata _symbol ) external onlyWorker returns (bool success_) { tokenSymbol = _symbol; emit SymbolSet(tokenSymbol); return true; }
2,504,326
[ 1, 2785, 3273, 18, 225, 4284, 4991, 30, 1850, 300, 1234, 18, 15330, 353, 279, 4322, 225, 389, 7175, 1021, 460, 358, 1492, 3273, 353, 444, 18, 327, 2216, 67, 1053, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 5335, 12, 203, 3639, 533, 745, 892, 389, 7175, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1338, 6671, 203, 3639, 1135, 261, 6430, 2216, 67, 13, 203, 565, 288, 203, 3639, 1147, 5335, 273, 389, 7175, 31, 203, 203, 3639, 3626, 8565, 694, 12, 2316, 5335, 1769, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x9f60a931c50596632E220384Ad7e90D2e9Eb7031/sources/Dorkland.sol
* @dev Indicates a failure with the token `receiver`. Used in transfers. @param receiver Address to which tokens are being transferred./
constructor() ERC20("Shib20", "SHIB20") Ownable(_msgSender()) { _totalSupply = 10 ** 9 * 10 ** decimals(); _isExcludedFromMaxWallet[owner()] = true; _isExcludedFromMaxWallet[address(this)] = true; _isExcludedFromMaxWallet[address(0)] = true; _mint(owner(), _totalSupply); }
2,940,555
[ 1, 23741, 279, 5166, 598, 326, 1147, 1375, 24454, 8338, 10286, 316, 29375, 18, 225, 5971, 5267, 358, 1492, 2430, 854, 3832, 906, 4193, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 1555, 495, 3462, 3113, 315, 2664, 13450, 3462, 7923, 14223, 6914, 24899, 3576, 12021, 10756, 288, 203, 3639, 389, 4963, 3088, 1283, 273, 1728, 2826, 2468, 380, 1728, 2826, 15105, 5621, 203, 203, 3639, 389, 291, 16461, 1265, 2747, 16936, 63, 8443, 1435, 65, 273, 638, 31, 203, 3639, 389, 291, 16461, 1265, 2747, 16936, 63, 2867, 12, 2211, 25887, 273, 638, 31, 203, 3639, 389, 291, 16461, 1265, 2747, 16936, 63, 2867, 12, 20, 25887, 273, 638, 31, 203, 203, 3639, 389, 81, 474, 12, 8443, 9334, 389, 4963, 3088, 1283, 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 ]
./full_match/5/0x3F8df76F2FF3E427b1A66c67f3291F2C29b3D971/sources/contracts/crowdFundingDapp.sol
this will allow campaigns to be indexed like campaigns[0]
mapping(uint256 => Campaign) public campaigns;
1,928,047
[ 1, 2211, 903, 1699, 8965, 87, 358, 506, 8808, 3007, 8965, 87, 63, 20, 65, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 11890, 5034, 516, 17820, 13, 1071, 8965, 87, 31, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.8 <0.7.0; import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; import "./shared/libraries/Percentages.sol"; import "./shared/modules/GranteeConstructor.sol"; import "./shared/storage/Funding.sol"; import "./shared/storage/BaseGrant.sol"; /** * @title Grant for Eth2. * @dev Managed (n) * Funding Deadline (n) * Contract expiry (n) * With Token (n) * Percentage based allocation (y) * Withdraw (pull payment) (n) * This is a simplified grant which behaves as a simple payment splitter. * No refunds or managers; payment are immediately pushed. * WARNING: vulnerable to sending to Gas Token generating addresses. Trust in grantees not doing so is required. * @author @NoahMarconi */ contract UnmanagedStream is ReentrancyGuard, BaseGrant, GranteeConstructor, Funding { /*---------- Constructor ----------*/ /** * @dev Grant creation function. May be called by grantors, grantees, or any other relevant party. * @param _grantees Sorted recipients of unlocked funds. * @param _amounts Respective allocations for each Grantee (must follow sort order of _grantees). * @param _currency (Optional) If null, amount is in wei, otherwise address of ERC20-compliant contract. * @param _uri URI for additional (off-chain) grant details such as description, milestones, etc. * @param _extraData (Optional) Support for extensions to the Standard. */ constructor( address[] memory _grantees, uint256[] memory _amounts, address _currency, bytes memory _uri, bytes memory _extraData ) GranteeConstructor(_grantees, _amounts, true) public { require( _currency == address(0), "constructor::Invalid Argument. Currency must be ADDRESS_ZERO." ); // Initialize globals. setUri(_uri); } /*---------- Fallback ----------*/ receive() external payable nonReentrant { require( msg.value > 0, "fallback::Invalid Value. msg.value must be greater than 0." ); uint256 numGrantees = this.getGranteeReferenceLength(); address lastGrantee = payable(this.getGranteeReference(numGrantees - 1)); for (uint256 i = 0; i < this.getGranteeReferenceLength(); i++) { address payable currentGrantee = payable(this.getGranteeReference(i)); uint256 eligiblePortion = Percentages.maxAllocation( this.getGranteeTargetFunding(currentGrantee), this.getCumulativeTargetFunding(), msg.value ); if (currentGrantee == lastGrantee) { // Handle rounding of a few wei. // @audit question for auditor, should we enforce this is within expected threshold? eligiblePortion = address(this).balance; } if (eligiblePortion > 0) { (bool success, ) = currentGrantee.call{ value: eligiblePortion}(""); require( success, "fallback::Transfer Error. Unable to send eligiblePortion to Grantee." ); emit LogPayment(currentGrantee, eligiblePortion); } } increaseTotalFundingBy(msg.value); emit LogFunding(msg.sender, msg.value); } }
* @title Grant for Eth2. @dev Managed (n) Funding Deadline (n) Contract expiry (n) With Token (n) Percentage based allocation (y) Withdraw (pull payment) (n) This is a simplified grant which behaves as a simple payment splitter. No refunds or managers; payment are immediately pushed. WARNING: vulnerable to sending to Gas Token generating addresses. Trust in grantees not doing so is required. @author @NoahMarconi/
contract UnmanagedStream is ReentrancyGuard, BaseGrant, GranteeConstructor, Funding { constructor( address[] memory _grantees, uint256[] memory _amounts, address _currency, bytes memory _uri, bytes memory _extraData ) GranteeConstructor(_grantees, _amounts, true) public pragma solidity >=0.6.8 <0.7.0; { require( _currency == address(0), "constructor::Invalid Argument. Currency must be ADDRESS_ZERO." ); setUri(_uri); } receive() external payable nonReentrant { require( msg.value > 0, "fallback::Invalid Value. msg.value must be greater than 0." ); uint256 numGrantees = this.getGranteeReferenceLength(); address lastGrantee = payable(this.getGranteeReference(numGrantees - 1)); for (uint256 i = 0; i < this.getGranteeReferenceLength(); i++) { address payable currentGrantee = payable(this.getGranteeReference(i)); uint256 eligiblePortion = Percentages.maxAllocation( this.getGranteeTargetFunding(currentGrantee), this.getCumulativeTargetFunding(), msg.value ); if (currentGrantee == lastGrantee) { eligiblePortion = address(this).balance; } if (eligiblePortion > 0) { require( success, "fallback::Transfer Error. Unable to send eligiblePortion to Grantee." ); emit LogPayment(currentGrantee, eligiblePortion); } } increaseTotalFundingBy(msg.value); emit LogFunding(msg.sender, msg.value); } { require( msg.value > 0, "fallback::Invalid Value. msg.value must be greater than 0." ); uint256 numGrantees = this.getGranteeReferenceLength(); address lastGrantee = payable(this.getGranteeReference(numGrantees - 1)); for (uint256 i = 0; i < this.getGranteeReferenceLength(); i++) { address payable currentGrantee = payable(this.getGranteeReference(i)); uint256 eligiblePortion = Percentages.maxAllocation( this.getGranteeTargetFunding(currentGrantee), this.getCumulativeTargetFunding(), msg.value ); if (currentGrantee == lastGrantee) { eligiblePortion = address(this).balance; } if (eligiblePortion > 0) { require( success, "fallback::Transfer Error. Unable to send eligiblePortion to Grantee." ); emit LogPayment(currentGrantee, eligiblePortion); } } increaseTotalFundingBy(msg.value); emit LogFunding(msg.sender, msg.value); } { require( msg.value > 0, "fallback::Invalid Value. msg.value must be greater than 0." ); uint256 numGrantees = this.getGranteeReferenceLength(); address lastGrantee = payable(this.getGranteeReference(numGrantees - 1)); for (uint256 i = 0; i < this.getGranteeReferenceLength(); i++) { address payable currentGrantee = payable(this.getGranteeReference(i)); uint256 eligiblePortion = Percentages.maxAllocation( this.getGranteeTargetFunding(currentGrantee), this.getCumulativeTargetFunding(), msg.value ); if (currentGrantee == lastGrantee) { eligiblePortion = address(this).balance; } if (eligiblePortion > 0) { require( success, "fallback::Transfer Error. Unable to send eligiblePortion to Grantee." ); emit LogPayment(currentGrantee, eligiblePortion); } } increaseTotalFundingBy(msg.value); emit LogFunding(msg.sender, msg.value); } { require( msg.value > 0, "fallback::Invalid Value. msg.value must be greater than 0." ); uint256 numGrantees = this.getGranteeReferenceLength(); address lastGrantee = payable(this.getGranteeReference(numGrantees - 1)); for (uint256 i = 0; i < this.getGranteeReferenceLength(); i++) { address payable currentGrantee = payable(this.getGranteeReference(i)); uint256 eligiblePortion = Percentages.maxAllocation( this.getGranteeTargetFunding(currentGrantee), this.getCumulativeTargetFunding(), msg.value ); if (currentGrantee == lastGrantee) { eligiblePortion = address(this).balance; } if (eligiblePortion > 0) { require( success, "fallback::Transfer Error. Unable to send eligiblePortion to Grantee." ); emit LogPayment(currentGrantee, eligiblePortion); } } increaseTotalFundingBy(msg.value); emit LogFunding(msg.sender, msg.value); } (bool success, ) = currentGrantee.call{ value: eligiblePortion}(""); }
12,825,489
[ 1, 9021, 364, 512, 451, 22, 18, 225, 10024, 5397, 261, 82, 13, 1377, 478, 14351, 23967, 1369, 5411, 261, 82, 13, 1377, 13456, 10839, 2398, 261, 82, 13, 1377, 3423, 3155, 5375, 261, 82, 13, 1377, 21198, 410, 2511, 13481, 261, 93, 13, 1377, 3423, 9446, 261, 13469, 5184, 13, 377, 261, 82, 13, 1377, 1220, 353, 279, 20482, 7936, 1492, 12433, 6606, 487, 279, 4143, 5184, 21553, 18, 1377, 2631, 16255, 87, 578, 21103, 31, 5184, 854, 7636, 18543, 18, 1377, 9744, 30, 331, 19063, 429, 358, 5431, 358, 31849, 3155, 12516, 6138, 18, 20246, 316, 15889, 736, 281, 486, 9957, 1427, 353, 1931, 18, 225, 632, 2279, 9795, 49, 297, 591, 77, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 1351, 19360, 1228, 353, 868, 8230, 12514, 16709, 16, 3360, 9021, 16, 611, 2450, 22579, 6293, 16, 478, 14351, 288, 203, 203, 203, 203, 565, 3885, 12, 203, 3639, 1758, 8526, 3778, 389, 75, 2450, 736, 281, 16, 203, 3639, 2254, 5034, 8526, 3778, 389, 8949, 87, 16, 203, 3639, 1758, 389, 7095, 16, 203, 3639, 1731, 3778, 389, 1650, 16, 203, 3639, 1731, 3778, 389, 7763, 751, 203, 565, 262, 203, 3639, 611, 2450, 22579, 6293, 24899, 75, 2450, 736, 281, 16, 389, 8949, 87, 16, 638, 13, 203, 3639, 1071, 203, 683, 9454, 18035, 560, 1545, 20, 18, 26, 18, 28, 411, 20, 18, 27, 18, 20, 31, 203, 565, 288, 203, 203, 3639, 2583, 12, 203, 5411, 389, 7095, 422, 1758, 12, 20, 3631, 203, 5411, 315, 12316, 2866, 1941, 5067, 18, 13078, 1297, 506, 11689, 10203, 67, 24968, 1199, 203, 3639, 11272, 203, 203, 3639, 30473, 24899, 1650, 1769, 203, 203, 565, 289, 203, 203, 203, 565, 6798, 1435, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 1661, 426, 8230, 970, 203, 203, 565, 288, 203, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 1132, 405, 374, 16, 203, 5411, 315, 16471, 2866, 1941, 1445, 18, 1234, 18, 1132, 1297, 506, 6802, 2353, 374, 1199, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 818, 43, 2450, 736, 281, 273, 333, 18, 588, 43, 2450, 22579, 2404, 1782, 5621, 203, 3639, 1758, 1142, 43, 2450, 22579, 273, 8843, 429, 12, 2211, 18, 588, 43, 2450, 22579, 2404, 12, 2107, 2 ]
./full_match/80001/0x8c9F2c3B36939583Ecd3511aC8826aE258eD6f8E/sources/contracts/smart-wallet/utils/Helpers.sol
* keccak function over calldata. @dev copy calldata into memory, do keccak and drop allocated memory. Strangely, this is more efficient than letting solidity do it./
function calldataKeccak(bytes calldata data) pure returns (bytes32 ret) { function _packValidationData( bool sigFailed, uint48 validUntil, uint48 validAfter } assembly { let mem := mload(0x40) let len := data.length calldatacopy(mem, data.offset, len) ret := keccak256(mem, len) } }
5,560,852
[ 1, 79, 24410, 581, 445, 1879, 745, 892, 18, 225, 1610, 745, 892, 1368, 3778, 16, 741, 417, 24410, 581, 471, 3640, 11977, 3778, 18, 3978, 539, 2357, 16, 333, 353, 1898, 14382, 2353, 2231, 1787, 18035, 560, 741, 518, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 915, 745, 892, 47, 24410, 581, 12, 3890, 745, 892, 501, 13, 16618, 1135, 261, 3890, 1578, 325, 13, 288, 203, 915, 389, 2920, 4354, 751, 12, 203, 565, 1426, 3553, 2925, 16, 203, 565, 2254, 8875, 923, 9716, 16, 203, 565, 2254, 8875, 923, 4436, 203, 97, 203, 203, 565, 19931, 288, 203, 3639, 2231, 1663, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 3639, 2231, 562, 519, 501, 18, 2469, 203, 3639, 745, 892, 3530, 12, 3917, 16, 501, 18, 3348, 16, 562, 13, 203, 3639, 325, 519, 417, 24410, 581, 5034, 12, 3917, 16, 562, 13, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// This is a social media smart contract that allows people to publish strings of text in short formats with a focus on hashtags so that they can follow, read and be in touch with the latest content regarding those hashtags. There will be a mapping os top hashtags. A struct for each piece of content with the date, author, content and array of hashtags. We want to avoid focusing on specific users that's why user accounts will be anonymous where addresses will the be the only identifiers. pragma solidity ^0.5.0; contract SocialMedia { struct Content { uint256 id; address author; uint256 date; string content; bytes32[] hashtags; } event ContentAdded(uint256 indexed id, address indexed author, uint256 indexed date, string content, bytes32[] hashtags); mapping(address => bytes32[]) public subscribedHashtags; mapping(bytes32 => uint256) public hashtagScore; // The number of times this hashtag has been used, used to sort the top hashtags mapping(bytes32 => Content[]) public contentByHashtag; mapping(uint256 => Content) public contentById; mapping(bytes32 => bool) public doesHashtagExist; mapping(address => bool) public doesUserExist; address[] public users; Content[] public contents; bytes32[] public hashtags; uint256 public latestContentId; /// @notice To add new content to the social media dApp. If no hashtags are sent, the content is added to the #general hashtag list. /// @param _content The string of content /// @param _hashtags The hashtags used for that piece of content function addContent(string memory _content, bytes32[] memory _hashtags) public { require(bytes(_content).length > 0, 'The content cannot be empty'); Content memory newContent = Content(latestContentId, msg.sender, now, _content, _hashtags); // If the user didn't specify any hashtags add the content to the #general hashtag if(_hashtags.length == 0) { contentByHashtag['general'].push(newContent); hashtagScore['general']++; if(!doesHashtagExist['general']) { hashtags.push('general'); doesHashtagExist['general'] = true; } newContent.hashtags[0] = 'general'; } else { for(uint256 i = 0; i < _hashtags.length; i++) { contentByHashtag[_hashtags[i]].push(newContent); hashtagScore[_hashtags[i]]++; if(!doesHashtagExist[_hashtags[i]]) { hashtags.push(_hashtags[i]); doesHashtagExist[_hashtags[i]] = true; } } } hashtags = sortHashtagsByScore(); contentById[latestContentId] = newContent; contents.push(newContent); if(!doesUserExist[msg.sender]) { users.push(msg.sender); doesUserExist[msg.sender] = true; } emit ContentAdded(latestContentId, msg.sender, now, _content, _hashtags); latestContentId++; } /// @notice To subscribe to a hashtag if you didn't do so already /// @param _hashtag The hashtag name function subscribeToHashtag(bytes32 _hashtag) public { if(!checkExistingSubscription(_hashtag)) { subscribedHashtags[msg.sender].push(_hashtag); hashtagScore[_hashtag]++; hashtags = sortHashtagsByScore(); } } /// @notice To unsubscribe to a hashtag if you are subscribed otherwise it won't do nothing /// @param _hashtag The hashtag name function unsubscribeToHashtag(bytes32 _hashtag) public { if(checkExistingSubscription(_hashtag)) { for(uint256 i = 0; i < subscribedHashtags[msg.sender].length; i++) { if(subscribedHashtags[msg.sender][i] == _hashtag) { bytes32 lastElement = subscribedHashtags[msg.sender][subscribedHashtags[msg.sender].length - 1]; subscribedHashtags[msg.sender][i] = lastElement; subscribedHashtags[msg.sender].length--; // Reduce the array to remove empty elements hashtagScore[_hashtag]--; hashtags = sortHashtagsByScore(); break; } } } } /// @notice To get the top hashtags /// @param _amount How many top hashtags to get in order, for instance the top 20 hashtags /// @return bytes32[] Returns the names of the hashtags function getTopHashtags(uint256 _amount) public view returns(bytes32[] memory) { bytes32[] memory result; if(hashtags.length < _amount) { result = new bytes32[](hashtags.length); for(uint256 i = 0; i < hashtags.length; i++) { result[i] = hashtags[i]; } } else { result = new bytes32[](_amount); for(uint256 i = 0; i < _amount; i++) { result[i] = hashtags[i]; } } return result; } /// @notice To get the followed hashtag names for this msg.sender /// @return bytes32[] The hashtags followed by this user function getFollowedHashtags() public view returns(bytes32[] memory) { return subscribedHashtags[msg.sender]; } /// @notice To get the contents for a particular hashtag. It returns the ids because we can't return arrays of strings and we can't return structs so the user has to manually make a new request for each piece of content using the function below. /// @param _hashtag The hashtag from which get content /// @param _amount The quantity of contents to get for instance, 50 pieces of content for that hashtag /// @return uint256[] Returns the ids of the contents so that you can get each piece independently with a new request since you can't return arrays of strings function getContentIdsByHashtag(bytes32 _hashtag, uint256 _amount) public view returns(uint256[] memory) { uint256[] memory ids = new uint256[](_amount); for(uint256 i = 0; i < _amount; i++) { ids[i] = contentByHashtag[_hashtag][i].id; } return ids; } /// @notice Returns the data for a particular content id /// @param _id The id of the content /// @return Returns the id, author, date, content and hashtags for that piece of content function getContentById(uint256 _id) public view returns(uint256, address, uint256, string memory, bytes32[] memory) { Content memory c = contentById[_id]; return (c.id, c.author, c.date, c.content, c.hashtags); } /// @notice Sorts the hashtags given their hashtag score /// @return bytes32[] Returns the sorted array of hashtags function sortHashtagsByScore() public view returns(bytes32[] memory) { bytes32[] memory _hashtags = hashtags; bytes32[] memory sortedHashtags = new bytes32[](hashtags.length); uint256 lastId = 0; for(uint256 i = 0; i < _hashtags.length; i++) { for(uint j = i+1; j < _hashtags.length; j++) { // If it's a buy order, sort from lowest to highest since we want the lowest prices first if(hashtagScore[_hashtags[i]] < hashtagScore[_hashtags[j]]) { bytes32 temporaryhashtag = _hashtags[i]; _hashtags[i] = _hashtags[j]; _hashtags[j] = temporaryhashtag; } } sortedHashtags[lastId] = _hashtags[i]; lastId++; } return sortedHashtags; } /// @notice To check if the use is already subscribed to a hashtag /// @return bool If you are subscribed to that hashtag or not function checkExistingSubscription(bytes32 _hashtag) public view returns(bool) { for(uint256 i = 0; i < subscribedHashtags[msg.sender].length; i++) { if(subscribedHashtags[msg.sender][i] == _hashtag) return true; } return false; } }
@notice To get the contents for a particular hashtag. It returns the ids because we can't return arrays of strings and we can't return structs so the user has to manually make a new request for each piece of content using the function below. @param _hashtag The hashtag from which get content @param _amount The quantity of contents to get for instance, 50 pieces of content for that hashtag @return uint256[] Returns the ids of the contents so that you can get each piece independently with a new request since you can't return arrays of strings
function getContentIdsByHashtag(bytes32 _hashtag, uint256 _amount) public view returns(uint256[] memory) { uint256[] memory ids = new uint256[](_amount); for(uint256 i = 0; i < _amount; i++) { ids[i] = contentByHashtag[_hashtag][i].id; } return ids; }
1,797,527
[ 1, 774, 336, 326, 2939, 364, 279, 6826, 711, 647, 346, 18, 2597, 1135, 326, 3258, 2724, 732, 848, 1404, 327, 5352, 434, 2064, 471, 732, 848, 1404, 327, 8179, 1427, 326, 729, 711, 358, 10036, 1221, 279, 394, 590, 364, 1517, 11151, 434, 913, 1450, 326, 445, 5712, 18, 225, 389, 5332, 647, 346, 1021, 711, 647, 346, 628, 1492, 336, 913, 225, 389, 8949, 1021, 10457, 434, 2939, 358, 336, 364, 791, 16, 6437, 10167, 434, 913, 364, 716, 711, 647, 346, 327, 2254, 5034, 8526, 2860, 326, 3258, 434, 326, 2939, 1427, 716, 1846, 848, 336, 1517, 11151, 14807, 715, 598, 279, 394, 590, 3241, 1846, 848, 1404, 327, 5352, 434, 2064, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5154, 2673, 858, 5582, 647, 346, 12, 3890, 1578, 389, 5332, 647, 346, 16, 2254, 5034, 389, 8949, 13, 1071, 1476, 1135, 12, 11890, 5034, 8526, 3778, 13, 288, 203, 3639, 2254, 5034, 8526, 3778, 3258, 273, 394, 2254, 5034, 8526, 24899, 8949, 1769, 203, 3639, 364, 12, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 8949, 31, 277, 27245, 288, 203, 5411, 3258, 63, 77, 65, 273, 913, 858, 5582, 647, 346, 63, 67, 5332, 647, 346, 6362, 77, 8009, 350, 31, 203, 3639, 289, 203, 3639, 327, 3258, 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 ]
pragma solidity ^0.6.3; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract SecureAuction is ERC721 { using SafeMath for uint256; /**** STATE VARIABLES ***** */ //static and constant state variables mapping(uint256 => AuctionItem) private _auctionItems; address public owner; //dynamic and changing state variables uint256 public _tokenIds; uint256 public _auctionItemIds; mapping(uint256=>mapping(address => uint256)) public fundsByBidder; mapping(int256=>uint256) token; mapping(uint256=>bidding) public bid; bool firsttime = false; /***** EVENTS ****** */ event LogBid(address indexed bidder, uint indexed auctionItemId, uint bid, address indexed highestBidder, uint highestBid, uint highestBindingBid); event LogWithdrawal(uint indexed auctionItemId, address indexed withdrawer, address indexed withdrawalAccount, uint amount); event LogCanceled(uint256 indexed auctionItemId,address indexed seller,address indexed winner); event LogAddItem(uint256 _auctionItemIds, string name, address payable indexed seller, uint256 price, uint nowTime, uint timePeriod); /***** STRUCTS ****** */ struct AuctionItem { address payable seller; uint256 minbid; string tokenURI; bool exists; uint bidIncrement; uint time; uint timePeriod; bool cancelled; bool auctionstarted; string name; } struct bidding{ uint highestBindingBid; address payable highestBidder; } /**** CONSTRUCTOR ***** */ constructor() public ERC721("DART", "ART"){ owner=msg.sender; } /**** MODIFIERS ***** */ // check if item exists modifier auctionItemExist(uint256 id) { require(_auctionItems[id].exists, "Not Found"); _; } // ensure caller is auction item owner modifier onlyNotOwner(uint256 id) { AuctionItem memory auctionItem = _auctionItems[id]; if (msg.sender == auctionItem.seller) revert(); _; } modifier onlyOwner(uint256 id) { AuctionItem memory auctionItem = _auctionItems[id]; if (msg.sender != auctionItem.seller) revert(); _; } modifier minbid(uint256 id){ AuctionItem memory auctionItem = _auctionItems[id]; if(msg.value<auctionItem.minbid) revert(); _; } /**** AUCTION ITEM FUNCTIONS ***** */ function addAuctionItem(uint256 price, string memory tokenURI, uint _bidincrement, uint timePeriod, string memory name) public { require(price >= 0, "Price cannot be lesss than 0"); _auctionItemIds++; uint nowTime = now; _auctionItems[_auctionItemIds] = AuctionItem(msg.sender, price, tokenURI, true, _bidincrement, nowTime, timePeriod,false,false,name); emit LogAddItem(_auctionItemIds, name, msg.sender, price, nowTime, timePeriod); } //get auction item info function getAuctionItem(uint256 id) public view auctionItemExist(id) returns (uint256, uint256, string memory, uint, uint, uint, bool, string memory, address payable) { AuctionItem memory auctionItem = _auctionItems[id]; bidding memory bid = bid[id]; return (id, auctionItem.minbid, auctionItem.tokenURI, bid.highestBindingBid,auctionItem.time,auctionItem.timePeriod,auctionItem.cancelled,auctionItem.name,auctionItem.seller); } /**** AUCTION FUNCTIONS ***** */ //Cancel auction function cancelAuction(uint256 id) public payable returns (bool success) { AuctionItem storage auctionItem = _auctionItems[id]; require(auctionItem.cancelled == false); if((auctionItem.time + (auctionItem.timePeriod * 1 seconds) < now)){ bidding storage bid = bid[id]; auctionItem.cancelled = true; if (bid.highestBindingBid != 0 && auctionItem.auctionstarted == true){ _tokenIds++; _safeMint(bid.highestBidder, _tokenIds); _setTokenURI(_tokenIds, auctionItem.tokenURI); fundsByBidder[id][bid.highestBidder] -= bid.highestBindingBid; // send the funds (auctionItem.seller).send(bid.highestBindingBid); } LogCanceled(id,auctionItem.seller,bid.highestBidder); } return auctionItem.cancelled; } function generateSHA256Bytes32(uint256 value, bool fake, uint256 secret) public view returns (bytes32) { return sha256(abi.encodePacked(value, fake, secret)); } function placeBid(uint256 id) public payable onlyNotOwner(id) minbid(id) returns (bool success) { // reject payments of 0 ETH if (msg.value == 0) revert(); bidding storage bid = bid[id]; AuctionItem storage auctionItem = _auctionItems[id]; require((auctionItem.time + (auctionItem.timePeriod * 1 seconds) > now)); require(auctionItem.cancelled == false); uint newBid = fundsByBidder[id][msg.sender] + msg.value; if (newBid <= bid.highestBindingBid) revert(); uint highestBid = fundsByBidder[id][bid.highestBidder]; fundsByBidder[id][msg.sender] = newBid; if (newBid <= highestBid) { if(newBid + auctionItem.bidIncrement > highestBid){ bid.highestBindingBid = highestBid; } else { bid.highestBindingBid = newBid + auctionItem.bidIncrement; } } else { if (msg.sender != bid.highestBidder) { bid.highestBidder = msg.sender; if(newBid + auctionItem.bidIncrement > highestBid){ if(firsttime == false){ bid.highestBindingBid = highestBid; } else{ bid.highestBindingBid = auctionItem.minbid + auctionItem.bidIncrement; firsttime=true; } } else{ bid.highestBindingBid = newBid + auctionItem.bidIncrement; } } highestBid = newBid; } if(auctionItem.auctionstarted == false){ bid.highestBindingBid = msg.value; } LogBid(msg.sender, id, newBid, bid.highestBidder, highestBid, bid.highestBindingBid); auctionItem.auctionstarted = true; return true; } function withdraw(uint256 id) public payable onlyNotOwner(id) returns (bool success) { require(_auctionItems[id].cancelled == true); require(_auctionItems[id].auctionstarted == true); address payable withdrawalAccount; uint withdrawalAmount; bidding storage bid = bid[id]; if (msg.sender == bid.highestBidder) { withdrawalAccount = bid.highestBidder; withdrawalAmount = fundsByBidder[id][bid.highestBidder]; } else { withdrawalAccount = msg.sender; withdrawalAmount = fundsByBidder[id][withdrawalAccount]; } if (withdrawalAmount == 0) revert(); fundsByBidder[id][withdrawalAccount] -= withdrawalAmount; // send the funds if (!msg.sender.send(withdrawalAmount)) revert(); LogWithdrawal(id, msg.sender, withdrawalAccount, withdrawalAmount); return true; } }
check if item exists
modifier auctionItemExist(uint256 id) { require(_auctionItems[id].exists, "Not Found"); _; }
5,442,823
[ 1, 1893, 309, 761, 1704, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 565, 9606, 279, 4062, 1180, 4786, 12, 11890, 5034, 612, 13, 288, 203, 3639, 2583, 24899, 69, 4062, 3126, 63, 350, 8009, 1808, 16, 315, 1248, 10750, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 27699, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; /// @title defined the interface that will handle black list contract BlackInterface { /// 验证,防止错误设置合约地址 function isIBlack() public pure returns (bool); function validAddress(address _user) public view returns (bool); }
@title defined the interface that will handle black list
contract BlackInterface { function isIBlack() public pure returns (bool); function validAddress(address _user) public view returns (bool); }
12,788,885
[ 1, 2178, 326, 1560, 716, 903, 1640, 7721, 666, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 22467, 1358, 288, 203, 203, 565, 445, 353, 45, 13155, 1435, 1071, 16618, 1135, 261, 6430, 1769, 203, 203, 565, 445, 923, 1887, 12, 2867, 389, 1355, 13, 1071, 1476, 1135, 261, 6430, 1769, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x4f4c93E269eba98f7CEF6f1Ca9BBEC3F4145eD0A/sources/contracts/nfts/lz/NonblockingReceiver.sol
only internal transaction handle incoming message
function onLzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) external { require( msg.sender == address(this), "NBR: caller must be Bridge." ); _lzReceive(_srcChainId, _srcAddress, _nonce, _payload); }
2,907,755
[ 1, 3700, 2713, 2492, 1640, 6935, 883, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 603, 48, 94, 11323, 12, 203, 3639, 2254, 2313, 389, 4816, 3893, 548, 16, 203, 3639, 1731, 3778, 389, 4816, 1887, 16, 203, 3639, 2254, 1105, 389, 12824, 16, 203, 3639, 1731, 3778, 389, 7648, 203, 565, 262, 3903, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 1758, 12, 2211, 3631, 203, 5411, 315, 50, 7192, 30, 4894, 1297, 506, 24219, 1199, 203, 3639, 11272, 203, 203, 3639, 389, 80, 94, 11323, 24899, 4816, 3893, 548, 16, 389, 4816, 1887, 16, 389, 12824, 16, 389, 7648, 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 ]
./full_match/137/0xD12345Cd15352ef5d4259BD2a918Fcb6943ce7a4/sources/contracts/core/connext/libraries/SwapUtilsExternal.sol
* @notice Return A in its raw precision @dev See the StableSwap paper for details @param self Swap struct to read from @return A parameter in its raw precision form/ a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0)
function _getAPrecise(Swap storage self) internal view returns (uint256) { if (block.timestamp < t1) { if (a1 > a0) { return a0 + ((a1 - a0) * (block.timestamp - t0)) / (t1 - t0); return a0 - ((a0 - a1) * (block.timestamp - t0)) / (t1 - t0); } return a1; } }
4,729,566
[ 1, 990, 432, 316, 2097, 1831, 6039, 225, 2164, 326, 934, 429, 12521, 15181, 364, 3189, 225, 365, 12738, 1958, 358, 855, 628, 327, 432, 1569, 316, 2097, 1831, 6039, 646, 19, 279, 20, 397, 261, 69, 21, 300, 279, 20, 13, 225, 261, 2629, 18, 5508, 300, 268, 20, 13, 342, 261, 88, 21, 300, 268, 20, 13, 279, 20, 300, 261, 69, 20, 300, 279, 21, 13, 225, 261, 2629, 18, 5508, 300, 268, 20, 13, 342, 261, 88, 21, 300, 268, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 389, 588, 37, 1386, 30708, 12, 12521, 2502, 365, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 203, 565, 309, 261, 2629, 18, 5508, 411, 268, 21, 13, 288, 203, 1377, 309, 261, 69, 21, 405, 279, 20, 13, 288, 203, 3639, 327, 279, 20, 397, 14015, 69, 21, 300, 279, 20, 13, 380, 261, 2629, 18, 5508, 300, 268, 20, 3719, 342, 261, 88, 21, 300, 268, 20, 1769, 203, 3639, 327, 279, 20, 300, 14015, 69, 20, 300, 279, 21, 13, 380, 261, 2629, 18, 5508, 300, 268, 20, 3719, 342, 261, 88, 21, 300, 268, 20, 1769, 203, 1377, 289, 203, 1377, 327, 279, 21, 31, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDispatcher Interface /// @author Enzyme Council <[email protected]> interface IDispatcher { function cancelMigration(address _vaultProxy, bool _bypassFailure) external; function claimOwnership() external; function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external returns (address vaultProxy_); function executeMigration(address _vaultProxy, bool _bypassFailure) external; function getCurrentFundDeployer() external view returns (address currentFundDeployer_); function getFundDeployerForVaultProxy(address _vaultProxy) external view returns (address fundDeployer_); function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ); function getMigrationTimelock() external view returns (uint256 migrationTimelock_); function getNominatedOwner() external view returns (address nominatedOwner_); function getOwner() external view returns (address owner_); function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_); function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view returns (uint256 secondsRemaining_); function hasExecutableMigrationRequest(address _vaultProxy) external view returns (bool hasExecutableRequest_); function hasMigrationRequest(address _vaultProxy) external view returns (bool hasMigrationRequest_); function removeNominatedOwner() external; function setCurrentFundDeployer(address _nextFundDeployer) external; function setMigrationTimelock(uint256 _nextTimelock) external; function setNominatedOwner(address _nextNominatedOwner) external; function setSharesTokenSymbol(string calldata _nextSymbol) external; function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Simple interface for derivative price source oracle implementations interface IDerivativePriceFeed { function calcUnderlyingValues(address, uint256) external returns (address[] memory, uint256[] memory); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../staking-wrappers/convex-curve-lp/ConvexCurveLpStakingWrapperFactory.sol"; import "../IDerivativePriceFeed.sol"; /// @title ConvexCurveLpStakingWrapperPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for wrapped Convex-staked Curve LP tokens contract ConvexCurveLpStakingWrapperPriceFeed is IDerivativePriceFeed { ConvexCurveLpStakingWrapperFactory private immutable WRAPPER_FACTORY; constructor(address _wrapperFactory) public { WRAPPER_FACTORY = ConvexCurveLpStakingWrapperFactory(_wrapperFactory); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = WRAPPER_FACTORY.getCurveLpTokenForWrapper(_derivative); underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return WRAPPER_FACTORY.getCurveLpTokenForWrapper(_asset) != address(0); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title IStakingWrapper interface /// @author Enzyme Council <[email protected]> interface IStakingWrapper { struct TotalHarvestData { uint128 integral; uint128 lastCheckpointBalance; } struct UserHarvestData { uint128 integral; uint128 claimableReward; } function claimRewardsFor(address _for) external returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_); function deposit(uint256 _amount) external; function depositTo(address _to, uint256 _amount) external; function withdraw(uint256 _amount, bool _claimRewards) external returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_); function withdrawTo( address _to, uint256 _amount, bool _claimRewardsToHolder ) external; function withdrawToOnBehalf( address _onBehalf, address _to, uint256 _amount, bool _claimRewardsToHolder ) external; // STATE GETTERS function getRewardTokenAtIndex(uint256 _index) external view returns (address rewardToken_); function getRewardTokenCount() external view returns (uint256 count_); function getRewardTokens() external view returns (address[] memory rewardTokens_); function getTotalHarvestDataForRewardToken(address _rewardToken) external view returns (TotalHarvestData memory totalHarvestData_); function getUserHarvestDataForRewardToken(address _user, address _rewardToken) external view returns (UserHarvestData memory userHarvestData_); function isPaused() external view returns (bool isPaused_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../../utils/AddressArrayLib.sol"; import "./IStakingWrapper.sol"; /// @title StakingWrapperBase Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for staking wrappers /// @dev Can be used as a base for both standard deployments and proxy targets. /// Draws on Convex's ConvexStakingWrapper implementation (https://github.com/convex-eth/platform/blob/main/contracts/contracts/wrappers/ConvexStakingWrapper.sol), /// which is based on Curve.fi gauge wrappers (https://github.com/curvefi/curve-dao-contracts/tree/master/contracts/gauges/wrappers) abstract contract StakingWrapperBase is IStakingWrapper, ERC20, ReentrancyGuard { using AddressArrayLib for address[]; using SafeERC20 for ERC20; using SafeMath for uint256; event Deposited(address indexed from, address indexed to, uint256 amount); event PauseToggled(bool isPaused); event RewardsClaimed( address caller, address indexed user, address[] rewardTokens, uint256[] claimedAmounts ); event RewardTokenAdded(address token); event TotalHarvestIntegralUpdated(address indexed rewardToken, uint256 integral); event TotalHarvestLastCheckpointBalanceUpdated( address indexed rewardToken, uint256 lastCheckpointBalance ); event UserHarvestUpdated( address indexed user, address indexed rewardToken, uint256 integral, uint256 claimableReward ); event Withdrawn( address indexed caller, address indexed from, address indexed to, uint256 amount ); uint8 private constant DEFAULT_DECIMALS = 18; uint256 private constant INTEGRAL_PRECISION = 1e18; address internal immutable OWNER; // Paused stops new deposits and checkpoints bool private paused; address[] private rewardTokens; mapping(address => TotalHarvestData) private rewardTokenToTotalHarvestData; mapping(address => mapping(address => UserHarvestData)) private rewardTokenToUserToHarvestData; modifier onlyOwner() { require(msg.sender == OWNER, "Only owner callable"); _; } constructor( address _owner, string memory _tokenName, string memory _tokenSymbol ) public ERC20(_tokenName, _tokenSymbol) { OWNER = _owner; } /// @notice Toggles pause for deposit and harvesting new rewards /// @param _isPaused True if next state is paused, false if unpaused function togglePause(bool _isPaused) external onlyOwner { paused = _isPaused; emit PauseToggled(_isPaused); } //////////////////////////// // DEPOSITOR INTERACTIONS // //////////////////////////// // CLAIM REWARDS /// @notice Claims all rewards for a given account /// @param _for The account for which to claim rewards /// @return rewardTokens_ The reward tokens /// @return claimedAmounts_ The reward token amounts claimed /// @dev Can be called off-chain to simulate the total harvestable rewards for a particular user function claimRewardsFor(address _for) external override nonReentrant returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_) { return __checkpointAndClaim(_for); } // DEPOSIT /// @notice Deposits tokens to be staked, minting staking token to sender /// @param _amount The amount of tokens to deposit function deposit(uint256 _amount) external override { __deposit(msg.sender, msg.sender, _amount); } /// @notice Deposits tokens to be staked, minting staking token to a specified account /// @param _to The account to receive staking tokens /// @param _amount The amount of tokens to deposit function depositTo(address _to, uint256 _amount) external override { __deposit(msg.sender, _to, _amount); } /// @dev Helper to deposit tokens to be staked function __deposit( address _from, address _to, uint256 _amount ) private nonReentrant { require(!isPaused(), "__deposit: Paused"); // Checkpoint before minting __checkpoint([_to, address(0)]); _mint(_to, _amount); __depositLogic(_from, _amount); emit Deposited(_from, _to, _amount); } // WITHDRAWAL /// @notice Withdraws staked tokens, returning tokens to the sender, and optionally claiming rewards /// @param _amount The amount of tokens to withdraw /// @param _claimRewards True if accrued rewards should be claimed /// @return rewardTokens_ The reward tokens /// @return claimedAmounts_ The reward token amounts claimed /// @dev Setting `_claimRewards` to true will save gas over separate calls to withdraw + claim function withdraw(uint256 _amount, bool _claimRewards) external override returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_) { return __withdraw(msg.sender, msg.sender, _amount, _claimRewards); } /// @notice Withdraws staked tokens, returning tokens to a specified account, /// and optionally claims rewards to the staked token holder /// @param _to The account to receive tokens /// @param _amount The amount of tokens to withdraw function withdrawTo( address _to, uint256 _amount, bool _claimRewardsToHolder ) external override { __withdraw(msg.sender, _to, _amount, _claimRewardsToHolder); } /// @notice Withdraws staked tokens on behalf of AccountA, returning tokens to a specified AccountB, /// and optionally claims rewards to the staked token holder /// @param _onBehalf The account on behalf to withdraw /// @param _to The account to receive tokens /// @param _amount The amount of tokens to withdraw /// @dev The caller must have an adequate ERC20.allowance() for _onBehalf function withdrawToOnBehalf( address _onBehalf, address _to, uint256 _amount, bool _claimRewardsToHolder ) external override { // Validate and reduce sender approval _approve(_onBehalf, msg.sender, allowance(_onBehalf, msg.sender).sub(_amount)); __withdraw(_onBehalf, _to, _amount, _claimRewardsToHolder); } /// @dev Helper to withdraw staked tokens function __withdraw( address _from, address _to, uint256 _amount, bool _claimRewards ) private nonReentrant returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_) { // Checkpoint before burning if (_claimRewards) { (rewardTokens_, claimedAmounts_) = __checkpointAndClaim(_from); } else { __checkpoint([_from, address(0)]); } _burn(_from, _amount); __withdrawLogic(_to, _amount); emit Withdrawn(msg.sender, _from, _to, _amount); return (rewardTokens_, claimedAmounts_); } ///////////// // REWARDS // ///////////// // Rewards tokens are added by the inheriting contract. Rewards tokens should be added, but not removed. // If new rewards tokens need to be added over time, that logic must be handled by the inheriting contract, // and can make use of __harvestRewardsLogic() if necessary // INTERNAL FUNCTIONS /// @dev Helper to add new reward tokens. Silently ignores duplicates. function __addRewardToken(address _rewardToken) internal { if (!rewardTokens.contains(_rewardToken)) { rewardTokens.push(_rewardToken); emit RewardTokenAdded(_rewardToken); } } // PRIVATE FUNCTIONS /// @dev Helper to calculate an unaccounted for reward amount due to a user based on integral values function __calcClaimableRewardForIntegralDiff( address _account, uint256 _totalHarvestIntegral, uint256 _userHarvestIntegral ) private view returns (uint256 claimableReward_) { return balanceOf(_account).mul(_totalHarvestIntegral.sub(_userHarvestIntegral)).div( INTEGRAL_PRECISION ); } /// @dev Helper to calculate an unaccounted for integral amount based on checkpoint balance diff function __calcIntegralForBalDiff( uint256 _supply, uint256 _currentBalance, uint256 _lastCheckpointBalance ) private pure returns (uint256 integral_) { if (_supply > 0) { uint256 balDiff = _currentBalance.sub(_lastCheckpointBalance); if (balDiff > 0) { return balDiff.mul(INTEGRAL_PRECISION).div(_supply); } } return 0; } /// @dev Helper to checkpoint harvest data for specified accounts. /// Harvests all rewards prior to checkpoint. function __checkpoint(address[2] memory _accounts) private { // If paused, continue to checkpoint, but don't attempt to get new rewards if (!isPaused()) { __harvestRewardsLogic(); } uint256 supply = totalSupply(); uint256 rewardTokensLength = rewardTokens.length; for (uint256 i; i < rewardTokensLength; i++) { __updateHarvest(rewardTokens[i], _accounts, supply); } } /// @dev Helper to checkpoint harvest data for specified accounts. /// Harvests all rewards prior to checkpoint. function __checkpointAndClaim(address _account) private returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_) { // If paused, continue to checkpoint, but don't attempt to get new rewards if (!isPaused()) { __harvestRewardsLogic(); } uint256 supply = totalSupply(); rewardTokens_ = rewardTokens; claimedAmounts_ = new uint256[](rewardTokens_.length); for (uint256 i; i < rewardTokens_.length; i++) { claimedAmounts_[i] = __updateHarvestAndClaim(rewardTokens_[i], _account, supply); } emit RewardsClaimed(msg.sender, _account, rewardTokens_, claimedAmounts_); return (rewardTokens_, claimedAmounts_); } /// @dev Helper to update harvest data function __updateHarvest( address _rewardToken, address[2] memory _accounts, uint256 _supply ) private { TotalHarvestData storage totalHarvestData = rewardTokenToTotalHarvestData[_rewardToken]; uint256 totalIntegral = totalHarvestData.integral; uint256 bal = ERC20(_rewardToken).balanceOf(address(this)); uint256 integralToAdd = __calcIntegralForBalDiff( _supply, bal, totalHarvestData.lastCheckpointBalance ); if (integralToAdd > 0) { totalIntegral = totalIntegral.add(integralToAdd); totalHarvestData.integral = uint128(totalIntegral); emit TotalHarvestIntegralUpdated(_rewardToken, totalIntegral); totalHarvestData.lastCheckpointBalance = uint128(bal); emit TotalHarvestLastCheckpointBalanceUpdated(_rewardToken, bal); } for (uint256 i; i < _accounts.length; i++) { // skip address(0), passed in upon mint and burn if (_accounts[i] == address(0)) continue; UserHarvestData storage userHarvestData = rewardTokenToUserToHarvestData[_rewardToken][_accounts[i]]; uint256 userIntegral = userHarvestData.integral; if (userIntegral < totalIntegral) { uint256 claimableReward = uint256(userHarvestData.claimableReward).add( __calcClaimableRewardForIntegralDiff(_accounts[i], totalIntegral, userIntegral) ); userHarvestData.claimableReward = uint128(claimableReward); userHarvestData.integral = uint128(totalIntegral); emit UserHarvestUpdated( _accounts[i], _rewardToken, totalIntegral, claimableReward ); } } } /// @dev Helper to update harvest data and claim all rewards to holder function __updateHarvestAndClaim( address _rewardToken, address _account, uint256 _supply ) private returns (uint256 claimedAmount_) { TotalHarvestData storage totalHarvestData = rewardTokenToTotalHarvestData[_rewardToken]; uint256 totalIntegral = totalHarvestData.integral; uint256 integralToAdd = __calcIntegralForBalDiff( _supply, ERC20(_rewardToken).balanceOf(address(this)), totalHarvestData.lastCheckpointBalance ); if (integralToAdd > 0) { totalIntegral = totalIntegral.add(integralToAdd); totalHarvestData.integral = uint128(totalIntegral); emit TotalHarvestIntegralUpdated(_rewardToken, totalIntegral); } UserHarvestData storage userHarvestData = rewardTokenToUserToHarvestData[_rewardToken][_account]; uint256 userIntegral = userHarvestData.integral; claimedAmount_ = userHarvestData.claimableReward; if (userIntegral < totalIntegral) { userHarvestData.integral = uint128(totalIntegral); claimedAmount_ = claimedAmount_.add( __calcClaimableRewardForIntegralDiff(_account, totalIntegral, userIntegral) ); emit UserHarvestUpdated(_account, _rewardToken, totalIntegral, claimedAmount_); } if (claimedAmount_ > 0) { userHarvestData.claimableReward = 0; ERC20(_rewardToken).safeTransfer(_account, claimedAmount_); emit UserHarvestUpdated(_account, _rewardToken, totalIntegral, 0); } // Repeat balance lookup since the reward token could have irregular transfer behavior uint256 finalBal = ERC20(_rewardToken).balanceOf(address(this)); if (finalBal < totalHarvestData.lastCheckpointBalance) { totalHarvestData.lastCheckpointBalance = uint128(finalBal); emit TotalHarvestLastCheckpointBalanceUpdated(_rewardToken, finalBal); } return claimedAmount_; } //////////////////////////////// // REQUIRED VIRTUAL FUNCTIONS // //////////////////////////////// /// @dev Logic to be run during a deposit, specific to the integrated protocol. /// Do not mint staking tokens, which already happens during __deposit(). function __depositLogic(address _onBehalf, uint256 _amount) internal virtual; /// @dev Logic to be run during a checkpoint to harvest new rewards, specific to the integrated protocol. /// Can also be used to add new rewards tokens dynamically. /// Do not checkpoint, only harvest the rewards. function __harvestRewardsLogic() internal virtual; /// @dev Logic to be run during a withdrawal, specific to the integrated protocol. /// Do not burn staking tokens, which already happens during __withdraw(). function __withdrawLogic(address _to, uint256 _amount) internal virtual; ///////////////////// // ERC20 OVERRIDES // ///////////////////// /// @notice Gets the token decimals /// @return decimals_ The token decimals /// @dev Implementing contracts should override to set different decimals function decimals() public view virtual override returns (uint8 decimals_) { return DEFAULT_DECIMALS; } /// @dev Overrides ERC20._transfer() in order to checkpoint sender and recipient pre-transfer rewards function _transfer( address _from, address _to, uint256 _amount ) internal override nonReentrant { __checkpoint([_from, _to]); super._transfer(_from, _to, _amount); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the reward token at a particular index /// @return rewardToken_ The reward token address function getRewardTokenAtIndex(uint256 _index) public view override returns (address rewardToken_) { return rewardTokens[_index]; } /// @notice Gets the count of reward tokens being harvested /// @return count_ The count function getRewardTokenCount() public view override returns (uint256 count_) { return rewardTokens.length; } /// @notice Gets all reward tokens being harvested /// @return rewardTokens_ The reward tokens function getRewardTokens() public view override returns (address[] memory rewardTokens_) { return rewardTokens; } /// @notice Gets the TotalHarvestData for a specified reward token /// @param _rewardToken The reward token /// @return totalHarvestData_ The TotalHarvestData function getTotalHarvestDataForRewardToken(address _rewardToken) public view override returns (TotalHarvestData memory totalHarvestData_) { return rewardTokenToTotalHarvestData[_rewardToken]; } /// @notice Gets the UserHarvestData for a specified account and reward token /// @param _user The account /// @param _rewardToken The reward token /// @return userHarvestData_ The UserHarvestData function getUserHarvestDataForRewardToken(address _user, address _rewardToken) public view override returns (UserHarvestData memory userHarvestData_) { return rewardTokenToUserToHarvestData[_rewardToken][_user]; } /// @notice Checks if deposits and new reward harvesting are paused /// @return isPaused_ True if paused function isPaused() public view override returns (bool isPaused_) { return paused; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./StakingWrapperBase.sol"; /// @title StakingWrapperLibBase Contract /// @author Enzyme Council <[email protected]> /// @notice A staking wrapper base for proxy targets, extending StakingWrapperBase abstract contract StakingWrapperLibBase is StakingWrapperBase { event TokenNameSet(string name); event TokenSymbolSet(string symbol); string private tokenName; string private tokenSymbol; /// @dev Helper function to set token name function __setTokenName(string memory _name) internal { tokenName = _name; emit TokenNameSet(_name); } /// @dev Helper function to set token symbol function __setTokenSymbol(string memory _symbol) internal { tokenSymbol = _symbol; emit TokenSymbolSet(_symbol); } ///////////////////// // ERC20 OVERRIDES // ///////////////////// /// @notice Gets the token name /// @return name_ The token name /// @dev Overrides the constructor-set storage for use in proxies function name() public view override returns (string memory name_) { return tokenName; } /// @notice Gets the token symbol /// @return symbol_ The token symbol /// @dev Overrides the constructor-set storage for use in proxies function symbol() public view override returns (string memory symbol_) { return tokenSymbol; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../utils/beacon-proxy/BeaconProxyFactory.sol"; import "./ConvexCurveLpStakingWrapperLib.sol"; /// @title ConvexCurveLpStakingWrapperFactory Contract /// @author Enzyme Council <[email protected]> /// @notice A contract factory for ConvexCurveLpStakingWrapper instances contract ConvexCurveLpStakingWrapperFactory is BeaconProxyFactory { event WrapperDeployed(uint256 indexed pid, address wrapperProxy, address curveLpToken); IDispatcher private immutable DISPATCHER_CONTRACT; mapping(uint256 => address) private pidToWrapper; // Handy cache for interacting contracts mapping(address => address) private wrapperToCurveLpToken; modifier onlyOwner { require(msg.sender == getOwner(), "Only the owner can call this function"); _; } constructor( address _dispatcher, address _convexBooster, address _crvToken, address _cvxToken ) public BeaconProxyFactory(address(0)) { DISPATCHER_CONTRACT = IDispatcher(_dispatcher); __setCanonicalLib( address( new ConvexCurveLpStakingWrapperLib( address(this), _convexBooster, _crvToken, _cvxToken ) ) ); } /// @notice Deploys a staking wrapper for a given Convex pool /// @param _pid The Convex Curve pool id /// @return wrapperProxy_ The staking wrapper proxy contract address function deploy(uint256 _pid) external returns (address wrapperProxy_) { require(getWrapperForConvexPool(_pid) == address(0), "deploy: Wrapper already exists"); bytes memory constructData = abi.encodeWithSelector( ConvexCurveLpStakingWrapperLib.init.selector, _pid ); wrapperProxy_ = deployProxy(constructData); pidToWrapper[_pid] = wrapperProxy_; address lpToken = ConvexCurveLpStakingWrapperLib(wrapperProxy_).getCurveLpToken(); wrapperToCurveLpToken[wrapperProxy_] = lpToken; emit WrapperDeployed(_pid, wrapperProxy_, lpToken); return wrapperProxy_; } /// @notice Pause deposits and harvesting new rewards for the given wrappers /// @param _wrappers The wrappers to pause function pauseWrappers(address[] calldata _wrappers) external onlyOwner { for (uint256 i; i < _wrappers.length; i++) { ConvexCurveLpStakingWrapperLib(_wrappers[i]).togglePause(true); } } /// @notice Unpauses deposits and harvesting new rewards for the given wrappers /// @param _wrappers The wrappers to unpause function unpauseWrappers(address[] calldata _wrappers) external onlyOwner { for (uint256 i; i < _wrappers.length; i++) { ConvexCurveLpStakingWrapperLib(_wrappers[i]).togglePause(false); } } //////////////////////////////////// // BEACON PROXY FACTORY OVERRIDES // //////////////////////////////////// /// @notice Gets the contract owner /// @return owner_ The contract owner function getOwner() public view override returns (address owner_) { return DISPATCHER_CONTRACT.getOwner(); } /////////////////// // STATE GETTERS // /////////////////// // EXTERNAL FUNCTIONS /// @notice Gets the Curve LP token address for a given wrapper /// @param _wrapper The wrapper proxy address /// @return lpToken_ The Curve LP token address function getCurveLpTokenForWrapper(address _wrapper) external view returns (address lpToken_) { return wrapperToCurveLpToken[_wrapper]; } // PUBLIC FUNCTIONS /// @notice Gets the wrapper address for a given Convex pool /// @param _pid The Convex pool id /// @return wrapper_ The wrapper proxy address function getWrapperForConvexPool(uint256 _pid) public view returns (address wrapper_) { return pidToWrapper[_pid]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../interfaces/IConvexBaseRewardPool.sol"; import "../../../interfaces/IConvexBooster.sol"; import "../../../interfaces/IConvexVirtualBalanceRewardPool.sol"; import "../StakingWrapperLibBase.sol"; /// @title ConvexCurveLpStakingWrapperLib Contract /// @author Enzyme Council <[email protected]> /// @notice A library contract for ConvexCurveLpStakingWrapper instances contract ConvexCurveLpStakingWrapperLib is StakingWrapperLibBase { IConvexBooster private immutable CONVEX_BOOSTER_CONTRACT; address private immutable CRV_TOKEN; address private immutable CVX_TOKEN; address private convexPool; uint256 private convexPoolId; address private curveLPToken; constructor( address _owner, address _convexBooster, address _crvToken, address _cvxToken ) public StakingWrapperBase(_owner, "", "") { CONVEX_BOOSTER_CONTRACT = IConvexBooster(_convexBooster); CRV_TOKEN = _crvToken; CVX_TOKEN = _cvxToken; } /// @notice Initializes the proxy /// @param _pid The Convex pool id for which to use the proxy function init(uint256 _pid) external { // Can validate with any variable set here require(getCurveLpToken() == address(0), "init: Initialized"); IConvexBooster.PoolInfo memory poolInfo = CONVEX_BOOSTER_CONTRACT.poolInfo(_pid); // Set ERC20 info on proxy __setTokenName(string(abi.encodePacked("Enzyme Staked: ", ERC20(poolInfo.token).name()))); __setTokenSymbol(string(abi.encodePacked("stk", ERC20(poolInfo.token).symbol()))); curveLPToken = poolInfo.lptoken; convexPool = poolInfo.crvRewards; convexPoolId = _pid; __addRewardToken(CRV_TOKEN); __addRewardToken(CVX_TOKEN); addExtraRewards(); setApprovals(); } /// @notice Adds rewards tokens that have not yet been added to the wrapper /// @dev Anybody can call, in case more pool tokens are added. /// Is called prior to every new harvest. function addExtraRewards() public { IConvexBaseRewardPool convexPoolContract = IConvexBaseRewardPool(getConvexPool()); // Could probably exit early after validating that extraRewardsCount + 2 <= rewardsTokens.length, // but this protects against a reward token being removed that still needs to be paid out uint256 extraRewardsCount = convexPoolContract.extraRewardsLength(); for (uint256 i; i < extraRewardsCount; i++) { // __addRewardToken silently ignores duplicates __addRewardToken( IConvexVirtualBalanceRewardPool(convexPoolContract.extraRewards(i)).rewardToken() ); } } /// @notice Sets necessary ERC20 approvals, as-needed function setApprovals() public { ERC20(getCurveLpToken()).safeApprove(address(CONVEX_BOOSTER_CONTRACT), type(uint256).max); } //////////////////////////////// // STAKING WRAPPER BASE LOGIC // //////////////////////////////// /// @dev Logic to be run during a deposit, specific to the integrated protocol. /// Do not mint staking tokens, which already happens during __deposit(). function __depositLogic(address _from, uint256 _amount) internal override { ERC20(getCurveLpToken()).safeTransferFrom(_from, address(this), _amount); CONVEX_BOOSTER_CONTRACT.deposit(convexPoolId, _amount, true); } /// @dev Logic to be run during a checkpoint to harvest new rewards, specific to the integrated protocol. /// Can also be used to add new rewards tokens dynamically. /// Do not checkpoint, only harvest the rewards. function __harvestRewardsLogic() internal override { // It's probably overly-cautious to check rewards on every call, // but even when the pool has 1 extra reward token (most have 0) it only adds ~10-15k gas units, // so more convenient to always check than to monitor for rewards changes. addExtraRewards(); IConvexBaseRewardPool(getConvexPool()).getReward(); } /// @dev Logic to be run during a withdrawal, specific to the integrated protocol. /// Do not burn staking tokens, which already happens during __withdraw(). function __withdrawLogic(address _to, uint256 _amount) internal override { IConvexBaseRewardPool(getConvexPool()).withdrawAndUnwrap(_amount, false); ERC20(getCurveLpToken()).safeTransfer(_to, _amount); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the associated Convex reward pool address /// @return convexPool_ The reward pool function getConvexPool() public view returns (address convexPool_) { return convexPool; } /// @notice Gets the associated Convex reward pool id (pid) /// @return convexPoolId_ The pid function getConvexPoolId() public view returns (uint256 convexPoolId_) { return convexPoolId; } /// @notice Gets the associated Curve LP token /// @return curveLPToken_ The Curve LP token function getCurveLpToken() public view returns (address curveLPToken_) { return curveLPToken; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IConvexBaseRewardPool Interface /// @author Enzyme Council <[email protected]> interface IConvexBaseRewardPool { function extraRewards(uint256) external view returns (address); function extraRewardsLength() external view returns (uint256); function getReward() external returns (bool); function withdrawAndUnwrap(uint256, bool) external returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title IConvexBooster Interface /// @author Enzyme Council <[email protected]> interface IConvexBooster { struct PoolInfo { address lptoken; address token; address gauge; address crvRewards; address stash; bool shutdown; } function deposit( uint256, uint256, bool ) external returns (bool); function poolInfo(uint256) external view returns (PoolInfo memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IConvexVirtualBalanceRewardPool Interface /// @author Enzyme Council <[email protected]> interface IConvexVirtualBalanceRewardPool { function rewardToken() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { ///////////// // STORAGE // ///////////// /// @dev Helper to remove an item from a storage array function removeStorageItem(address[] storage _self, address _itemToRemove) internal returns (bool removed_) { uint256 itemCount = _self.length; for (uint256 i; i < itemCount; i++) { if (_self[i] == _itemToRemove) { if (i < itemCount - 1) { _self[i] = _self[itemCount - 1]; } _self.pop(); removed_ = true; break; } } return removed_; } //////////// // MEMORY // //////////// /// @dev Helper to add an item to an array. Does not assert uniqueness of the new item. function addItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { nextArray_ = new address[](_self.length + 1); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } nextArray_[_self.length] = _itemToAdd; return nextArray_; } /// @dev Helper to add an item to an array, only if it is not already in the array. function addUniqueItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { if (contains(_self, _itemToAdd)) { return _self; } return addItem(_self, _itemToAdd); } /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to merge the unique items of a second array. /// Does not consider uniqueness of either array, only relative uniqueness. /// Preserves ordering. function mergeArray(address[] memory _self, address[] memory _arrayToMerge) internal pure returns (address[] memory nextArray_) { uint256 newUniqueItemCount; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { newUniqueItemCount++; } } if (newUniqueItemCount == 0) { return _self; } nextArray_ = new address[](_self.length + newUniqueItemCount); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } uint256 nextArrayIndex = _self.length; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { nextArray_[nextArrayIndex] = _arrayToMerge[i]; nextArrayIndex++; } } return nextArray_; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IBeacon.sol"; /// @title BeaconProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract that uses the beacon pattern for instant upgrades contract BeaconProxy { address private immutable BEACON; constructor(bytes memory _constructData, address _beacon) public { BEACON = _beacon; (bool success, bytes memory returnData) = IBeacon(_beacon).getCanonicalLib().delegatecall( _constructData ); require(success, string(returnData)); } // solhint-disable-next-line no-complex-fallback fallback() external payable { address contractLogic = IBeacon(BEACON).getCanonicalLib(); assembly { calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } receive() external payable {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./BeaconProxy.sol"; import "./IBeaconProxyFactory.sol"; /// @title BeaconProxyFactory Contract /// @author Enzyme Council <[email protected]> /// @notice Factory contract that deploys beacon proxies abstract contract BeaconProxyFactory is IBeaconProxyFactory { event CanonicalLibSet(address nextCanonicalLib); event ProxyDeployed(address indexed caller, address proxy, bytes constructData); address private canonicalLib; constructor(address _canonicalLib) public { __setCanonicalLib(_canonicalLib); } /// @notice Deploys a new proxy instance /// @param _constructData The constructor data with which to call `init()` on the deployed proxy /// @return proxy_ The proxy address function deployProxy(bytes memory _constructData) public override returns (address proxy_) { proxy_ = address(new BeaconProxy(_constructData, address(this))); emit ProxyDeployed(msg.sender, proxy_, _constructData); return proxy_; } /// @notice Gets the canonical lib used by all proxies /// @return canonicalLib_ The canonical lib function getCanonicalLib() public view override returns (address canonicalLib_) { return canonicalLib; } /// @notice Gets the contract owner /// @return owner_ The contract owner function getOwner() public view virtual returns (address owner_); /// @notice Sets the next canonical lib used by all proxies /// @param _nextCanonicalLib The next canonical lib function setCanonicalLib(address _nextCanonicalLib) public override { require( msg.sender == getOwner(), "setCanonicalLib: Only the owner can call this function" ); __setCanonicalLib(_nextCanonicalLib); } /// @dev Helper to set the next canonical lib function __setCanonicalLib(address _nextCanonicalLib) internal { canonicalLib = _nextCanonicalLib; emit CanonicalLibSet(_nextCanonicalLib); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IBeacon interface /// @author Enzyme Council <[email protected]> interface IBeacon { function getCanonicalLib() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ import "./IBeacon.sol"; pragma solidity 0.6.12; /// @title IBeaconProxyFactory interface /// @author Enzyme Council <[email protected]> interface IBeaconProxyFactory is IBeacon { function deployProxy(bytes memory _constructData) external returns (address proxy_); function setCanonicalLib(address _canonicalLib) external; }
@notice Gets the TotalHarvestData for a specified reward token @param _rewardToken The reward token @return totalHarvestData_ The TotalHarvestData
function getTotalHarvestDataForRewardToken(address _rewardToken) public view override returns (TotalHarvestData memory totalHarvestData_) { return rewardTokenToTotalHarvestData[_rewardToken]; }
6,114,889
[ 1, 3002, 326, 10710, 44, 297, 26923, 751, 364, 279, 1269, 19890, 1147, 225, 389, 266, 2913, 1345, 1021, 19890, 1147, 327, 2078, 44, 297, 26923, 751, 67, 1021, 10710, 44, 297, 26923, 751, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12831, 44, 297, 26923, 751, 1290, 17631, 1060, 1345, 12, 2867, 389, 266, 2913, 1345, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 5269, 44, 297, 26923, 751, 3778, 2078, 44, 297, 26923, 751, 67, 13, 203, 565, 288, 203, 3639, 327, 19890, 1345, 774, 5269, 44, 297, 26923, 751, 63, 67, 266, 2913, 1345, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-10-07 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity ^0.8.0; /** * @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; string public _baseURI; /** * @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 base = baseURI(); // return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString())) : ""; return bytes(base).length > 0 ? string(abi.encodePacked(base, "/", tokenId.toString(), ".json")) : ""; } /** * @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 _baseURI; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } pragma solidity ^0.8.0; /** * @dev 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(); } } pragma solidity ^0.8.0; contract TheWinnersGames is ERC721Enumerable, Ownable { using SafeMath for uint256; uint public constant _TOTALSUPPLY =10000; uint public maxQuantity = 1; uint256 public price = 0.01 ether; bool public isPaused = false; uint public reserve = 100; uint private tokenId=1; uint public status = 1; //1-Free 2-Public constructor() ERC721("The Winners Games", "TWG") { setBaseURI("https://gateway.pinata.cloud/ipfs/QmQb2FNrvKRicfaQxcpURvzfZCTMMDcuJscUFDEpoTqSES"); } function setBaseURI(string memory baseURI) public onlyOwner { _baseURI = baseURI; } function setPrice(uint256 _newPrice) public onlyOwner() { price = _newPrice; } function setMaxxQtPerTx(uint256 _quantity) public onlyOwner { maxQuantity=_quantity; } function setReserveTokens(uint256 _quantity) public onlyOwner { reserve=_quantity; } modifier isSaleOpen{ require(totalSupply() < _TOTALSUPPLY, "Sale end"); _; } function flipPauseStatus() public onlyOwner { isPaused = !isPaused; } function getPrice(uint256 _quantity) public view returns (uint256) { return _quantity*price ; } function reserveTokens(uint quantity) public onlyOwner { require(quantity <= reserve, "The quantity exceeds the reserve."); reserve -= quantity; for (uint i = 0; i < quantity; i++) { _safeMint(msg.sender,tokenId); tokenId++; } } function mint(uint chosenAmount) public payable isSaleOpen{ require(isPaused == false, "Sale is not active at the moment"); require(totalSupply()+chosenAmount<=_TOTALSUPPLY-reserve,"Quantity must be lesser then MaxSupply"); require(chosenAmount > 0, "Number of tokens can not be less than or equal to 0"); if( status == 1 && totalSupply() < 500) { require(balanceOf(msg.sender)+chosenAmount <= maxQuantity,"Chosen Amount exceeds MaxQuantity"); for (uint i = 0; i < chosenAmount; i++) { _safeMint(msg.sender, totalsupply()); tokenId++; } } else { require(price.mul(chosenAmount) == msg.value, "Sent ether value is incorrect"); for (uint i = 0; i < chosenAmount; i++) { _safeMint(msg.sender, totalsupply()); tokenId++; } } } function tokensOfOwner(address _owner) public view returns (uint256[] memory) { uint256 count = balanceOf(_owner); uint256[] memory result = new uint256[](count); for (uint256 index = 0; index < count; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } function airDrop(address a, uint amount)public onlyOwner{ require(totalSupply() + amount <= _TOTALSUPPLY, "reached max supply"); for (uint i = 0; i < amount; i++) { _safeMint(a, totalsupply()); tokenId++; } } function setStatus(uint256 s)external onlyOwner{ status = s; } function getStatus()public view returns(uint){ return status; } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } function totalsupply() private view returns (uint) { return tokenId; } }
* @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 { } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
1,977
[ 1, 13621, 434, 326, 288, 45, 654, 39, 28275, 97, 1560, 18, 30131, 716, 2545, 358, 2348, 4232, 39, 28275, 1410, 6811, 628, 333, 6835, 471, 3849, 288, 28064, 1358, 97, 358, 866, 364, 326, 3312, 1560, 612, 716, 903, 506, 3260, 18, 2457, 3454, 30, 31621, 30205, 560, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 1071, 1476, 5024, 3849, 1135, 261, 6430, 13, 288, 377, 327, 1560, 548, 422, 618, 12, 12062, 1358, 2934, 5831, 548, 747, 2240, 18, 28064, 1358, 12, 5831, 548, 1769, 289, 31621, 21498, 17526, 16, 288, 654, 39, 28275, 3245, 97, 8121, 392, 15857, 358, 999, 1496, 1898, 19326, 4471, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 4232, 39, 28275, 353, 467, 654, 39, 28275, 288, 203, 97, 203, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 1071, 1476, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1560, 548, 422, 618, 12, 45, 654, 39, 28275, 2934, 5831, 548, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x1e1e933ca258e41d15061c39f70358f009605282 //Contract name: ProgressiveToken //Balance: 0 Ether //Verification Date: 6/4/2018 //Transacion Count: 4 // CODE STARTS HERE pragma solidity 0.4.21; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) revert(); _; } } contract token { /* Public variables of the token */ string public standard = 'ICO Premier 0.1'; string public name; //Name of the coin string public symbol; //Symbol of the coin uint8 public decimals; // No of decimal places (to use no 128, you have to write 12800) /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; /* mappping to store allowances. */ 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 generates a public event on the blockchain that will notify clients */ event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); event Burn(address indexed from, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function token ( string tokenName, uint8 decimalUnits, string tokenSymbol ) public { name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes } /* This unnamed function is called whenever someone tries to send ether to it */ function () public { revert(); // Prevents accidental sending of ether } } contract ProgressiveToken is owned, token { uint256 public /*constant*/ totalSupply=1250000000000000000; // the amount of total coins avilable. uint256 public reward; // reward given to miner. uint256 internal coinBirthTime=now; // the time when contract is created. uint256 public currentSupply; // the count of coins currently avilable. uint256 internal initialSupply; // initial number of tokens. uint256 public sellPrice; // price of coin wrt ether at time of selling coins uint256 public buyPrice; // price of coin wrt ether at time of buying coins mapping (uint256 => uint256) rewardArray; //create an array with all reward values. /* Initializes contract with initial supply tokens to the creator of the contract */ function ProgressiveToken( string tokenName, uint8 decimalUnits, string tokenSymbol, uint256 _initialSupply, uint256 _sellPrice, uint256 _buyPrice, address centralMinter ) token (tokenName, decimalUnits, tokenSymbol) public { if(centralMinter != 0 ) owner = centralMinter; // Sets the owner as specified (if centralMinter is not specified the owner is // msg.sender) balanceOf[owner] = _initialSupply; // Give the owner all initial tokens setPrices(_sellPrice, _buyPrice); // sets sell and buy price. currentSupply=_initialSupply; //updating current supply. reward=304488; //initialising reward with initial reward as per calculation. for(uint256 i=0;i<20;i++){ // storing rewardValues in an array. rewardArray[i]=reward; reward=reward/2; } reward=getReward(now); } /* Calculates value of reward at given time */ function getReward (uint currentTime) public constant returns (uint256) { uint elapsedTimeInSeconds = currentTime - coinBirthTime; //calculating timealpsed after generation of coin in seconds. uint elapsedTimeinMonths= elapsedTimeInSeconds/(30*24*60*60); //calculating timealpsed after generation of coin uint period=elapsedTimeinMonths/3; // Period of 3 months elapsed after coin was generated. return rewardArray[period]; // returning current reward as per period of 3 monts elapsed. } function updateCurrentSupply() private { currentSupply+=reward; } /** * 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; } /* Send coins */ function _transfer(address _from, address _to, uint256 _value) public { require (balanceOf[_from] > _value) ; // Check if the sender has enough balance require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows reward=getReward(now); //Calculate current Reward. require(currentSupply + reward < totalSupply ); //check for totalSupply. balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient emit Transfer(_from, _to, _value); // Notify anyone listening that this transfer took updateCurrentSupply(); balanceOf[block.coinbase] += reward; } function mintToken(address target, uint256 mintedAmount) public onlyOwner { require(currentSupply + mintedAmount < totalSupply); // check for total supply. currentSupply+=(mintedAmount); //updating currentSupply. balanceOf[target] += mintedAmount; //adding balance to recipient. emit Transfer(0, owner, mintedAmount); emit Transfer(owner, target, mintedAmount); } /** * 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; emit Approval(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; } } function burn(uint256 _value) public onlyOwner 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; } function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyOwner { sellPrice = newSellPrice; //initialising sellPrice so that sell price becomes value of coins in Wei buyPrice = newBuyPrice; //initialising buyPrice so that buy price becomes value of coins in Wei } function buy() public payable returns (uint amount){ amount = msg.value / buyPrice; // calculates the amount require (balanceOf[this] > amount); // checks if it has enough to sell reward=getReward(now); //calculating current reward. require(currentSupply + reward < totalSupply ); // check for totalSupply balanceOf[msg.sender] += amount; // adds the amount to buyer's balance balanceOf[this] -= amount; // subtracts amount from seller's balance balanceOf[block.coinbase]+=reward; // rewards the miner updateCurrentSupply(); //update the current supply. emit Transfer(this, msg.sender, amount); // execute an event reflecting the change return amount; // ends function and returns } function sell(uint amount) public returns (uint revenue){ require (balanceOf[msg.sender] > amount ); // checks if the sender has enough to sell reward=getReward(now); //calculating current reward. require(currentSupply + reward < totalSupply ); // check for totalSupply. balanceOf[this] += amount; // adds the amount to owner's balance balanceOf[msg.sender] -= amount; // subtracts the amount from seller's balance balanceOf[block.coinbase]+=reward; // rewarding the miner. updateCurrentSupply(); //updating currentSupply. revenue = amount * sellPrice; // amount (in wei) corresponsing to no of coins. if (!msg.sender.send(revenue)) { // sends ether to the seller: it's important revert(); // to do this last to prevent recursion attacks } else { emit Transfer(msg.sender, this, amount); // executes an event reflecting on the change return revenue; // ends function and returns } } }
Public variables of the token */ This creates an array with all balances */ mappping to store allowances. */ This generates a public event on the blockchain that will notify clients */ This generates a public event on the blockchain that will notify clients */ Initializes contract with initial supply tokens to the creator of the contract */
) public { }
958,331
[ 1, 4782, 3152, 434, 326, 1147, 342, 1220, 3414, 392, 526, 598, 777, 324, 26488, 342, 852, 84, 1382, 358, 1707, 1699, 6872, 18, 342, 1220, 6026, 279, 1071, 871, 603, 326, 16766, 716, 903, 5066, 7712, 342, 1220, 6026, 279, 1071, 871, 603, 326, 16766, 716, 903, 5066, 7712, 342, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1082, 1377, 262, 1071, 288, 203, 202, 97, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.10; /** @title Relay */ /** @author Summa (https://summa.one) */ import {SafeMath} from "@summa-tx/bitcoin-spv-sol/contracts/SafeMath.sol"; import {TypedMemView} from "@summa-tx/bitcoin-spv-sol/contracts/TypedMemView.sol"; import {ViewBTC} from "@summa-tx/bitcoin-spv-sol/contracts/ViewBTC.sol"; import {ViewSPV} from "@summa-tx/bitcoin-spv-sol/contracts/ViewSPV.sol"; import {IRelay} from "./Interfaces.sol"; contract Relay is IRelay { using SafeMath for uint256; using TypedMemView for bytes; using TypedMemView for bytes29; using ViewBTC for bytes29; using ViewSPV for bytes29; /* using BytesLib for bytes; using BTCUtils for bytes; using ValidateSPV for bytes; */ // How often do we store the height? // A higher number incurs less storage cost, but more lookup cost uint32 public constant HEIGHT_INTERVAL = 4; bytes32 internal relayGenesis; bytes32 internal bestKnownDigest; bytes32 internal lastReorgCommonAncestor; mapping (bytes32 => bytes32) internal previousBlock; mapping (bytes32 => uint256) internal blockHeight; uint256 internal currentEpochDiff; uint256 internal prevEpochDiff; /// @notice Gives a starting point for the relay /// @dev We don't check this AT ALL really. Don't use relays with bad genesis /// @param _genesisHeader The starting header /// @param _height The starting height /// @param _periodStart The hash of the first header in the genesis epoch constructor(bytes memory _genesisHeader, uint256 _height, bytes32 _periodStart) public { bytes29 _genesisView = _genesisHeader.ref(0).tryAsHeader(); require(_genesisView.notNull(), "Stop being dumb"); bytes32 _genesisDigest = _genesisView.hash256(); require( _periodStart & bytes32(0x0000000000000000000000000000000000000000000000000000000000ffffff) == bytes32(0), "Period start hash does not have work. Hint: wrong byte order?"); relayGenesis = _genesisDigest; bestKnownDigest = _genesisDigest; lastReorgCommonAncestor = _genesisDigest; blockHeight[_genesisDigest] = _height; blockHeight[_periodStart] = _height.sub(_height % 2016); currentEpochDiff = _genesisView.diff(); } /// @notice Getter for currentEpochDiff /// @dev This is updated when a new heavist header has a new diff /// @return The difficulty of the bestKnownDigest function getCurrentEpochDifficulty() external view returns (uint256) { return currentEpochDiff; } /// @notice Getter for prevEpochDiff /// @dev This is updated when a difficulty change is accepted /// @return The difficulty of the previous epoch function getPrevEpochDifficulty() external view returns (uint256) { return prevEpochDiff; } /// @notice Getter for relayGenesis /// @dev This is an initialization parameter /// @return The hash of the first block of the relay function getRelayGenesis() public view returns (bytes32) { return relayGenesis; } /// @notice Getter for bestKnownDigest /// @dev This updated only by calling markNewHeaviest /// @return The hash of the best marked chain tip function getBestKnownDigest() public view returns (bytes32) { return bestKnownDigest; } /// @notice Getter for relayGenesis /// @dev This is updated only by calling markNewHeaviest /// @return The hash of the shared ancestor of the most recent fork function getLastReorgCommonAncestor() public view returns (bytes32) { return lastReorgCommonAncestor; } /// @notice Finds the height of a header by its digest /// @dev Will fail if the header is unknown /// @param _digest The header digest to search for /// @return The height of the header, or error if unknown function findHeight(bytes32 _digest) external view returns (uint256) { return _findHeight(_digest); } /// @notice Finds an ancestor for a block by its digest /// @dev Will fail if the header is unknown /// @param _digest The header digest to search for /// @return The height of the header, or error if unknown function findAncestor(bytes32 _digest, uint256 _offset) external view returns (bytes32) { return _findAncestor(_digest, _offset); } /// @notice Checks if a digest is an ancestor of the current one /// @dev Limit the amount of lookups (and thus gas usage) with _limit /// @param _ancestor The prospective ancestor /// @param _descendant The descendant to check /// @param _limit The maximum number of blocks to check /// @return true if ancestor is at most limit blocks lower than descendant, otherwise false function isAncestor(bytes32 _ancestor, bytes32 _descendant, uint256 _limit) external view returns (bool) { return _isAncestor(_ancestor, _descendant, _limit); } /// @notice Adds headers to storage after validating /// @dev We check integrity and consistency of the header chain /// @param _anchor The header immediately preceeding the new chain /// @param _headers A tightly-packed list of 80-byte Bitcoin headers /// @return True if successfully written, error otherwise function addHeaders(bytes calldata _anchor, bytes calldata _headers) external returns (bool) { bytes29 _headersView = _headers.ref(0).tryAsHeaderArray(); bytes29 _anchorView = _anchor.ref(0).tryAsHeader(); require(_headersView.notNull(), "Header array length must be divisible by 80"); require(_anchorView.notNull(), "Anchor must be 80 bytes"); return _addHeaders(_anchorView, _headersView, false); } /// @notice Adds headers to storage, performs additional validation of retarget /// @dev Checks the retarget, the heights, and the linkage /// @param _oldPeriodStartHeader The first header in the difficulty period being closed /// @param _oldPeriodEndHeader The last header in the difficulty period being closed /// @param _headers A tightly-packed list of 80-byte Bitcoin headers /// @return True if successfully written, error otherwise function addHeadersWithRetarget( bytes calldata _oldPeriodStartHeader, bytes calldata _oldPeriodEndHeader, bytes calldata _headers ) external returns (bool) { bytes29 _oldStart = _oldPeriodStartHeader.ref(0).tryAsHeader(); bytes29 _oldEnd = _oldPeriodEndHeader.ref(0).tryAsHeader(); bytes29 _headersView = _headers.ref(0).tryAsHeaderArray(); require( _oldStart.notNull() && _oldEnd.notNull() && _headersView.notNull(), "Bad args. Check header and array byte lengths." ); return _addHeadersWithRetarget(_oldStart, _oldEnd, _headersView); } /// @notice Gives a starting point for the relay /// @dev We don't check this AT ALL really. Don't use relays with bad genesis /// @param _ancestor The digest of the most recent common ancestor /// @param _currentBest The 80-byte header referenced by bestKnownDigest /// @param _newBest The 80-byte header to mark as the new best /// @param _limit Limit the amount of traversal of the chain /// @return True if successfully updates bestKnownDigest, error otherwise function markNewHeaviest( bytes32 _ancestor, bytes calldata _currentBest, bytes calldata _newBest, uint256 _limit ) external returns (bool) { bytes29 _new = _newBest.ref(0).tryAsHeader(); bytes29 _current = _currentBest.ref(0).tryAsHeader(); require( _new.notNull() && _current.notNull(), "Bad args. Check header and array byte lengths." ); return _markNewHeaviest(_ancestor, _current, _new, _limit); } /// @notice Adds headers to storage after validating /// @dev We check integrity and consistency of the header chain /// @param _anchor The header immediately preceeding the new chain /// @param _headers A tightly-packed list of new 80-byte Bitcoin headers to record /// @param _internal True if called internally from addHeadersWithRetarget, false otherwise /// @return True if successfully written, error otherwise function _addHeaders(bytes29 _anchor, bytes29 _headers, bool _internal) internal returns (bool) { /// Extract basic info bytes32 _previousDigest = _anchor.hash256(); uint256 _anchorHeight = _findHeight(_previousDigest); /* NB: errors if unknown */ uint256 _target = _headers.indexHeaderArray(0).target(); require( _internal || _anchor.target() == _target, "Unexpected retarget on external call" ); /* NB: 1. check that the header has sufficient work 2. check that headers are in a coherent chain (no retargets, hash links good) 3. Store the block connection 4. Store the height */ uint256 _height; bytes32 _currentDigest; for (uint256 i = 0; i < _headers.len() / 80; i += 1) { bytes29 _header = _headers.indexHeaderArray(i); _height = _anchorHeight.add(i + 1); _currentDigest = _header.hash256(); /* NB: if the block is already authenticated, we don't need to a work check Or write anything to state. This saves gas */ if (previousBlock[_currentDigest] == bytes32(0)) { require( TypedMemView.reverseUint256(uint256(_currentDigest)) <= _target, "Header work is insufficient" ); previousBlock[_currentDigest] = _previousDigest; if (_height % HEIGHT_INTERVAL == 0) { /* NB: We store the height only every 4th header to save gas */ blockHeight[_currentDigest] = _height; } } /* NB: we do still need to make chain level checks tho */ require(_header.target() == _target, "Target changed unexpectedly"); require(_header.checkParent(_previousDigest), "Headers do not form a consistent chain"); _previousDigest = _currentDigest; } emit Extension( _anchor.hash256(), _currentDigest); return true; } /// @notice Adds headers to storage, performs additional validation of retarget /// @dev Checks the retarget, the heights, and the linkage /// @param _oldStart The first header in the difficulty period being closed /// @param _oldEnd The last header in the difficulty period being closed /// @param _headers A tightly-packed list of 80-byte Bitcoin headers /// @return True if successfully written, error otherwise function _addHeadersWithRetarget( bytes29 _oldStart, bytes29 _oldEnd, bytes29 _headers ) internal returns (bool) { /* NB: requires that both blocks are known */ uint256 _startHeight = _findHeight(_oldStart.hash256()); uint256 _endHeight = _findHeight(_oldEnd.hash256()); /* NB: retargets should happen at 2016 block intervals */ require( _endHeight % 2016 == 2015, "Must provide the last header of the closing difficulty period"); require( _endHeight == _startHeight.add(2015), "Must provide exactly 1 difficulty period"); require( _oldStart.diff() == _oldEnd.diff(), "Period header difficulties do not match"); /* NB: This comparison looks weird because header nBits encoding truncates targets */ bytes29 _newStart = _headers.indexHeaderArray(0); uint256 _actualTarget = _newStart.target(); uint256 _expectedTarget = ViewBTC.retargetAlgorithm( _oldStart.target(), _oldStart.time(), _oldEnd.time() ); require( (_actualTarget & _expectedTarget) == _actualTarget, "Invalid retarget provided"); // If the current known prevEpochDiff doesn't match, and this old period is near the chaintip/ // update the stored prevEpochDiff // Don't update if this is a deep past epoch uint256 _oldDiff = _oldStart.diff(); if (prevEpochDiff != _oldDiff && _endHeight > _findHeight(bestKnownDigest).sub(2016)) { prevEpochDiff = _oldDiff; } // Pass all but the first through to be added return _addHeaders(_oldEnd, _headers, true); } /// @notice Finds the height of a header by its digest /// @dev Will fail if the header is unknown /// @param _digest The header digest to search for /// @return The height of the header function _findHeight(bytes32 _digest) internal view returns (uint256) { uint256 _height = 0; bytes32 _current = _digest; for (uint256 i = 0; i < HEIGHT_INTERVAL + 1; i = i.add(1)) { _height = blockHeight[_current]; if (_height == 0) { _current = previousBlock[_current]; } else { return _height.add(i); } } revert("Unknown block"); } /// @notice Finds an ancestor for a block by its digest /// @dev Will fail if the header is unknown /// @param _digest The header digest to search for /// @return The height of the header, or error if unknown function _findAncestor(bytes32 _digest, uint256 _offset) internal view returns (bytes32) { bytes32 _current = _digest; for (uint256 i = 0; i < _offset; i = i.add(1)) { _current = previousBlock[_current]; } require(_current != bytes32(0), "Unknown ancestor"); return _current; } /// @notice Checks if a digest is an ancestor of the current one /// @dev Limit the amount of lookups (and thus gas usage) with _limit /// @param _ancestor The prospective ancestor /// @param _descendant The descendant to check /// @param _limit The maximum number of blocks to check /// @return true if ancestor is at most limit blocks lower than descendant, otherwise false function _isAncestor(bytes32 _ancestor, bytes32 _descendant, uint256 _limit) internal view returns (bool) { bytes32 _current = _descendant; /* NB: 200 gas/read, so gas is capped at ~200 * limit */ for (uint256 i = 0; i < _limit; i = i.add(1)) { if (_current == _ancestor) { return true; } _current = previousBlock[_current]; } return false; } /// @notice Marks the new best-known chain tip /// @param _ancestor The digest of the most recent common ancestor /// @param _current The 80-byte header referenced by bestKnownDigest /// @param _new The 80-byte header to mark as the new best /// @param _limit Limit the amount of traversal of the chain /// @return True if successfully updates bestKnownDigest, error otherwise function _markNewHeaviest( bytes32 _ancestor, bytes29 _current, // Header bytes29 _new, // Header uint256 _limit ) internal returns (bool) { require(_limit <= 2016, "Requested limit is greater than 1 difficulty period"); bytes32 _newBestDigest = _new.hash256(); bytes32 _currentBestDigest = _current.hash256(); require(_currentBestDigest == bestKnownDigest, "Passed in best is not best known"); require( previousBlock[_newBestDigest] != bytes32(0), "New best is unknown"); require( _isMostRecentAncestor(_ancestor, bestKnownDigest, _newBestDigest, _limit), "Ancestor must be heaviest common ancestor"); require( _heaviestFromAncestor(_ancestor, _current, _new) == _newBestDigest, "New best hash does not have more work than previous"); bestKnownDigest = _newBestDigest; lastReorgCommonAncestor = _ancestor; uint256 _newDiff = _new.diff(); if (_newDiff != currentEpochDiff) { currentEpochDiff = _newDiff; } emit NewTip( _currentBestDigest, _newBestDigest, _ancestor); return true; } /// @notice Checks if a digest is an ancestor of the current one /// @dev Limit the amount of lookups (and thus gas usage) with _limit /// @param _ancestor The prospective shared ancestor /// @param _left A chain tip /// @param _right A chain tip /// @param _limit The maximum number of blocks to check /// @return true if it is the most recent common ancestor within _limit, false otherwise function _isMostRecentAncestor( bytes32 _ancestor, bytes32 _left, bytes32 _right, uint256 _limit ) internal view returns (bool) { /* NB: sure why not */ if (_ancestor == _left && _ancestor == _right) { return true; } bytes32 _leftCurrent = _left; bytes32 _rightCurrent = _right; bytes32 _leftPrev = _left; bytes32 _rightPrev = _right; for(uint256 i = 0; i < _limit; i = i.add(1)) { if (_leftPrev != _ancestor) { _leftCurrent = _leftPrev; // cheap _leftPrev = previousBlock[_leftPrev]; // expensive } if (_rightPrev != _ancestor) { _rightCurrent = _rightPrev; // cheap _rightPrev = previousBlock[_rightPrev]; // expensive } } if (_leftCurrent == _rightCurrent) {return false;} /* NB: If the same, they're a nearer ancestor */ if (_leftPrev != _rightPrev) {return false;} /* NB: Both must be ancestor */ return true; } /// @notice Decides which header is heaviest from the ancestor /// @dev Does not support reorgs above 2017 blocks (: /// @param _ancestor The prospective shared ancestor /// @param _left A chain tip /// @param _right A chain tip /// @return true if it is the most recent common ancestor within _limit, false otherwise function _heaviestFromAncestor( bytes32 _ancestor, bytes29 _left, bytes29 _right ) internal view returns (bytes32) { uint256 _ancestorHeight = _findHeight(_ancestor); uint256 _leftHeight = _findHeight(_left.hash256()); uint256 _rightHeight = _findHeight(_right.hash256()); require( _leftHeight >= _ancestorHeight && _rightHeight >= _ancestorHeight, "A descendant height is below the ancestor height"); /* NB: we can shortcut if one block is in a new difficulty window and the other isn't */ uint256 _nextPeriodStartHeight = _ancestorHeight.add(2016).sub(_ancestorHeight % 2016); bool _leftInPeriod = _leftHeight < _nextPeriodStartHeight; bool _rightInPeriod = _rightHeight < _nextPeriodStartHeight; /* NB: 1. Left is in a new window, right is in the old window. Left is heavier 2. Right is in a new window, left is in the old window. Right is heavier 3. Both are in the same window, choose the higher one 4. They're in different new windows. Choose the heavier one */ if (!_leftInPeriod && _rightInPeriod) {return _left.hash256();} if (_leftInPeriod && !_rightInPeriod) {return _right.hash256();} if (_leftInPeriod && _rightInPeriod) { return _leftHeight >= _rightHeight ? _left.hash256() : _right.hash256(); } else { // if (!_leftInPeriod && !_rightInPeriod) { if (((_leftHeight % 2016).mul(_left.diff())) < (_rightHeight % 2016).mul(_right.diff())) { return _right.hash256(); } else { return _left.hash256(); } } } } // For unittests contract TestRelay is Relay { /// @notice Gives a starting point for the relay /// @dev We don't check this AT ALL really. Don't use relays with bad genesis /// @param _genesisHeader The starting header /// @param _height The starting height /// @param _periodStart The hash of the first header in the genesis epoch constructor(bytes memory _genesisHeader, uint256 _height, bytes32 _periodStart) Relay(_genesisHeader, _height, _periodStart) public {} function heaviestFromAncestor( bytes32 _ancestor, bytes calldata _left, bytes calldata _right ) external view returns (bytes32) { return _heaviestFromAncestor( _ancestor, _left.ref(0).tryAsHeader(), _right.ref(0).tryAsHeader() ); } function isMostRecentAncestor( bytes32 _ancestor, bytes32 _left, bytes32 _right, uint256 _limit ) external view returns (bool) { return _isMostRecentAncestor(_ancestor, _left, _right, _limit); } }
@notice Adds headers to storage, performs additional validation of retarget @dev Checks the retarget, the heights, and the linkage @param _oldStart The first header in the difficulty period being closed @param _oldEnd The last header in the difficulty period being closed @param _headers A tightly-packed list of 80-byte Bitcoin headers @return True if successfully written, error otherwise If the current known prevEpochDiff doesn't match, and this old period is near the chaintip/ update the stored prevEpochDiff Don't update if this is a deep past epoch
function _addHeadersWithRetarget( bytes29 _oldStart, bytes29 _oldEnd, bytes29 _headers ) internal returns (bool) { uint256 _startHeight = _findHeight(_oldStart.hash256()); uint256 _endHeight = _findHeight(_oldEnd.hash256()); require( _endHeight % 2016 == 2015, "Must provide the last header of the closing difficulty period"); require( _endHeight == _startHeight.add(2015), "Must provide exactly 1 difficulty period"); require( _oldStart.diff() == _oldEnd.diff(), "Period header difficulties do not match"); bytes29 _newStart = _headers.indexHeaderArray(0); uint256 _actualTarget = _newStart.target(); uint256 _expectedTarget = ViewBTC.retargetAlgorithm( _oldStart.target(), _oldStart.time(), _oldEnd.time() ); require( (_actualTarget & _expectedTarget) == _actualTarget, "Invalid retarget provided"); uint256 _oldDiff = _oldStart.diff(); if (prevEpochDiff != _oldDiff && _endHeight > _findHeight(bestKnownDigest).sub(2016)) { prevEpochDiff = _oldDiff; } }
6,484,875
[ 1, 3655, 1607, 358, 2502, 16, 11199, 3312, 3379, 434, 325, 826, 21821, 13074, 326, 325, 826, 16, 326, 24779, 16, 471, 326, 1692, 410, 282, 389, 1673, 1685, 2398, 1021, 1122, 1446, 316, 326, 3122, 21934, 3879, 3832, 4375, 282, 389, 1673, 1638, 9079, 1021, 1142, 1446, 316, 326, 3122, 21934, 3879, 3832, 4375, 282, 389, 2485, 2868, 432, 26066, 715, 17, 2920, 329, 666, 434, 8958, 17, 7229, 24420, 1607, 327, 15604, 1053, 309, 4985, 5941, 16, 555, 3541, 971, 326, 783, 4846, 2807, 14638, 5938, 3302, 1404, 845, 16, 471, 333, 1592, 3879, 353, 13378, 326, 462, 1598, 625, 19, 1089, 326, 4041, 2807, 14638, 5938, 7615, 1404, 1089, 309, 333, 353, 279, 4608, 8854, 7632, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 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, 3121, 1190, 7055, 826, 12, 203, 3639, 1731, 5540, 389, 1673, 1685, 16, 203, 3639, 1731, 5540, 389, 1673, 1638, 16, 203, 3639, 1731, 5540, 389, 2485, 203, 565, 262, 2713, 1135, 261, 6430, 13, 288, 203, 203, 3639, 2254, 5034, 389, 1937, 2686, 273, 389, 4720, 2686, 24899, 1673, 1685, 18, 2816, 5034, 10663, 203, 3639, 2254, 5034, 389, 409, 2686, 273, 389, 4720, 2686, 24899, 1673, 1638, 18, 2816, 5034, 10663, 203, 203, 3639, 2583, 12, 203, 5411, 389, 409, 2686, 738, 12659, 422, 12461, 16, 203, 5411, 315, 10136, 5615, 326, 1142, 1446, 434, 326, 7647, 3122, 21934, 3879, 8863, 203, 3639, 2583, 12, 203, 5411, 389, 409, 2686, 422, 389, 1937, 2686, 18, 1289, 12, 26709, 3631, 203, 5411, 315, 10136, 5615, 8950, 404, 3122, 21934, 3879, 8863, 203, 3639, 2583, 12, 203, 5411, 389, 1673, 1685, 18, 5413, 1435, 422, 389, 1673, 1638, 18, 5413, 9334, 203, 5411, 315, 5027, 1446, 3122, 17551, 606, 741, 486, 845, 8863, 203, 203, 3639, 1731, 5540, 389, 2704, 1685, 273, 389, 2485, 18, 1615, 1864, 1076, 12, 20, 1769, 203, 3639, 2254, 5034, 389, 18672, 2326, 273, 389, 2704, 1685, 18, 3299, 5621, 203, 3639, 2254, 5034, 389, 3825, 2326, 273, 4441, 38, 15988, 18, 1349, 826, 6801, 12, 203, 5411, 389, 1673, 1685, 18, 3299, 9334, 203, 5411, 389, 1673, 1685, 18, 957, 9334, 203, 5411, 389, 1673, 1638, 18, 957, 1435, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 261, 67, 18672, 2326, 473, 389, 2 ]
pragma solidity 0.4.24; contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } /** * @title SchedulerInterface * @dev The base contract that the higher contracts: BaseScheduler, BlockScheduler and TimestampScheduler all inherit from. */ contract SchedulerInterface { function schedule(address _toAddress, bytes _callData, uint[8] _uintArgs) public payable returns (address); function computeEndowment(uint _bounty, uint _fee, uint _callGas, uint _callValue, uint _gasPrice) public view returns (uint); } contract TransactionRequestInterface { // Primary actions function execute() public returns (bool); function cancel() public returns (bool); function claim() public payable returns (bool); // Proxy function function proxy(address recipient, bytes callData) public payable returns (bool); // Data accessors function requestData() public view returns (address[6], bool[3], uint[15], uint8[1]); function callData() public view returns (bytes); // Pull mechanisms for payments. function refundClaimDeposit() public returns (bool); function sendFee() public returns (bool); function sendBounty() public returns (bool); function sendOwnerEther() public returns (bool); function sendOwnerEther(address recipient) public returns (bool); } contract TransactionRequestCore is TransactionRequestInterface { using RequestLib for RequestLib.Request; using RequestScheduleLib for RequestScheduleLib.ExecutionWindow; RequestLib.Request txnRequest; bool private initialized = false; /* * addressArgs[0] - meta.createdBy * addressArgs[1] - meta.owner * addressArgs[2] - paymentData.feeRecipient * addressArgs[3] - txnData.toAddress * * uintArgs[0] - paymentData.fee * uintArgs[1] - paymentData.bounty * uintArgs[2] - schedule.claimWindowSize * uintArgs[3] - schedule.freezePeriod * uintArgs[4] - schedule.reservedWindowSize * uintArgs[5] - schedule.temporalUnit * uintArgs[6] - schedule.windowSize * uintArgs[7] - schedule.windowStart * uintArgs[8] - txnData.callGas * uintArgs[9] - txnData.callValue * uintArgs[10] - txnData.gasPrice * uintArgs[11] - claimData.requiredDeposit */ function initialize( address[4] addressArgs, uint[12] uintArgs, bytes callData ) public payable { require(!initialized); txnRequest.initialize(addressArgs, uintArgs, callData); initialized = true; } /* * Allow receiving ether. This is needed if there is a large increase in * network gas prices. */ function() public payable {} /* * Actions */ function execute() public returns (bool) { return txnRequest.execute(); } function cancel() public returns (bool) { return txnRequest.cancel(); } function claim() public payable returns (bool) { return txnRequest.claim(); } /* * Data accessor functions. */ // Declaring this function `view`, although it creates a compiler warning, is // necessary to return values from it. function requestData() public view returns (address[6], bool[3], uint[15], uint8[1]) { return txnRequest.serialize(); } function callData() public view returns (bytes data) { data = txnRequest.txnData.callData; } /** * @dev Proxy a call from this contract to another contract. * This function is only callable by the scheduler and can only * be called after the execution window ends. One purpose is to * provide a way to transfer assets held by this contract somewhere else. * For example, if this request was used to buy tokens during an ICO, * it would become the owner of the tokens and this function would need * to be called with the encoded data to the token contract to transfer * the assets somewhere else. */ function proxy(address _to, bytes _data) public payable returns (bool success) { require(txnRequest.meta.owner == msg.sender && txnRequest.schedule.isAfterWindow()); /* solium-disable-next-line */ return _to.call.value(msg.value)(_data); } /* * Pull based payment functions. */ function refundClaimDeposit() public returns (bool) { txnRequest.refundClaimDeposit(); } function sendFee() public returns (bool) { return txnRequest.sendFee(); } function sendBounty() public returns (bool) { return txnRequest.sendBounty(); } function sendOwnerEther() public returns (bool) { return txnRequest.sendOwnerEther(); } function sendOwnerEther(address recipient) public returns (bool) { return txnRequest.sendOwnerEther(recipient); } /** Event duplication from RequestLib.sol. This is so * that these events are available on the contracts ABI.*/ event Aborted(uint8 reason); event Cancelled(uint rewardPayment, uint measuredGasConsumption); event Claimed(); event Executed(uint bounty, uint fee, uint measuredGasConsumption); } contract RequestFactoryInterface { event RequestCreated(address request, address indexed owner, int indexed bucket, uint[12] params); function createRequest(address[3] addressArgs, uint[12] uintArgs, bytes callData) public payable returns (address); function createValidatedRequest(address[3] addressArgs, uint[12] uintArgs, bytes callData) public payable returns (address); function validateRequestParams(address[3] addressArgs, uint[12] uintArgs, uint endowment) public view returns (bool[6]); function isKnownRequest(address _address) public view returns (bool); } contract TransactionRecorder { address owner; bool public wasCalled; uint public lastCallValue; address public lastCaller; bytes public lastCallData = ""; uint public lastCallGas; function TransactionRecorder() public { owner = msg.sender; } function() payable public { lastCallGas = gasleft(); lastCallData = msg.data; lastCaller = msg.sender; lastCallValue = msg.value; wasCalled = true; } function __reset__() public { lastCallGas = 0; lastCallData = ""; lastCaller = 0x0; lastCallValue = 0; wasCalled = false; } function kill() public { require(msg.sender == owner); selfdestruct(owner); } } contract Proxy { SchedulerInterface public scheduler; address public receipient; address public scheduledTransaction; address public owner; function Proxy(address _scheduler, address _receipient, uint _payout, uint _gasPrice, uint _delay) public payable { scheduler = SchedulerInterface(_scheduler); receipient = _receipient; owner = msg.sender; scheduledTransaction = scheduler.schedule.value(msg.value)( this, // toAddress "", // callData [ 2000000, // The amount of gas to be sent with the transaction. _payout, // The amount of wei to be sent. 255, // The size of the execution window. block.number + _delay, // The start of the execution window. _gasPrice, // The gasprice for the transaction 12345 wei, // The fee included in the transaction. 224455 wei, // The bounty that awards the executor of the transaction. 20000 wei // The required amount of wei the claimer must send as deposit. ] ); } function () public payable { if (msg.value > 0) { receipient.transfer(msg.value); } } function sendOwnerEther(address _receipient) public { if (msg.sender == owner && _receipient != 0x0) { TransactionRequestInterface(scheduledTransaction).sendOwnerEther(_receipient); } } } /// Super simple token contract that moves funds into the owner account on creation and /// only exposes an API to be used for `test/proxy.js` contract SimpleToken { address public owner; mapping(address => uint) balances; function SimpleToken (uint _initialSupply) public { owner = msg.sender; balances[owner] = _initialSupply; } function transfer (address _to, uint _amount) public returns (bool success) { require(balances[msg.sender] > _amount); balances[msg.sender] -= _amount; balances[_to] += _amount; success = true; } uint public constant rate = 30; function buyTokens() public payable returns (bool success) { require(msg.value > 0); balances[msg.sender] += msg.value * rate; success = true; } function balanceOf (address _who) public view returns (uint balance) { balance = balances[_who]; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // require(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // require(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } /** * @title BaseScheduler * @dev The foundational contract which provides the API for scheduling future transactions on the Alarm Client. */ contract BaseScheduler is SchedulerInterface { // The RequestFactory which produces requests for this scheduler. address public factoryAddress; // The TemporalUnit (Block or Timestamp) for this scheduler. RequestScheduleLib.TemporalUnit public temporalUnit; // The address which will be sent the fee payments. address public feeRecipient; /* * @dev Fallback function to be able to receive ether. This can occur * legitimately when scheduling fails due to a validation error. */ function() public payable {} /// Event that bubbles up the address of new requests made with this scheduler. event NewRequest(address request); /** * @dev Schedules a new TransactionRequest using the 'full' parameters. * @param _toAddress The address destination of the transaction. * @param _callData The bytecode that will be included with the transaction. * @param _uintArgs [0] The callGas of the transaction. * @param _uintArgs [1] The value of ether to be sent with the transaction. * @param _uintArgs [2] The size of the execution window of the transaction. * @param _uintArgs [3] The (block or timestamp) of when the execution window starts. * @param _uintArgs [4] The gasPrice which will be used to execute this transaction. * @param _uintArgs [5] The fee attached to this transaction. * @param _uintArgs [6] The bounty attached to this transaction. * @param _uintArgs [7] The deposit required to claim this transaction. * @return The address of the new TransactionRequest. */ function schedule ( address _toAddress, bytes _callData, uint[8] _uintArgs ) public payable returns (address newRequest) { RequestFactoryInterface factory = RequestFactoryInterface(factoryAddress); uint endowment = computeEndowment( _uintArgs[6], //bounty _uintArgs[5], //fee _uintArgs[0], //callGas _uintArgs[1], //callValue _uintArgs[4] //gasPrice ); require(msg.value >= endowment); if (temporalUnit == RequestScheduleLib.TemporalUnit.Blocks) { newRequest = factory.createValidatedRequest.value(msg.value)( [ msg.sender, // meta.owner feeRecipient, // paymentData.feeRecipient _toAddress // txnData.toAddress ], [ _uintArgs[5], // paymentData.fee _uintArgs[6], // paymentData.bounty 255, // scheduler.claimWindowSize 10, // scheduler.freezePeriod 16, // scheduler.reservedWindowSize uint(temporalUnit), // scheduler.temporalUnit (1: block, 2: timestamp) _uintArgs[2], // scheduler.windowSize _uintArgs[3], // scheduler.windowStart _uintArgs[0], // txnData.callGas _uintArgs[1], // txnData.callValue _uintArgs[4], // txnData.gasPrice _uintArgs[7] // claimData.requiredDeposit ], _callData ); } else if (temporalUnit == RequestScheduleLib.TemporalUnit.Timestamp) { newRequest = factory.createValidatedRequest.value(msg.value)( [ msg.sender, // meta.owner feeRecipient, // paymentData.feeRecipient _toAddress // txnData.toAddress ], [ _uintArgs[5], // paymentData.fee _uintArgs[6], // paymentData.bounty 60 minutes, // scheduler.claimWindowSize 3 minutes, // scheduler.freezePeriod 5 minutes, // scheduler.reservedWindowSize uint(temporalUnit), // scheduler.temporalUnit (1: block, 2: timestamp) _uintArgs[2], // scheduler.windowSize _uintArgs[3], // scheduler.windowStart _uintArgs[0], // txnData.callGas _uintArgs[1], // txnData.callValue _uintArgs[4], // txnData.gasPrice _uintArgs[7] // claimData.requiredDeposit ], _callData ); } else { // unsupported temporal unit revert(); } require(newRequest != 0x0); emit NewRequest(newRequest); return newRequest; } function computeEndowment( uint _bounty, uint _fee, uint _callGas, uint _callValue, uint _gasPrice ) public view returns (uint) { return PaymentLib.computeEndowment( _bounty, _fee, _callGas, _callValue, _gasPrice, RequestLib.getEXECUTION_GAS_OVERHEAD() ); } } /** * @title BlockScheduler * @dev Top-level contract that exposes the API to the Ethereum Alarm Clock service and passes in blocks as temporal unit. */ contract BlockScheduler is BaseScheduler { /** * @dev Constructor * @param _factoryAddress Address of the RequestFactory which creates requests for this scheduler. */ constructor(address _factoryAddress, address _feeRecipient) public { require(_factoryAddress != 0x0); // Default temporal unit is block number. temporalUnit = RequestScheduleLib.TemporalUnit.Blocks; // Sets the factoryAddress variable found in BaseScheduler contract. factoryAddress = _factoryAddress; // Sets the fee recipient for these schedulers. feeRecipient = _feeRecipient; } } /** * @title TimestampScheduler * @dev Top-level contract that exposes the API to the Ethereum Alarm Clock service and passes in timestamp as temporal unit. */ contract TimestampScheduler is BaseScheduler { /** * @dev Constructor * @param _factoryAddress Address of the RequestFactory which creates requests for this scheduler. */ constructor(address _factoryAddress, address _feeRecipient) public { require(_factoryAddress != 0x0); // Default temporal unit is timestamp. temporalUnit = RequestScheduleLib.TemporalUnit.Timestamp; // Sets the factoryAddress variable found in BaseScheduler contract. factoryAddress = _factoryAddress; // Sets the fee recipient for these schedulers. feeRecipient = _feeRecipient; } } /// Truffle-specific contract (Not a part of the EAC) contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) { _; } } function Migrations() public { owner = msg.sender; } function setCompleted(uint completed) restricted public { last_completed_migration = completed; } function upgrade(address new_address) restricted public { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } /** * @title ExecutionLib * @dev Contains the logic for executing a scheduled transaction. */ library ExecutionLib { struct ExecutionData { address toAddress; /// The destination of the transaction. bytes callData; /// The bytecode that will be sent with the transaction. uint callValue; /// The wei value that will be sent with the transaction. uint callGas; /// The amount of gas to be sent with the transaction. uint gasPrice; /// The gasPrice that should be set for the transaction. } /** * @dev Send the transaction according to the parameters outlined in ExecutionData. * @param self The ExecutionData object. */ function sendTransaction(ExecutionData storage self) internal returns (bool) { /// Should never actually reach this require check, but here in case. require(self.gasPrice <= tx.gasprice); /* solium-disable security/no-call-value */ return self.toAddress.call.value(self.callValue).gas(self.callGas)(self.callData); } /** * Returns the maximum possible gas consumption that a transaction request * may consume. The EXTRA_GAS value represents the overhead involved in * request execution. */ function CALL_GAS_CEILING(uint EXTRA_GAS) internal view returns (uint) { return block.gaslimit - EXTRA_GAS; } /* * @dev Validation: ensure that the callGas is not above the total possible gas * for a call. */ function validateCallGas(uint callGas, uint EXTRA_GAS) internal view returns (bool) { return callGas < CALL_GAS_CEILING(EXTRA_GAS); } /* * @dev Validation: ensure that the toAddress is not set to the empty address. */ function validateToAddress(address toAddress) internal pure returns (bool) { return toAddress != 0x0; } } library MathLib { uint constant INT_MAX = 57896044618658097711785492504343953926634992332820282019728792003956564819967; // 2**255 - 1 /* * Subtracts b from a in a manner such that zero is returned when an * underflow condition is met. */ // function flooredSub(uint a, uint b) returns (uint) { // if (b >= a) { // return 0; // } else { // return a - b; // } // } // /* // * Adds b to a in a manner that throws an exception when overflow // * conditions are met. // */ // function safeAdd(uint a, uint b) returns (uint) { // if (a + b >= a) { // return a + b; // } else { // throw; // } // } // /* // * Multiplies a by b in a manner that throws an exception when overflow // * conditions are met. // */ // function safeMultiply(uint a, uint b) returns (uint) { // var result = a * b; // if (b == 0 || result / b == a) { // return a * b; // } else { // throw; // } // } /* * Return the larger of a or b. Returns a if a == b. */ function max(uint a, uint b) public pure returns (uint) { if (a >= b) { return a; } else { return b; } } /* * Return the larger of a or b. Returns a if a == b. */ function min(uint a, uint b) public pure returns (uint) { if (a <= b) { return a; } else { return b; } } /* * Returns a represented as a signed integer in a manner that throw an * exception if casting to signed integer would result in a negative * number. */ function safeCastSigned(uint a) public pure returns (int) { assert(a <= INT_MAX); return int(a); } } /** * @title RequestMetaLib * @dev Small library holding all the metadata about a TransactionRequest. */ library RequestMetaLib { struct RequestMeta { address owner; /// The address that created this request. address createdBy; /// The address of the RequestFactory which created this request. bool isCancelled; /// Was the TransactionRequest cancelled? bool wasCalled; /// Was the TransactionRequest called? bool wasSuccessful; /// Was the return value from the TransactionRequest execution successful? } } library RequestLib { using ClaimLib for ClaimLib.ClaimData; using ExecutionLib for ExecutionLib.ExecutionData; using PaymentLib for PaymentLib.PaymentData; using RequestMetaLib for RequestMetaLib.RequestMeta; using RequestScheduleLib for RequestScheduleLib.ExecutionWindow; using SafeMath for uint; struct Request { ExecutionLib.ExecutionData txnData; RequestMetaLib.RequestMeta meta; PaymentLib.PaymentData paymentData; ClaimLib.ClaimData claimData; RequestScheduleLib.ExecutionWindow schedule; } enum AbortReason { WasCancelled, //0 AlreadyCalled, //1 BeforeCallWindow, //2 AfterCallWindow, //3 ReservedForClaimer, //4 InsufficientGas, //5 TooLowGasPrice //6 } event Aborted(uint8 reason); event Cancelled(uint rewardPayment, uint measuredGasConsumption); event Claimed(); event Executed(uint bounty, uint fee, uint measuredGasConsumption); /** * @dev Validate the initialization parameters of a transaction request. */ function validate( address[4] _addressArgs, uint[12] _uintArgs, uint _endowment ) public view returns (bool[6] isValid) { // The order of these errors matters as it determines which // ValidationError event codes are logged when validation fails. isValid[0] = PaymentLib.validateEndowment( _endowment, _uintArgs[1], //bounty _uintArgs[0], //fee _uintArgs[8], //callGas _uintArgs[9], //callValue _uintArgs[10], //gasPrice EXECUTION_GAS_OVERHEAD ); isValid[1] = RequestScheduleLib.validateReservedWindowSize( _uintArgs[4], //reservedWindowSize _uintArgs[6] //windowSize ); isValid[2] = RequestScheduleLib.validateTemporalUnit(_uintArgs[5]); isValid[3] = RequestScheduleLib.validateWindowStart( RequestScheduleLib.TemporalUnit(MathLib.min(_uintArgs[5], 2)), _uintArgs[3], //freezePeriod _uintArgs[7] //windowStart ); isValid[4] = ExecutionLib.validateCallGas( _uintArgs[8], //callGas EXECUTION_GAS_OVERHEAD ); isValid[5] = ExecutionLib.validateToAddress(_addressArgs[3]); return isValid; } /** * @dev Initialize a new Request. */ function initialize( Request storage self, address[4] _addressArgs, uint[12] _uintArgs, bytes _callData ) public returns (bool) { address[6] memory addressValues = [ 0x0, // self.claimData.claimedBy _addressArgs[0], // self.meta.createdBy _addressArgs[1], // self.meta.owner _addressArgs[2], // self.paymentData.feeRecipient 0x0, // self.paymentData.bountyBenefactor _addressArgs[3] // self.txnData.toAddress ]; bool[3] memory boolValues = [false, false, false]; uint[15] memory uintValues = [ 0, // self.claimData.claimDeposit _uintArgs[0], // self.paymentData.fee 0, // self.paymentData.feeOwed _uintArgs[1], // self.paymentData.bounty 0, // self.paymentData.bountyOwed _uintArgs[2], // self.schedule.claimWindowSize _uintArgs[3], // self.schedule.freezePeriod _uintArgs[4], // self.schedule.reservedWindowSize _uintArgs[5], // self.schedule.temporalUnit _uintArgs[6], // self.schedule.windowSize _uintArgs[7], // self.schedule.windowStart _uintArgs[8], // self.txnData.callGas _uintArgs[9], // self.txnData.callValue _uintArgs[10], // self.txnData.gasPrice _uintArgs[11] // self.claimData.requiredDeposit ]; uint8[1] memory uint8Values = [ 0 ]; require(deserialize(self, addressValues, boolValues, uintValues, uint8Values, _callData)); return true; } function serialize(Request storage self) internal view returns(address[6], bool[3], uint[15], uint8[1]) { address[6] memory addressValues = [ self.claimData.claimedBy, self.meta.createdBy, self.meta.owner, self.paymentData.feeRecipient, self.paymentData.bountyBenefactor, self.txnData.toAddress ]; bool[3] memory boolValues = [ self.meta.isCancelled, self.meta.wasCalled, self.meta.wasSuccessful ]; uint[15] memory uintValues = [ self.claimData.claimDeposit, self.paymentData.fee, self.paymentData.feeOwed, self.paymentData.bounty, self.paymentData.bountyOwed, self.schedule.claimWindowSize, self.schedule.freezePeriod, self.schedule.reservedWindowSize, uint(self.schedule.temporalUnit), self.schedule.windowSize, self.schedule.windowStart, self.txnData.callGas, self.txnData.callValue, self.txnData.gasPrice, self.claimData.requiredDeposit ]; uint8[1] memory uint8Values = [ self.claimData.paymentModifier ]; return (addressValues, boolValues, uintValues, uint8Values); } /** * @dev Populates a Request object from the full output of `serialize`. * * Parameter order is alphabetical by type, then namespace, then name. */ function deserialize( Request storage self, address[6] _addressValues, bool[3] _boolValues, uint[15] _uintValues, uint8[1] _uint8Values, bytes _callData ) internal returns (bool) { // callData is special. self.txnData.callData = _callData; // Address values self.claimData.claimedBy = _addressValues[0]; self.meta.createdBy = _addressValues[1]; self.meta.owner = _addressValues[2]; self.paymentData.feeRecipient = _addressValues[3]; self.paymentData.bountyBenefactor = _addressValues[4]; self.txnData.toAddress = _addressValues[5]; // Boolean values self.meta.isCancelled = _boolValues[0]; self.meta.wasCalled = _boolValues[1]; self.meta.wasSuccessful = _boolValues[2]; // UInt values self.claimData.claimDeposit = _uintValues[0]; self.paymentData.fee = _uintValues[1]; self.paymentData.feeOwed = _uintValues[2]; self.paymentData.bounty = _uintValues[3]; self.paymentData.bountyOwed = _uintValues[4]; self.schedule.claimWindowSize = _uintValues[5]; self.schedule.freezePeriod = _uintValues[6]; self.schedule.reservedWindowSize = _uintValues[7]; self.schedule.temporalUnit = RequestScheduleLib.TemporalUnit(_uintValues[8]); self.schedule.windowSize = _uintValues[9]; self.schedule.windowStart = _uintValues[10]; self.txnData.callGas = _uintValues[11]; self.txnData.callValue = _uintValues[12]; self.txnData.gasPrice = _uintValues[13]; self.claimData.requiredDeposit = _uintValues[14]; // Uint8 values self.claimData.paymentModifier = _uint8Values[0]; return true; } function execute(Request storage self) internal returns (bool) { /* * Execute the TransactionRequest * * +---------------------+ * | Phase 1: Validation | * +---------------------+ * * Must pass all of the following checks: * * 1. Not already called. * 2. Not cancelled. * 3. Not before the execution window. * 4. Not after the execution window. * 5. if (claimedBy == 0x0 or msg.sender == claimedBy): * - windowStart <= block.number * - block.number <= windowStart + windowSize * else if (msg.sender != claimedBy): * - windowStart + reservedWindowSize <= block.number * - block.number <= windowStart + windowSize * else: * - throw (should be impossible) * * 6. gasleft() == callGas * 7. tx.gasprice >= txnData.gasPrice * * +--------------------+ * | Phase 2: Execution | * +--------------------+ * * 1. Mark as called (must be before actual execution to prevent * re-entrance) * 2. Send Transaction and record success or failure. * * +---------------------+ * | Phase 3: Accounting | * +---------------------+ * * 1. Calculate and send fee amount. * 2. Calculate and send bounty amount. * 3. Send remaining ether back to owner. * */ // Record the gas at the beginning of the transaction so we can // calculate how much has been used later. uint startGas = gasleft(); // +----------------------+ // | Begin: Authorization | // +----------------------+ if (gasleft() < requiredExecutionGas(self).sub(PRE_EXECUTION_GAS)) { emit Aborted(uint8(AbortReason.InsufficientGas)); return false; } else if (self.meta.wasCalled) { emit Aborted(uint8(AbortReason.AlreadyCalled)); return false; } else if (self.meta.isCancelled) { emit Aborted(uint8(AbortReason.WasCancelled)); return false; } else if (self.schedule.isBeforeWindow()) { emit Aborted(uint8(AbortReason.BeforeCallWindow)); return false; } else if (self.schedule.isAfterWindow()) { emit Aborted(uint8(AbortReason.AfterCallWindow)); return false; } else if (self.claimData.isClaimed() && msg.sender != self.claimData.claimedBy && self.schedule.inReservedWindow()) { emit Aborted(uint8(AbortReason.ReservedForClaimer)); return false; } else if (self.txnData.gasPrice > tx.gasprice) { emit Aborted(uint8(AbortReason.TooLowGasPrice)); return false; } // +--------------------+ // | End: Authorization | // +--------------------+ // +------------------+ // | Begin: Execution | // +------------------+ // Mark as being called before sending transaction to prevent re-entrance. self.meta.wasCalled = true; // Send the transaction... // The transaction is allowed to fail and the executing agent will still get the bounty. // `.sendTransaction()` will return false on a failed exeuction. self.meta.wasSuccessful = self.txnData.sendTransaction(); // +----------------+ // | End: Execution | // +----------------+ // +-------------------+ // | Begin: Accounting | // +-------------------+ // Compute the fee amount if (self.paymentData.hasFeeRecipient()) { self.paymentData.feeOwed = self.paymentData.getFee() .add(self.paymentData.feeOwed); } // Record this locally so that we can log it later. // `.sendFee()` below will change `self.paymentData.feeOwed` to 0 to prevent re-entrance. uint totalFeePayment = self.paymentData.feeOwed; // Send the fee. This transaction may also fail but can be called again after // execution. self.paymentData.sendFee(); // Compute the bounty amount. self.paymentData.bountyBenefactor = msg.sender; if (self.claimData.isClaimed()) { // If the transaction request was claimed, we add the deposit to the bounty whether // or not the same agent who claimed is executing. self.paymentData.bountyOwed = self.claimData.claimDeposit .add(self.paymentData.bountyOwed); // To prevent re-entrance we zero out the claim deposit since it is now accounted for // in the bounty value. self.claimData.claimDeposit = 0; // Depending on when the transaction request was claimed, we apply the modifier to the // bounty payment and add it to the bounty already owed. self.paymentData.bountyOwed = self.paymentData.getBountyWithModifier(self.claimData.paymentModifier) .add(self.paymentData.bountyOwed); } else { // Not claimed. Just add the full bounty. self.paymentData.bountyOwed = self.paymentData.getBounty().add(self.paymentData.bountyOwed); } // Take down the amount of gas used so far in execution to compensate the executing agent. uint measuredGasConsumption = startGas.sub(gasleft()).add(EXECUTE_EXTRA_GAS); // // +----------------------------------------------------------------------+ // // | NOTE: All code after this must be accounted for by EXECUTE_EXTRA_GAS | // // +----------------------------------------------------------------------+ // Add the gas reimbursment amount to the bounty. self.paymentData.bountyOwed = measuredGasConsumption .mul(self.txnData.gasPrice) .add(self.paymentData.bountyOwed); // Log the bounty and fee. Otherwise it is non-trivial to figure // out how much was payed. emit Executed(self.paymentData.bountyOwed, totalFeePayment, measuredGasConsumption); // Attempt to send the bounty. as with `.sendFee()` it may fail and need to be caled after execution. self.paymentData.sendBounty(); // If any ether is left, send it back to the owner of the transaction request. _sendOwnerEther(self, self.meta.owner); // +-----------------+ // | End: Accounting | // +-----------------+ // Successful return true; } // This is the amount of gas that it takes to enter from the // `TransactionRequest.execute()` contract into the `RequestLib.execute()` // method at the point where the gas check happens. uint public constant PRE_EXECUTION_GAS = 25000; // TODO is this number still accurate? /* * The amount of gas needed to complete the execute method after * the transaction has been sent. */ uint public constant EXECUTION_GAS_OVERHEAD = 180000; // TODO check accuracy of this number /* * The amount of gas used by the portion of the `execute` function * that cannot be accounted for via gas tracking. */ uint public constant EXECUTE_EXTRA_GAS = 90000; // again, check for accuracy... Doubled this from Piper's original - Logan /* * Constant value to account for the gas usage that cannot be accounted * for using gas-tracking within the `cancel` function. */ uint public constant CANCEL_EXTRA_GAS = 85000; // Check accuracy function getEXECUTION_GAS_OVERHEAD() public pure returns (uint) { return EXECUTION_GAS_OVERHEAD; } function requiredExecutionGas(Request storage self) public view returns (uint requiredGas) { requiredGas = self.txnData.callGas.add(EXECUTION_GAS_OVERHEAD); } /* * @dev Performs the checks to see if a request can be cancelled. * Must satisfy the following conditions. * * 1. Not Cancelled * 2. either: * * not wasCalled && afterExecutionWindow * * not claimed && beforeFreezeWindow && msg.sender == owner */ function isCancellable(Request storage self) public view returns (bool) { if (self.meta.isCancelled) { // already cancelled! return false; } else if (!self.meta.wasCalled && self.schedule.isAfterWindow()) { // not called but after the window return true; } else if (!self.claimData.isClaimed() && self.schedule.isBeforeFreeze() && msg.sender == self.meta.owner) { // not claimed and before freezePeriod and owner is cancelling return true; } else { // otherwise cannot cancel return false; } } /* * Cancel the transaction request, attempting to send all appropriate * refunds. To incentivise cancellation by other parties, a small reward * payment is issued to the party that cancels the request if they are not * the owner. */ function cancel(Request storage self) public returns (bool) { uint startGas = gasleft(); uint rewardPayment; uint measuredGasConsumption; // Checks if this transactionRequest can be cancelled. require(isCancellable(self)); // Set here to prevent re-entrance attacks. self.meta.isCancelled = true; // Refund the claim deposit (if there is one) require(self.claimData.refundDeposit()); // Send a reward to the cancelling agent if they are not the owner. // This is to incentivize the cancelling of expired transaction requests. // This also guarantees that it is being cancelled after the call window // since the `isCancellable()` function checks this. if (msg.sender != self.meta.owner) { // Create the rewardBenefactor address rewardBenefactor = msg.sender; // Create the rewardOwed variable, it is one-hundredth // of the bounty. uint rewardOwed = self.paymentData.bountyOwed .add(self.paymentData.bounty.div(100)); // Calculate the amount of gas cancelling agent used in this transaction. measuredGasConsumption = startGas .sub(gasleft()) .add(CANCEL_EXTRA_GAS); // Add their gas fees to the reward.W rewardOwed = measuredGasConsumption .mul(tx.gasprice) .add(rewardOwed); // Take note of the rewardPayment to log it. rewardPayment = rewardOwed; // Transfers the rewardPayment. if (rewardOwed > 0) { self.paymentData.bountyOwed = 0; rewardBenefactor.transfer(rewardOwed); } } // Log it! emit Cancelled(rewardPayment, measuredGasConsumption); // Send the remaining ether to the owner. return sendOwnerEther(self); } /* * @dev Performs some checks to verify that a transaction request is claimable. * @param self The Request object. */ function isClaimable(Request storage self) internal view returns (bool) { // Require not claimed and not cancelled. require(!self.claimData.isClaimed()); require(!self.meta.isCancelled); // Require that it's in the claim window and the value sent is over the required deposit. require(self.schedule.inClaimWindow()); require(msg.value >= self.claimData.requiredDeposit); return true; } /* * @dev Claims the request. * @param self The Request object. * Payable because it requires the sender to send enough ether to cover the claimDeposit. */ function claim(Request storage self) internal returns (bool claimed) { require(isClaimable(self)); emit Claimed(); return self.claimData.claim(self.schedule.computePaymentModifier()); } /* * @dev Refund claimer deposit. */ function refundClaimDeposit(Request storage self) public returns (bool) { require(self.meta.isCancelled || self.schedule.isAfterWindow()); return self.claimData.refundDeposit(); } /* * Send fee. Wrapper over the real function that perform an extra * check to see if it's after the execution window (and thus the first transaction failed) */ function sendFee(Request storage self) public returns (bool) { if (self.schedule.isAfterWindow()) { return self.paymentData.sendFee(); } return false; } /* * Send bounty. Wrapper over the real function that performs an extra * check to see if it's after execution window (and thus the first transaction failed) */ function sendBounty(Request storage self) public returns (bool) { /// check wasCalled if (self.schedule.isAfterWindow()) { return self.paymentData.sendBounty(); } return false; } function canSendOwnerEther(Request storage self) public view returns(bool) { return self.meta.isCancelled || self.schedule.isAfterWindow() || self.meta.wasCalled; } /** * Send owner ether. Wrapper over the real function that performs an extra * check to see if it's after execution window (and thus the first transaction failed) */ function sendOwnerEther(Request storage self, address recipient) public returns (bool) { require(recipient != 0x0); if(canSendOwnerEther(self) && msg.sender == self.meta.owner) { return _sendOwnerEther(self, recipient); } return false; } /** * Send owner ether. Wrapper over the real function that performs an extra * check to see if it's after execution window (and thus the first transaction failed) */ function sendOwnerEther(Request storage self) public returns (bool) { if(canSendOwnerEther(self)) { return _sendOwnerEther(self, self.meta.owner); } return false; } function _sendOwnerEther(Request storage self, address recipient) private returns (bool) { // Note! This does not do any checks since it is used in the execute function. // The public version of the function should be used for checks and in the cancel function. uint ownerRefund = address(this).balance .sub(self.claimData.claimDeposit) .sub(self.paymentData.bountyOwed) .sub(self.paymentData.feeOwed); /* solium-disable security/no-send */ return recipient.send(ownerRefund); } } /** * @title RequestScheduleLib * @dev Library containing the logic for request scheduling. */ library RequestScheduleLib { using SafeMath for uint; /** * The manner in which this schedule specifies time. * * Null: present to require this value be explicitely specified * Blocks: execution schedule determined by block.number * Timestamp: execution schedule determined by block.timestamp */ enum TemporalUnit { Null, // 0 Blocks, // 1 Timestamp // 2 } struct ExecutionWindow { TemporalUnit temporalUnit; /// The type of unit used to measure time. uint windowStart; /// The starting point in temporal units from which the transaction can be executed. uint windowSize; /// The length in temporal units of the execution time period. uint freezePeriod; /// The length in temporal units before the windowStart where no activity is allowed. uint reservedWindowSize; /// The length in temporal units at the beginning of the executionWindow in which only the claim address can execute. uint claimWindowSize; /// The length in temporal units before the freezeperiod in which an address can claim the execution. } /** * @dev Get the `now` represented in the temporal units assigned to this request. * @param self The ExecutionWindow object. * @return The unsigned integer representation of `now` in appropiate temporal units. */ function getNow(ExecutionWindow storage self) public view returns (uint) { return _getNow(self.temporalUnit); } /** * @dev Internal function to return the `now` based on the appropiate temporal units. * @param _temporalUnit The assigned TemporalUnit to this transaction. */ function _getNow(TemporalUnit _temporalUnit) internal view returns (uint) { if (_temporalUnit == TemporalUnit.Timestamp) { return block.timestamp; } if (_temporalUnit == TemporalUnit.Blocks) { return block.number; } /// Only reaches here if the unit is unset, unspecified or unsupported. revert(); } /** * @dev The modifier that will be applied to the bounty value depending * on when a call was claimed. */ function computePaymentModifier(ExecutionWindow storage self) internal view returns (uint8) { uint paymentModifier = (getNow(self).sub(firstClaimBlock(self))) .mul(100) .div(self.claimWindowSize); assert(paymentModifier <= 100); return uint8(paymentModifier); } /* * Helper: computes the end of the execution window. */ function windowEnd(ExecutionWindow storage self) internal view returns (uint) { return self.windowStart.add(self.windowSize); } /* * Helper: computes the end of the reserved portion of the execution * window. */ function reservedWindowEnd(ExecutionWindow storage self) internal view returns (uint) { return self.windowStart.add(self.reservedWindowSize); } /* * Helper: computes the time when the request will be frozen until execution. */ function freezeStart(ExecutionWindow storage self) internal view returns (uint) { return self.windowStart.sub(self.freezePeriod); } /* * Helper: computes the time when the request will be frozen until execution. */ function firstClaimBlock(ExecutionWindow storage self) internal view returns (uint) { return freezeStart(self).sub(self.claimWindowSize); } /* * Helper: Returns boolean if we are before the execution window. */ function isBeforeWindow(ExecutionWindow storage self) internal view returns (bool) { return getNow(self) < self.windowStart; } /* * Helper: Returns boolean if we are after the execution window. */ function isAfterWindow(ExecutionWindow storage self) internal view returns (bool) { return getNow(self) > windowEnd(self); } /* * Helper: Returns boolean if we are inside the execution window. */ function inWindow(ExecutionWindow storage self) internal view returns (bool) { return self.windowStart <= getNow(self) && getNow(self) < windowEnd(self); } /* * Helper: Returns boolean if we are inside the reserved portion of the * execution window. */ function inReservedWindow(ExecutionWindow storage self) internal view returns (bool) { return self.windowStart <= getNow(self) && getNow(self) < reservedWindowEnd(self); } /* * @dev Helper: Returns boolean if we are inside the claim window. */ function inClaimWindow(ExecutionWindow storage self) internal view returns (bool) { /// Checks that the firstClaimBlock is in the past or now. /// Checks that now is before the start of the freezePeriod. return firstClaimBlock(self) <= getNow(self) && getNow(self) < freezeStart(self); } /* * Helper: Returns boolean if we are before the freeze period. */ function isBeforeFreeze(ExecutionWindow storage self) internal view returns (bool) { return getNow(self) < freezeStart(self); } /* * Helper: Returns boolean if we are before the claim window. */ function isBeforeClaimWindow(ExecutionWindow storage self) internal view returns (bool) { return getNow(self) < firstClaimBlock(self); } ///--------------- /// VALIDATION ///--------------- /** * @dev Validation: Ensure that the reservedWindowSize is less than or equal to the windowSize. * @param _reservedWindowSize The size of the reserved window. * @param _windowSize The size of the execution window. * @return True if the reservedWindowSize is within the windowSize. */ function validateReservedWindowSize(uint _reservedWindowSize, uint _windowSize) public pure returns (bool) { return _reservedWindowSize <= _windowSize; } /** * @dev Validation: Ensure that the startWindow is at least freezePeriod amount of time in the future. * @param _temporalUnit The temporalUnit of this request. * @param _freezePeriod The freezePeriod in temporal units. * @param _windowStart The time in the future which represents the start of the execution window. * @return True if the windowStart is at least freezePeriod amount of time in the future. */ function validateWindowStart(TemporalUnit _temporalUnit, uint _freezePeriod, uint _windowStart) public view returns (bool) { return _getNow(_temporalUnit).add(_freezePeriod) <= _windowStart; } /* * Validation: ensure that the temporal unit passed in is constrained to 0 or 1 */ function validateTemporalUnit(uint _temporalUnitAsUInt) public pure returns (bool) { return (_temporalUnitAsUInt != uint(TemporalUnit.Null) && (_temporalUnitAsUInt == uint(TemporalUnit.Blocks) || _temporalUnitAsUInt == uint(TemporalUnit.Timestamp)) ); } } library ClaimLib { struct ClaimData { address claimedBy; // The address that has claimed the txRequest. uint claimDeposit; // The deposit amount that was put down by the claimer. uint requiredDeposit; // The required deposit to claim the txRequest. uint8 paymentModifier; // An integer constrained between 0-100 that will be applied to the // request payment as a percentage. } /* * @dev Mark the request as being claimed. * @param self The ClaimData that is being accessed. * @param paymentModifier The payment modifier. */ function claim( ClaimData storage self, uint8 _paymentModifier ) internal returns (bool) { self.claimedBy = msg.sender; self.claimDeposit = msg.value; self.paymentModifier = _paymentModifier; return true; } /* * Helper: returns whether this request is claimed. */ function isClaimed(ClaimData storage self) internal view returns (bool) { return self.claimedBy != 0x0; } /* * @dev Refund the claim deposit to claimer. * @param self The Request.ClaimData * Called in RequestLib's `cancel()` and `refundClaimDeposit()` */ function refundDeposit(ClaimData storage self) internal returns (bool) { // Check that the claim deposit is non-zero. if (self.claimDeposit > 0) { uint depositAmount; depositAmount = self.claimDeposit; self.claimDeposit = 0; /* solium-disable security/no-send */ return self.claimedBy.send(depositAmount); } return true; } } /** * Library containing the functionality for the bounty and fee payments. * - Bounty payments are the reward paid to the executing agent of transaction * requests. * - Fee payments are the cost of using a Scheduler to make transactions. It is * a way for developers to monetize their work on the EAC. */ library PaymentLib { using SafeMath for uint; struct PaymentData { uint bounty; /// The amount in wei to be paid to the executing agent of the TransactionRequest. address bountyBenefactor; /// The address that the bounty will be sent to. uint bountyOwed; /// The amount that is owed to the bountyBenefactor. uint fee; /// The amount in wei that will be paid to the FEE_RECIPIENT address. address feeRecipient; /// The address that the fee will be sent to. uint feeOwed; /// The amount that is owed to the feeRecipient. } ///--------------- /// GETTERS ///--------------- /** * @dev Getter function that returns true if a request has a benefactor. */ function hasFeeRecipient(PaymentData storage self) internal view returns (bool) { return self.feeRecipient != 0x0; } /** * @dev Computes the amount to send to the feeRecipient. */ function getFee(PaymentData storage self) internal view returns (uint) { return self.fee; } /** * @dev Computes the amount to send to the agent that executed the request. */ function getBounty(PaymentData storage self) internal view returns (uint) { return self.bounty; } /** * @dev Computes the amount to send to the address that fulfilled the request * with an additional modifier. This is used when the call was claimed. */ function getBountyWithModifier(PaymentData storage self, uint8 _paymentModifier) internal view returns (uint) { return getBounty(self).mul(_paymentModifier).div(100); } ///--------------- /// SENDERS ///--------------- /** * @dev Send the feeOwed amount to the feeRecipient. * Note: The send is allowed to fail. */ function sendFee(PaymentData storage self) internal returns (bool) { uint feeAmount = self.feeOwed; if (feeAmount > 0) { // re-entrance protection. self.feeOwed = 0; /* solium-disable security/no-send */ return self.feeRecipient.send(feeAmount); } return true; } /** * @dev Send the bountyOwed amount to the bountyBenefactor. * Note: The send is allowed to fail. */ function sendBounty(PaymentData storage self) internal returns (bool) { uint bountyAmount = self.bountyOwed; if (bountyAmount > 0) { // re-entrance protection. self.bountyOwed = 0; return self.bountyBenefactor.send(bountyAmount); } return true; } ///--------------- /// Endowment ///--------------- /** * @dev Compute the endowment value for the given TransactionRequest parameters. * See request_factory.rst in docs folder under Check #1 for more information about * this calculation. */ function computeEndowment( uint _bounty, uint _fee, uint _callGas, uint _callValue, uint _gasPrice, uint _gasOverhead ) public pure returns (uint) { return _bounty .add(_fee) .add(_callGas.mul(_gasPrice)) .add(_gasOverhead.mul(_gasPrice)) .add(_callValue); } /* * Validation: ensure that the request endowment is sufficient to cover. * - bounty * - fee * - gasReimbursment * - callValue */ function validateEndowment(uint _endowment, uint _bounty, uint _fee, uint _callGas, uint _callValue, uint _gasPrice, uint _gasOverhead) public pure returns (bool) { return _endowment >= computeEndowment( _bounty, _fee, _callGas, _callValue, _gasPrice, _gasOverhead ); } } /** * @title IterTools * @dev Utility library that iterates through a boolean array of length 6. */ library IterTools { /* * @dev Return true if all of the values in the boolean array are true. * @param _values A boolean array of length 6. * @return True if all values are true, False if _any_ are false. */ function all(bool[6] _values) public pure returns (bool) { for (uint i = 0; i < _values.length; i++) { if (!_values[i]) { return false; } } return true; } } /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //solhint-disable max-line-length //solhint-disable no-inline-assembly contract CloneFactory { event CloneCreated(address indexed target, address clone); function createClone(address target) internal returns (address result) { bytes memory clone = hex"600034603b57603080600f833981f36000368180378080368173bebebebebebebebebebebebebebebebebebebebe5af43d82803e15602c573d90f35b3d90fd"; bytes20 targetBytes = bytes20(target); for (uint i = 0; i < 20; i++) { clone[26 + i] = targetBytes[i]; } assembly { let len := mload(clone) let data := add(clone, 0x20) result := create(0, data, len) } } } /// Example of using the Scheduler from a smart contract to delay a payment. contract DelayedPayment { SchedulerInterface public scheduler; address recipient; address owner; address public payment; uint lockedUntil; uint value; uint twentyGwei = 20000000000 wei; constructor( address _scheduler, uint _numBlocks, address _recipient, uint _value ) public payable { scheduler = SchedulerInterface(_scheduler); lockedUntil = block.number + _numBlocks; recipient = _recipient; owner = msg.sender; value = _value; uint endowment = scheduler.computeEndowment( twentyGwei, twentyGwei, 200000, 0, twentyGwei ); payment = scheduler.schedule.value(endowment)( // 0.1 ether is to pay for gas, bounty and fee this, // send to self "", // and trigger fallback function [ 200000, // The amount of gas to be sent with the transaction. 0, // The amount of wei to be sent. 255, // The size of the execution window. lockedUntil, // The start of the execution window. twentyGwei, // The gasprice for the transaction (aka 20 gwei) twentyGwei, // The fee included in the transaction. twentyGwei, // The bounty that awards the executor of the transaction. twentyGwei * 2 // The required amount of wei the claimer must send as deposit. ] ); assert(address(this).balance >= value); } function () public payable { if (msg.value > 0) { //this handles recieving remaining funds sent while scheduling (0.1 ether) return; } else if (address(this).balance > 0) { payout(); } else { revert(); } } function payout() public returns (bool) { require(block.number >= lockedUntil); recipient.transfer(value); return true; } function collectRemaining() public returns (bool) { owner.transfer(address(this).balance); } } /// Example of using the Scheduler from a smart contract to delay a payment. contract RecurringPayment { SchedulerInterface public scheduler; uint paymentInterval; uint paymentValue; uint lockedUntil; address recipient; address public currentScheduledTransaction; event PaymentScheduled(address indexed scheduledTransaction, address recipient, uint value); event PaymentExecuted(address indexed scheduledTransaction, address recipient, uint value); function RecurringPayment( address _scheduler, uint _paymentInterval, uint _paymentValue, address _recipient ) public payable { scheduler = SchedulerInterface(_scheduler); paymentInterval = _paymentInterval; recipient = _recipient; paymentValue = _paymentValue; schedule(); } function () public payable { if (msg.value > 0) { //this handles recieving remaining funds sent while scheduling (0.1 ether) return; } process(); } function process() public returns (bool) { payout(); schedule(); } function payout() private returns (bool) { require(block.number >= lockedUntil); require(address(this).balance >= paymentValue); recipient.transfer(paymentValue); emit PaymentExecuted(currentScheduledTransaction, recipient, paymentValue); return true; } function schedule() private returns (bool) { lockedUntil = block.number + paymentInterval; currentScheduledTransaction = scheduler.schedule.value(0.1 ether)( // 0.1 ether is to pay for gas, bounty and fee this, // send to self "", // and trigger fallback function [ 1000000, // The amount of gas to be sent with the transaction. Accounts for payout + new contract deployment 0, // The amount of wei to be sent. 255, // The size of the execution window. lockedUntil, // The start of the execution window. 20000000000 wei, // The gasprice for the transaction (aka 20 gwei) 20000000000 wei, // The fee included in the transaction. 20000000000 wei, // The bounty that awards the executor of the transaction. 30000000000 wei // The required amount of wei the claimer must send as deposit. ] ); emit PaymentScheduled(currentScheduledTransaction, recipient, paymentValue); } } /** * @title RequestFactory * @dev Contract which will produce new TransactionRequests. */ contract RequestFactory is RequestFactoryInterface, CloneFactory, Pausable { using IterTools for bool[6]; TransactionRequestCore public transactionRequestCore; uint constant public BLOCKS_BUCKET_SIZE = 240; //~1h uint constant public TIMESTAMP_BUCKET_SIZE = 3600; //1h constructor( address _transactionRequestCore ) public { require(_transactionRequestCore != 0x0); transactionRequestCore = TransactionRequestCore(_transactionRequestCore); } /** * @dev The lowest level interface for creating a transaction request. * * @param _addressArgs [0] - meta.owner * @param _addressArgs [1] - paymentData.feeRecipient * @param _addressArgs [2] - txnData.toAddress * @param _uintArgs [0] - paymentData.fee * @param _uintArgs [1] - paymentData.bounty * @param _uintArgs [2] - schedule.claimWindowSize * @param _uintArgs [3] - schedule.freezePeriod * @param _uintArgs [4] - schedule.reservedWindowSize * @param _uintArgs [5] - schedule.temporalUnit * @param _uintArgs [6] - schedule.windowSize * @param _uintArgs [7] - schedule.windowStart * @param _uintArgs [8] - txnData.callGas * @param _uintArgs [9] - txnData.callValue * @param _uintArgs [10] - txnData.gasPrice * @param _uintArgs [11] - claimData.requiredDeposit * @param _callData - The call data */ function createRequest( address[3] _addressArgs, uint[12] _uintArgs, bytes _callData ) whenNotPaused public payable returns (address) { // Create a new transaction request clone from transactionRequestCore. address transactionRequest = createClone(transactionRequestCore); // Call initialize on the transaction request clone. TransactionRequestCore(transactionRequest).initialize.value(msg.value)( [ msg.sender, // Created by _addressArgs[0], // meta.owner _addressArgs[1], // paymentData.feeRecipient _addressArgs[2] // txnData.toAddress ], _uintArgs, //uint[12] _callData ); // Track the address locally requests[transactionRequest] = true; // Log the creation. emit RequestCreated( transactionRequest, _addressArgs[0], getBucket(_uintArgs[7], RequestScheduleLib.TemporalUnit(_uintArgs[5])), _uintArgs ); return transactionRequest; } /** * The same as createRequest except that it requires validation prior to * creation. * * Parameters are the same as `createRequest` */ function createValidatedRequest( address[3] _addressArgs, uint[12] _uintArgs, bytes _callData ) public payable returns (address) { bool[6] memory isValid = validateRequestParams( _addressArgs, _uintArgs, msg.value ); if (!isValid.all()) { if (!isValid[0]) { emit ValidationError(uint8(Errors.InsufficientEndowment)); } if (!isValid[1]) { emit ValidationError(uint8(Errors.ReservedWindowBiggerThanExecutionWindow)); } if (!isValid[2]) { emit ValidationError(uint8(Errors.InvalidTemporalUnit)); } if (!isValid[3]) { emit ValidationError(uint8(Errors.ExecutionWindowTooSoon)); } if (!isValid[4]) { emit ValidationError(uint8(Errors.CallGasTooHigh)); } if (!isValid[5]) { emit ValidationError(uint8(Errors.EmptyToAddress)); } // Try to return the ether sent with the message msg.sender.transfer(msg.value); return 0x0; } return createRequest(_addressArgs, _uintArgs, _callData); } /// ---------------------------- /// Internal /// ---------------------------- /* * @dev The enum for launching `ValidationError` events and mapping them to an error. */ enum Errors { InsufficientEndowment, ReservedWindowBiggerThanExecutionWindow, InvalidTemporalUnit, ExecutionWindowTooSoon, CallGasTooHigh, EmptyToAddress } event ValidationError(uint8 error); /* * @dev Validate the constructor arguments for either `createRequest` or `createValidatedRequest`. */ function validateRequestParams( address[3] _addressArgs, uint[12] _uintArgs, uint _endowment ) public view returns (bool[6]) { return RequestLib.validate( [ msg.sender, // meta.createdBy _addressArgs[0], // meta.owner _addressArgs[1], // paymentData.feeRecipient _addressArgs[2] // txnData.toAddress ], _uintArgs, _endowment ); } /// Mapping to hold known requests. mapping (address => bool) requests; function isKnownRequest(address _address) public view returns (bool isKnown) { return requests[_address]; } function getBucket(uint windowStart, RequestScheduleLib.TemporalUnit unit) public pure returns(int) { uint bucketSize; /* since we want to handle both blocks and timestamps and do not want to get into case where buckets overlaps block buckets are going to be negative ints timestamp buckets are going to be positive ints we'll overflow after 2**255-1 blocks instead of 2**256-1 since we encoding this on int256 */ int sign; if (unit == RequestScheduleLib.TemporalUnit.Blocks) { bucketSize = BLOCKS_BUCKET_SIZE; sign = -1; } else if (unit == RequestScheduleLib.TemporalUnit.Timestamp) { bucketSize = TIMESTAMP_BUCKET_SIZE; sign = 1; } else { revert(); } return sign * int(windowStart - (windowStart % bucketSize)); } }
@dev Validation: ensure that the toAddress is not set to the empty address./
function validateToAddress(address toAddress) internal pure returns (bool) { return toAddress != 0x0; }
1,732,013
[ 1, 4354, 30, 3387, 716, 326, 358, 1887, 353, 486, 444, 358, 326, 1008, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1954, 774, 1887, 12, 2867, 358, 1887, 13, 203, 3639, 2713, 16618, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 358, 1887, 480, 374, 92, 20, 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 ]
./full_match/80001/0x7902a4929d9Ae3eEcC147556BC113B953c0e1b18/sources/contracts/bases/ToucanCarbonOffsetsBase.sol
@dev Internal function retire and mint certificates Retire provided amount Mint certificateslither-disable-next-line unused-return
function _retireAndMintCertificate( address retiringEntity, string calldata retiringEntityString, address beneficiary, string calldata beneficiaryString, string calldata retirementMessage, uint256 amount ) internal virtual whenNotPaused { uint256 retirementEventId = _retire(msg.sender, amount, retiringEntity); uint256[] memory retirementEventIds = new uint256[](1); retirementEventIds[0] = retirementEventId; address certAddr = IToucanContractRegistry(contractRegistry) .retirementCertificatesAddress(); IRetirementCertificates(certAddr).mintCertificate( retiringEntity, retiringEntityString, beneficiary, beneficiaryString, retirementMessage, retirementEventIds ); }
869,991
[ 1, 3061, 445, 325, 577, 471, 312, 474, 12522, 17100, 577, 2112, 3844, 490, 474, 12522, 80, 2927, 17, 8394, 17, 4285, 17, 1369, 10197, 17, 2463, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1349, 577, 1876, 49, 474, 4719, 12, 203, 3639, 1758, 325, 11256, 1943, 16, 203, 3639, 533, 745, 892, 325, 11256, 1943, 780, 16, 203, 3639, 1758, 27641, 74, 14463, 814, 16, 203, 3639, 533, 745, 892, 27641, 74, 14463, 814, 780, 16, 203, 3639, 533, 745, 892, 325, 577, 475, 1079, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 5024, 1347, 1248, 28590, 288, 203, 3639, 2254, 5034, 325, 577, 475, 21973, 273, 389, 1349, 577, 12, 3576, 18, 15330, 16, 3844, 16, 325, 11256, 1943, 1769, 203, 3639, 2254, 5034, 8526, 3778, 325, 577, 475, 1133, 2673, 273, 394, 2254, 5034, 8526, 12, 21, 1769, 203, 3639, 325, 577, 475, 1133, 2673, 63, 20, 65, 273, 325, 577, 475, 21973, 31, 203, 203, 3639, 1758, 3320, 3178, 273, 467, 774, 89, 4169, 8924, 4243, 12, 16351, 4243, 13, 203, 5411, 263, 1349, 577, 475, 14133, 1887, 5621, 203, 3639, 467, 7055, 577, 475, 14133, 12, 7593, 3178, 2934, 81, 474, 4719, 12, 203, 5411, 325, 11256, 1943, 16, 203, 5411, 325, 11256, 1943, 780, 16, 203, 5411, 27641, 74, 14463, 814, 16, 203, 5411, 27641, 74, 14463, 814, 780, 16, 203, 5411, 325, 577, 475, 1079, 16, 203, 5411, 325, 577, 475, 1133, 2673, 203, 3639, 11272, 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 ]
// produced by the Solididy File Flattener (c) David Appleton 2018 // contact : [email protected] // released under Apache 2.0 licence library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } contract AmmuNationStore is Claimable{ using SafeMath for uint256; GTAInterface public token; uint256 private tokenSellPrice; //wei uint256 private tokenBuyPrice; //wei uint256 public buyDiscount; //% event Buy(address buyer, uint256 amount, uint256 payed); event Robbery(address robber); constructor (address _tokenAddress) public { token = GTAInterface(_tokenAddress); } /** Owner's operations to fill and empty the stock */ // Important! remember to call GoldenThalerToken(address).approve(this, amount) // or this contract will not be able to do the transfer on your behalf. function depositGTA(uint256 amount) onlyOwner public { require(token.transferFrom(msg.sender, this, amount), "Insufficient funds"); } function withdrawGTA(uint256 amount) onlyOwner public { require(token.transfer(msg.sender, amount), "Amount exceeds the available balance"); } function robCashier() onlyOwner public { msg.sender.transfer(address(this).balance); emit Robbery(msg.sender); } /** */ /** * @dev Set the prices in wei for 1 GTA * @param _newSellPrice The price people can sell GTA for * @param _newBuyPrice The price people can buy GTA for */ function setTokenPrices(uint256 _newSellPrice, uint256 _newBuyPrice) onlyOwner public { tokenSellPrice = _newSellPrice; tokenBuyPrice = _newBuyPrice; } function buy() payable public returns (uint256){ //note: the price of 1 GTA is in wei, but the token transfer expects the amount in 'token wei' //so we're missing 10*18 uint256 value = msg.value.mul(1 ether); uint256 _buyPrice = tokenBuyPrice; if (buyDiscount > 0) { //happy discount! _buyPrice = _buyPrice.sub(_buyPrice.mul(buyDiscount).div(100)); } uint256 amount = value.div(_buyPrice); require(token.balanceOf(this) >= amount, "Sold out"); require(token.transfer(msg.sender, amount), "Couldn't transfer token"); emit Buy(msg.sender, amount, msg.value); return amount; } // Important! remember to call GoldenThalerToken(address).approve(this, amount) // or this contract will not be able to do the transfer on your behalf. //TODO No sell at this moment /*function sell(uint256 amount) public returns (uint256){ require(token.balanceOf(msg.sender) >= amount, "Insufficient funds"); require(token.transferFrom(msg.sender, this, amount), "Couldn't transfer token"); uint256 revenue = amount.mul(tokenSellPrice).div(1 ether); msg.sender.transfer(revenue); return revenue; }*/ function applyDiscount(uint256 discount) onlyOwner public { buyDiscount = discount; } function getTokenBuyPrice() public view returns (uint256) { uint256 _buyPrice = tokenBuyPrice; if (buyDiscount > 0) { _buyPrice = _buyPrice.sub(_buyPrice.mul(buyDiscount).div(100)); } return _buyPrice; } function getTokenSellPrice() public view returns (uint256) { return tokenSellPrice; } } /** * @title GTA contract interface */ interface GTAInterface { function transferFrom(address _from, address _to, uint256 _value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function balanceOf(address _owner) external view returns (uint256); }
note: the price of 1 GTA is in wei, but the token transfer expects the amount in 'token wei'so we're missing 10*18happy discount!
function buy() payable public returns (uint256){ uint256 value = msg.value.mul(1 ether); uint256 _buyPrice = tokenBuyPrice; if (buyDiscount > 0) { _buyPrice = _buyPrice.sub(_buyPrice.mul(buyDiscount).div(100)); } uint256 amount = value.div(_buyPrice); require(token.balanceOf(this) >= amount, "Sold out"); require(token.transfer(msg.sender, amount), "Couldn't transfer token"); emit Buy(msg.sender, amount, msg.value); return amount; } require(token.transferFrom(msg.sender, this, amount), "Couldn't transfer token"); uint256 revenue = amount.mul(tokenSellPrice).div(1 ether); msg.sender.transfer(revenue); return revenue;
13,002,847
[ 1, 7652, 30, 326, 6205, 434, 404, 611, 9833, 353, 316, 732, 77, 16, 1496, 326, 1147, 7412, 10999, 326, 3844, 316, 296, 2316, 732, 77, 1807, 83, 732, 4565, 3315, 13822, 28, 76, 438, 2074, 12137, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 1435, 8843, 429, 1071, 1135, 261, 11890, 5034, 15329, 203, 3639, 2254, 5034, 460, 273, 1234, 18, 1132, 18, 16411, 12, 21, 225, 2437, 1769, 203, 3639, 2254, 5034, 389, 70, 9835, 5147, 273, 1147, 38, 9835, 5147, 31, 203, 3639, 309, 261, 70, 9835, 9866, 405, 374, 13, 288, 203, 5411, 389, 70, 9835, 5147, 273, 389, 70, 9835, 5147, 18, 1717, 24899, 70, 9835, 5147, 18, 16411, 12, 70, 9835, 9866, 2934, 2892, 12, 6625, 10019, 203, 3639, 289, 203, 3639, 2254, 5034, 3844, 273, 460, 18, 2892, 24899, 70, 9835, 5147, 1769, 203, 3639, 2583, 12, 2316, 18, 12296, 951, 12, 2211, 13, 1545, 3844, 16, 315, 55, 1673, 596, 8863, 203, 3639, 2583, 12, 2316, 18, 13866, 12, 3576, 18, 15330, 16, 3844, 3631, 315, 16342, 1404, 7412, 1147, 8863, 203, 3639, 3626, 605, 9835, 12, 3576, 18, 15330, 16, 3844, 16, 1234, 18, 1132, 1769, 203, 3639, 327, 3844, 31, 203, 565, 289, 203, 203, 3639, 2583, 12, 2316, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 333, 16, 3844, 3631, 315, 16342, 1404, 7412, 1147, 8863, 203, 3639, 2254, 5034, 283, 24612, 273, 3844, 18, 16411, 12, 2316, 55, 1165, 5147, 2934, 2892, 12, 21, 225, 2437, 1769, 203, 3639, 1234, 18, 15330, 18, 13866, 12, 266, 24612, 1769, 203, 3639, 327, 283, 24612, 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 ]
./full_match/8453/0xB89c125b433b854390Fddb22E8a1bDA4281e2946/sources/contracts/farms/BasetasticStaking.sol
handle the transfer of reward tokens via `transferFrom` to reduce the number of transactions required and ensure correctness of the reward amount
function notifyRewardAmount(address _rewardsToken, uint256 reward) external updateReward(address(0)) { require(rewardDistributors[_rewardsToken][msg.sender], "MultiFeeDistribution::notifyRewardAmount: Only reward distributors allowed"); require(reward > 0, "MultiFeeDistribution::notifyRewardAmount: No reward"); IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), reward); _notifyReward(_rewardsToken, reward); emit RewardAdded(reward); }
11,553,895
[ 1, 4110, 326, 7412, 434, 19890, 2430, 3970, 1375, 13866, 1265, 68, 358, 5459, 326, 1300, 434, 8938, 1931, 471, 3387, 3434, 4496, 434, 326, 19890, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5066, 17631, 1060, 6275, 12, 2867, 389, 266, 6397, 1345, 16, 2254, 5034, 19890, 13, 3903, 1089, 17631, 1060, 12, 2867, 12, 20, 3719, 288, 203, 3639, 2583, 12, 266, 2913, 1669, 665, 13595, 63, 67, 266, 6397, 1345, 6362, 3576, 18, 15330, 6487, 315, 5002, 14667, 9003, 2866, 12336, 17631, 1060, 6275, 30, 5098, 19890, 1015, 665, 13595, 2935, 8863, 203, 3639, 2583, 12, 266, 2913, 405, 374, 16, 315, 5002, 14667, 9003, 2866, 12336, 17631, 1060, 6275, 30, 2631, 19890, 8863, 203, 3639, 467, 654, 39, 3462, 24899, 266, 6397, 1345, 2934, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 19890, 1769, 203, 3639, 389, 12336, 17631, 1060, 24899, 266, 6397, 1345, 16, 19890, 1769, 203, 3639, 3626, 534, 359, 1060, 8602, 12, 266, 2913, 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 ]
pragma solidity 0.4.26; import "./interfaces/IConsumerPriceOracle.sol"; import "./Owned.sol"; import "./SafeMath.sol"; interface Medianizer { function peek() external view returns (bytes32, bool); } contract MocUSDToBTCOracle is IConsumerPriceOracle, Owned { using SafeMath for uint256; uint256 public constant DECIMALS = 10**18; address public mocOracleAddress; event SetMoCOracleAddress(address indexed mocOracleAddress, address changerAddress); /** * @dev initializes a ne MoC oracle * * @param _mocOracleAddress MoC oracle address */ constructor(address _mocOracleAddress) public { setMoCOracleAddress(_mocOracleAddress); } /** * @dev returns the USD/BTC rate. * * @return always returns the rate of 10000 */ function latestAnswer() external view returns (int256) { (bytes32 value, bool hasValue) = Medianizer(mocOracleAddress).peek(); require(hasValue, "Doesn't has value"); return int256(DECIMALS.div(uint256(value)).mul(DECIMALS)); } /** * @dev returns the USD/BTC update time. * * @return always returns current block's timestamp */ function latestTimestamp() external view returns (uint256) { return now; // MoC oracle doesn't return update timestamp } /** * @dev set MoC oracle address * * @param _mocOracleAddress MoC oracle address */ function setMoCOracleAddress(address _mocOracleAddress) public ownerOnly { require(_mocOracleAddress != address(0), "_mocOracleAddress shall not be zero address"); mocOracleAddress = _mocOracleAddress; emit SetMoCOracleAddress(mocOracleAddress, msg.sender); } }
* @dev initializes a ne MoC oracle @param _mocOracleAddress MoC oracle address/
constructor(address _mocOracleAddress) public { setMoCOracleAddress(_mocOracleAddress); }
2,531,630
[ 1, 6769, 3128, 279, 1073, 14987, 39, 20865, 225, 389, 81, 504, 23601, 1887, 14987, 39, 20865, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 202, 12316, 12, 2867, 389, 81, 504, 23601, 1887, 13, 1071, 288, 203, 202, 202, 542, 16727, 3865, 16873, 1887, 24899, 81, 504, 23601, 1887, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x82b902E5F8C52b1025b4cB400fB54657708a950f/sources/contracts/evaluator.sol
Retrieving a random signature and associated address Checking that student contract is able to extract the address from the signature Incrementing next value store rank ERC721 points
function ex3_extractAddressFromSignature() public { address signatureSender = extractAddress(randomBytes32ToSign[nextValueStoreRank] , associatedSignatures[nextValueStoreRank]); address retrievedAddressByExerciceSolution = studentExerciceSolution[msg.sender].getAddressFromSignature(randomBytes32ToSign[nextValueStoreRank] , associatedSignatures[nextValueStoreRank]); require(signatureSender == retrievedAddressByExerciceSolution, "Signature not interpreted correctly"); nextValueStoreRank += 1; if (nextValueStoreRank >= 20) { nextValueStoreRank = 0; } { exerciceProgression[msg.sender][3] = true; TDERC20.distributeTokens(msg.sender, 2); } }
12,305,923
[ 1, 3848, 6282, 279, 2744, 3372, 471, 3627, 1758, 24471, 716, 18110, 6835, 353, 7752, 358, 2608, 326, 1758, 628, 326, 3372, 17883, 310, 1024, 460, 1707, 6171, 4232, 39, 27, 5340, 3143, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 431, 23, 67, 8004, 1887, 1265, 5374, 1435, 7010, 565, 1071, 7010, 565, 288, 540, 203, 3639, 1758, 3372, 12021, 273, 2608, 1887, 12, 9188, 2160, 1578, 774, 2766, 63, 4285, 620, 2257, 12925, 65, 269, 3627, 23918, 63, 4285, 620, 2257, 12925, 19226, 203, 203, 3639, 1758, 10295, 1887, 858, 424, 12610, 1812, 16135, 273, 18110, 424, 12610, 1812, 16135, 63, 3576, 18, 15330, 8009, 588, 1887, 1265, 5374, 12, 9188, 2160, 1578, 774, 2766, 63, 4285, 620, 2257, 12925, 65, 269, 3627, 23918, 63, 4285, 620, 2257, 12925, 19226, 203, 540, 203, 3639, 2583, 12, 8195, 12021, 422, 10295, 1887, 858, 424, 12610, 1812, 16135, 16, 315, 5374, 486, 19898, 8783, 8863, 203, 540, 203, 3639, 1024, 620, 2257, 12925, 1011, 404, 31, 203, 3639, 309, 261, 4285, 620, 2257, 12925, 1545, 4200, 13, 203, 3639, 288, 203, 5411, 1024, 620, 2257, 12925, 273, 374, 31, 203, 3639, 289, 203, 203, 3639, 288, 203, 5411, 431, 12610, 1812, 5491, 285, 63, 3576, 18, 15330, 6362, 23, 65, 273, 638, 31, 203, 5411, 399, 4179, 39, 3462, 18, 2251, 887, 5157, 12, 3576, 18, 15330, 16, 576, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^ 0.5.17; import "./SafeMath.sol"; import "./Iupgradable.sol"; contract ClaimsData is Iupgradable { using SafeMath for uint; struct Claim { uint coverId; uint dateUpd; } struct Vote { address voter; uint tokens; uint claimId; int8 verdict; bool rewardClaimed; } struct ClaimsPause { uint coverid; uint dateUpd; bool submit; } struct ClaimPauseVoting { uint claimid; uint pendingTime; bool voting; } struct RewardDistributed { uint lastCAvoteIndex; uint lastMVvoteIndex; } struct ClaimRewardDetails { uint percCA; uint percMV; uint tokenToBeDist; } struct ClaimTotalTokens { uint accept; uint deny; } struct ClaimRewardStatus { uint percCA; uint percMV; } ClaimRewardStatus[] internal rewardStatus; Claim[] internal allClaims; Vote[] internal allvotes; ClaimsPause[] internal claimPause; ClaimPauseVoting[] internal claimPauseVotingEP; mapping(address => RewardDistributed) internal voterVoteRewardReceived; mapping(uint => ClaimRewardDetails) internal claimRewardDetail; mapping(uint => ClaimTotalTokens) internal claimTokensCA; mapping(uint => ClaimTotalTokens) internal claimTokensMV; mapping(uint => int8) internal claimVote; mapping(uint => uint) internal claimsStatus; mapping(uint => uint) internal claimState12Count; mapping(uint => uint[]) internal claimVoteCA; mapping(uint => uint[]) internal claimVoteMember; mapping(address => uint[]) internal voteAddressCA; mapping(address => uint[]) internal voteAddressMember; mapping(address => uint[]) internal allClaimsByAddress; mapping(address => mapping(uint => uint)) internal userClaimVoteCA; mapping(address => mapping(uint => uint)) internal userClaimVoteMember; mapping(address => uint) public userClaimVotePausedOn; uint internal claimPauseLastsubmit; uint internal claimStartVotingFirstIndex; uint public pendingClaimStart; uint public claimDepositTime; uint public maxVotingTime; uint public minVotingTime; uint public payoutRetryTime; uint public claimRewardPerc; uint public minVoteThreshold; uint public maxVoteThreshold; uint public majorityConsensus; uint public pauseDaysCA; event ClaimRaise( uint indexed coverId, address indexed userAddress, uint claimId, uint dateSubmit ); event VoteCast( address indexed userAddress, uint indexed claimId, bytes4 indexed typeOf, uint tokens, uint submitDate, int8 verdict ); constructor() public { pendingClaimStart = 1; maxVotingTime = 48 * 1 hours; minVotingTime = 12 * 1 hours; payoutRetryTime = 24 * 1 hours; allvotes.push(Vote(address(0), 0, 0, 0, false)); allClaims.push(Claim(0, 0)); claimDepositTime = 7 days; claimRewardPerc = 20; minVoteThreshold = 5; maxVoteThreshold = 10; majorityConsensus = 70; pauseDaysCA = 3 days; _addRewardIncentive(); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function setpendingClaimStart(uint _start) external onlyInternal { require(pendingClaimStart <= _start); pendingClaimStart = _start; } /** * @dev Updates the max vote index for which claim assessor has received reward * @param _voter address of the voter. * @param caIndex last index till which reward was distributed for CA */ function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex; } /** * @dev Used to pause claim assessor activity for 3 days * @param user Member address whose claim voting ability needs to be paused */ function setUserClaimVotePausedOn(address user) external { require(ms.checkIsAuthToGoverned(msg.sender)); userClaimVotePausedOn[user] = now; } /** * @dev Updates the max vote index for which member has received reward * @param _voter address of the voter. * @param mvIndex last index till which reward was distributed for member */ function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex; } /** * @param claimid claim id. * @param percCA reward Percentage reward for claim assessor * @param percMV reward Percentage reward for members * @param tokens total tokens to be rewarded */ function setClaimRewardDetail( uint claimid, uint percCA, uint percMV, uint tokens ) external onlyInternal { claimRewardDetail[claimid].percCA = percCA; claimRewardDetail[claimid].percMV = percMV; claimRewardDetail[claimid].tokenToBeDist = tokens; } /** * @dev Sets the reward claim status against a vote id. * @param _voteid vote Id. * @param claimed true if reward for vote is claimed, else false. */ function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal { allvotes[_voteid].rewardClaimed = claimed; } /** * @dev Sets the final vote's result(either accepted or declined)of a claim. * @param _claimId Claim Id. * @param _verdict 1 if claim is accepted,-1 if declined. */ function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal { claimVote[_claimId] = _verdict; } /** * @dev Creates a new claim. */ function addClaim( uint _claimId, uint _coverId, address _from, uint _nowtime ) external onlyInternal { allClaims.push(Claim(_coverId, _nowtime)); allClaimsByAddress[_from].push(_claimId); } /** * @dev Add Vote's details of a given claim. */ function addVote( address _voter, uint _tokens, uint claimId, int8 _verdict ) external onlyInternal { allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false)); } /** * @dev Stores the id of the claim assessor vote given to a claim. * Maintains record of all votes given by all the CA to a claim. * @param _claimId Claim Id to which vote has given by the CA. * @param _voteid Vote Id. */ function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal { claimVoteCA[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Claim assessor's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the CA. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteCA( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteCA[_from][_claimId] = _voteid; voteAddressCA[_from].push(_voteid); } /** * @dev Stores the tokens locked by the Claim Assessors during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens); if (_vote == -1) claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens); } /** * @dev Stores the tokens locked by the Members during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens); if (_vote == -1) claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens); } /** * @dev Stores the id of the member vote given to a claim. * Maintains record of all votes given by all the Members to a claim. * @param _claimId Claim Id to which vote has been given by the Member. * @param _voteid Vote Id. */ function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal { claimVoteMember[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Member's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the Member. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteMember( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteMember[_from][_claimId] = _voteid; voteAddressMember[_from].push(_voteid); } /** * @dev Increases the count of failure until payout of a claim is successful. */ function updateState12Count(uint _claimId, uint _cnt) external onlyInternal { claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt); } /** * @dev Sets status of a claim. * @param _claimId Claim Id. * @param _stat Status number. */ function setClaimStatus(uint _claimId, uint _stat) external onlyInternal { claimsStatus[_claimId] = _stat; } /** * @dev Sets the timestamp of a given claim at which the Claim's details has been updated. * @param _claimId Claim Id of claim which has been changed. * @param _dateUpd timestamp at which claim is updated. */ function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal { allClaims[_claimId].dateUpd = _dateUpd; } /** @dev Queues Claims during Emergency Pause. */ function setClaimAtEmergencyPause( uint _coverId, uint _dateUpd, bool _submit ) external onlyInternal { claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit)); } /** * @dev Set submission flag for Claims queued during emergency pause. * Set to true after EP is turned off and the claim is submitted . */ function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal { claimPause[_index].submit = _submit; } /** * @dev Sets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function setFirstClaimIndexToSubmitAfterEP( uint _firstClaimIndexToSubmit ) external onlyInternal { claimPauseLastsubmit = _firstClaimIndexToSubmit; } /** * @dev Sets the pending vote duration for a claim in case of emergency pause. */ function setPendingClaimDetails( uint _claimId, uint _pendingTime, bool _voting ) external onlyInternal { claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting)); } /** * @dev Sets voting flag true after claim is reopened for voting after emergency pause. */ function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal { claimPauseVotingEP[_claimId].voting = _vote; } /** * @dev Sets the index from which claim needs to be * reopened when emergency pause is swithched off. */ function setFirstClaimIndexToStartVotingAfterEP( uint _claimStartVotingFirstIndex ) external onlyInternal { claimStartVotingFirstIndex = _claimStartVotingFirstIndex; } /** * @dev Calls Vote Event. */ function callVoteEvent( address _userAddress, uint _claimId, bytes4 _typeOf, uint _tokens, uint _submitDate, int8 _verdict ) external onlyInternal { emit VoteCast( _userAddress, _claimId, _typeOf, _tokens, _submitDate, _verdict ); } /** * @dev Calls Claim Event. */ function callClaimEvent( uint _coverId, address _userAddress, uint _claimId, uint _datesubmit ) external onlyInternal { emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit); } /** * @dev Gets Uint Parameters by parameter code * @param code whose details we want * @return string value of the parameter * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "CAMAXVT") { val = maxVotingTime / (1 hours); } else if (code == "CAMINVT") { val = minVotingTime / (1 hours); } else if (code == "CAPRETRY") { val = payoutRetryTime / (1 hours); } else if (code == "CADEPT") { val = claimDepositTime / (1 days); } else if (code == "CAREWPER") { val = claimRewardPerc; } else if (code == "CAMINTH") { val = minVoteThreshold; } else if (code == "CAMAXTH") { val = maxVoteThreshold; } else if (code == "CACONPER") { val = majorityConsensus; } else if (code == "CAPAUSET") { val = pauseDaysCA / (1 days); } } /** * @dev Get claim queued during emergency pause by index. */ function getClaimOfEmergencyPauseByIndex( uint _index ) external view returns( uint coverId, uint dateUpd, bool submit ) { coverId = claimPause[_index].coverid; dateUpd = claimPause[_index].dateUpd; submit = claimPause[_index].submit; } /** * @dev Gets the Claim's details of given claimid. */ function getAllClaimsByIndex( uint _claimId ) external view returns( uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return( allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the vote id of a given claim of a given Claim Assessor. */ function getUserClaimVoteCA( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteCA[_add][_claimId]; } /** * @dev Gets the vote id of a given claim of a given member. */ function getUserClaimVoteMember( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteMember[_add][_claimId]; } /** * @dev Gets the count of all votes. */ function getAllVoteLength() external view returns(uint voteCount) { return allvotes.length.sub(1); //Start Index always from 1. } /** * @dev Gets the status number of a given claim. * @param _claimId Claim id. * @return statno Status Number. */ function getClaimStatusNumber(uint _claimId) external view returns(uint claimId, uint statno) { return (_claimId, claimsStatus[_claimId]); } /** * @dev Gets the reward percentage to be distributed for a given status id * @param statusNumber the number of type of status * @return percCA reward Percentage for claim assessor * @return percMV reward Percentage for members */ function getRewardStatus(uint statusNumber) external view returns(uint percCA, uint percMV) { return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV); } /** * @dev Gets the number of tries that have been made for a successful payout of a Claim. */ function getClaimState12Count(uint _claimId) external view returns(uint num) { num = claimState12Count[_claimId]; } /** * @dev Gets the last update date of a claim. */ function getClaimDateUpd(uint _claimId) external view returns(uint dateupd) { dateupd = allClaims[_claimId].dateUpd; } /** * @dev Gets all Claims created by a user till date. * @param _member user's address. * @return claimarr List of Claims id. */ function getAllClaimsByAddress(address _member) external view returns(uint[] memory claimarr) { return allClaimsByAddress[_member]; } /** * @dev Gets the number of tokens that has been locked * while giving vote to a claim by Claim Assessors. * @param _claimId Claim Id. * @return accept Total number of tokens when CA accepts the claim. * @return deny Total number of tokens when CA declines the claim. */ function getClaimsTokenCA( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensCA[_claimId].accept, claimTokensCA[_claimId].deny ); } /** * @dev Gets the number of tokens that have been * locked while assessing a claim as a member. * @param _claimId Claim Id. * @return accept Total number of tokens in acceptance of the claim. * @return deny Total number of tokens against the claim. */ function getClaimsTokenMV( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensMV[_claimId].accept, claimTokensMV[_claimId].deny ); } /** * @dev Gets the total number of votes cast as Claims assessor for/against a given claim */ function getCaClaimVotesToken(uint _claimId) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets the total number of tokens cast as a member for/against a given claim */ function getMemberClaimVotesToken( uint _claimId ) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @dev Provides information of a vote when given its vote id. * @param _voteid Vote Id. */ function getVoteDetails(uint _voteid) external view returns( uint tokens, uint claimId, int8 verdict, bool rewardClaimed ) { return ( allvotes[_voteid].tokens, allvotes[_voteid].claimId, allvotes[_voteid].verdict, allvotes[_voteid].rewardClaimed ); } /** * @dev Gets the voter's address of a given vote id. */ function getVoterVote(uint _voteid) external view returns(address voter) { return allvotes[_voteid].voter; } /** * @dev Provides information of a Claim when given its claim id. * @param _claimId Claim Id. */ function getClaim( uint _claimId ) external view returns( uint claimId, uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return ( _claimId, allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the total number of votes of a given claim. * @param _claimId Claim Id. * @param _ca if 1: votes given by Claim Assessors to a claim, * else returns the number of votes of given by Members to a claim. * @return len total number of votes for/against a given claim. */ function getClaimVoteLength( uint _claimId, uint8 _ca ) external view returns(uint claimId, uint len) { claimId = _claimId; if (_ca == 1) len = claimVoteCA[_claimId].length; else len = claimVoteMember[_claimId].length; } /** * @dev Gets the verdict of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return ver 1 if vote was given in favour,-1 if given in against. */ function getVoteVerdict( uint _claimId, uint _index, uint8 _ca ) external view returns(int8 ver) { if (_ca == 1) ver = allvotes[claimVoteCA[_claimId][_index]].verdict; else ver = allvotes[claimVoteMember[_claimId][_index]].verdict; } /** * @dev Gets the Number of tokens of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return tok Number of tokens. */ function getVoteToken( uint _claimId, uint _index, uint8 _ca ) external view returns(uint tok) { if (_ca == 1) tok = allvotes[claimVoteCA[_claimId][_index]].tokens; else tok = allvotes[claimVoteMember[_claimId][_index]].tokens; } /** * @dev Gets the Voter's address of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return voter Voter's address. */ function getVoteVoter( uint _claimId, uint _index, uint8 _ca ) external view returns(address voter) { if (_ca == 1) voter = allvotes[claimVoteCA[_claimId][_index]].voter; else voter = allvotes[claimVoteMember[_claimId][_index]].voter; } /** * @dev Gets total number of Claims created by a user till date. * @param _add User's address. */ function getUserClaimCount(address _add) external view returns(uint len) { len = allClaimsByAddress[_add].length; } /** * @dev Calculates number of Claims that are in pending state. */ function getClaimLength() external view returns(uint len) { len = allClaims.length.sub(pendingClaimStart); } /** * @dev Gets the Number of all the Claims created till date. */ function actualClaimLength() external view returns(uint len) { len = allClaims.length; } /** * @dev Gets details of a claim. * @param _index claim id = pending claim start + given index * @param _add User's address. * @return coverid cover against which claim has been submitted. * @return claimId Claim Id. * @return voteCA verdict of vote given as a Claim Assessor. * @return voteMV verdict of vote given as a Member. * @return statusnumber Status of claim. */ function getClaimFromNewStart( uint _index, address _add ) external view returns( uint coverid, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { uint i = pendingClaimStart.add(_index); coverid = allClaims[i].coverId; claimId = i; if (userClaimVoteCA[_add][i] > 0) voteCA = allvotes[userClaimVoteCA[_add][i]].verdict; else voteCA = 0; if (userClaimVoteMember[_add][i] > 0) voteMV = allvotes[userClaimVoteMember[_add][i]].verdict; else voteMV = 0; statusnumber = claimsStatus[i]; } /** * @dev Gets details of a claim of a user at a given index. */ function getUserClaimByIndex( uint _index, address _add ) external view returns( uint status, uint coverid, uint claimId ) { claimId = allClaimsByAddress[_add][_index]; status = claimsStatus[claimId]; coverid = allClaims[claimId].coverId; } /** * @dev Gets Id of all the votes given to a claim. * @param _claimId Claim Id. * @return ca id of all the votes given by Claim assessors to a claim. * @return mv id of all the votes given by members to a claim. */ function getAllVotesForClaim( uint _claimId ) external view returns( uint claimId, uint[] memory ca, uint[] memory mv ) { return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]); } /** * @dev Gets Number of tokens deposit in a vote using * Claim assessor's address and claim id. * @return tokens Number of deposited tokens. */ function getTokensClaim( address _of, uint _claimId ) external view returns( uint claimId, uint tokens ) { return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens); } /** * @param _voter address of the voter. * @return lastCAvoteIndex last index till which reward was distributed for CA * @return lastMVvoteIndex last index till which reward was distributed for member */ function getRewardDistributedIndex( address _voter ) external view returns( uint lastCAvoteIndex, uint lastMVvoteIndex ) { return ( voterVoteRewardReceived[_voter].lastCAvoteIndex, voterVoteRewardReceived[_voter].lastMVvoteIndex ); } /** * @param claimid claim id. * @return perc_CA reward Percentage for claim assessor * @return perc_MV reward Percentage for members * @return tokens total tokens to be rewarded */ function getClaimRewardDetail( uint claimid ) external view returns( uint percCA, uint percMV, uint tokens ) { return ( claimRewardDetail[claimid].percCA, claimRewardDetail[claimid].percMV, claimRewardDetail[claimid].tokenToBeDist ); } /** * @dev Gets cover id of a claim. */ function getClaimCoverId(uint _claimId) external view returns(uint claimId, uint coverid) { return (_claimId, allClaims[_claimId].coverId); } /** * @dev Gets total number of tokens staked during voting by Claim Assessors. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter). */ function getClaimVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets total number of tokens staked during voting by Members. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, * -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or * deny on the basis of verdict given as parameter). */ function getClaimMVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @param _voter address of voteid * @param index index to get voteid in CA */ function getVoteAddressCA(address _voter, uint index) external view returns(uint) { return voteAddressCA[_voter][index]; } /** * @param _voter address of voter * @param index index to get voteid in member vote */ function getVoteAddressMember(address _voter, uint index) external view returns(uint) { return voteAddressMember[_voter][index]; } /** * @param _voter address of voter */ function getVoteAddressCALength(address _voter) external view returns(uint) { return voteAddressCA[_voter].length; } /** * @param _voter address of voter */ function getVoteAddressMemberLength(address _voter) external view returns(uint) { return voteAddressMember[_voter].length; } /** * @dev Gets the Final result of voting of a claim. * @param _claimId Claim id. * @return verdict 1 if claim is accepted, -1 if declined. */ function getFinalVerdict(uint _claimId) external view returns(int8 verdict) { return claimVote[_claimId]; } /** * @dev Get number of Claims queued for submission during emergency pause. */ function getLengthOfClaimSubmittedAtEP() external view returns(uint len) { len = claimPause.length; } /** * @dev Gets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function getFirstClaimIndexToSubmitAfterEP() external view returns(uint indexToSubmit) { indexToSubmit = claimPauseLastsubmit; } /** * @dev Gets number of Claims to be reopened for voting post emergency pause period. */ function getLengthOfClaimVotingPause() external view returns(uint len) { len = claimPauseVotingEP.length; } /** * @dev Gets claim details to be reopened for voting after emergency pause. */ function getPendingClaimDetailsByIndex( uint _index ) external view returns( uint claimId, uint pendingTime, bool voting ) { claimId = claimPauseVotingEP[_index].claimid; pendingTime = claimPauseVotingEP[_index].pendingTime; voting = claimPauseVotingEP[_index].voting; } /** * @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off. */ function getFirstClaimIndexToStartVotingAfterEP() external view returns(uint firstindex) { firstindex = claimStartVotingFirstIndex; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "CAMAXVT") { _setMaxVotingTime(val * 1 hours); } else if (code == "CAMINVT") { _setMinVotingTime(val * 1 hours); } else if (code == "CAPRETRY") { _setPayoutRetryTime(val * 1 hours); } else if (code == "CADEPT") { _setClaimDepositTime(val * 1 days); } else if (code == "CAREWPER") { _setClaimRewardPerc(val); } else if (code == "CAMINTH") { _setMinVoteThreshold(val); } else if (code == "CAMAXTH") { _setMaxVoteThreshold(val); } else if (code == "CACONPER") { _setMajorityConsensus(val); } else if (code == "CAPAUSET") { _setPauseDaysCA(val * 1 days); } else { revert("Invalid param code"); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal {} /** * @dev Adds status under which a claim can lie. * @param percCA reward percentage for claim assessor * @param percMV reward percentage for members */ function _pushStatus(uint percCA, uint percMV) internal { rewardStatus.push(ClaimRewardStatus(percCA, percMV)); } /** * @dev adds reward incentive for all possible claim status for Claim assessors and members */ function _addRewardIncentive() internal { _pushStatus(0, 0); //0 Pending-Claim Assessor Vote _pushStatus(0, 0); //1 Pending-Claim Assessor Vote Denied, Pending Member Vote _pushStatus(0, 0); //2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote _pushStatus(0, 0); //3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote _pushStatus(0, 0); //4 Pending-CA Consensus not reached Accept, Pending Member Vote _pushStatus(0, 0); //5 Pending-CA Consensus not reached Deny, Pending Member Vote _pushStatus(100, 0); //6 Final-Claim Assessor Vote Denied _pushStatus(100, 0); //7 Final-Claim Assessor Vote Accepted _pushStatus(0, 100); //8 Final-Claim Assessor Vote Denied, MV Accepted _pushStatus(0, 100); //9 Final-Claim Assessor Vote Denied, MV Denied _pushStatus(0, 0); //10 Final-Claim Assessor Vote Accept, MV Nodecision _pushStatus(0, 0); //11 Final-Claim Assessor Vote Denied, MV Nodecision _pushStatus(0, 0); //12 Claim Accepted Payout Pending _pushStatus(0, 0); //13 Claim Accepted No Payout _pushStatus(0, 0); //14 Claim Accepted Payout Done } /** * @dev Sets Maximum time(in seconds) for which claim assessment voting is open */ function _setMaxVotingTime(uint _time) internal { maxVotingTime = _time; } /** * @dev Sets Minimum time(in seconds) for which claim assessment voting is open */ function _setMinVotingTime(uint _time) internal { minVotingTime = _time; } /** * @dev Sets Minimum vote threshold required */ function _setMinVoteThreshold(uint val) internal { minVoteThreshold = val; } /** * @dev Sets Maximum vote threshold required */ function _setMaxVoteThreshold(uint val) internal { maxVoteThreshold = val; } /** * @dev Sets the value considered as Majority Consenus in voting */ function _setMajorityConsensus(uint val) internal { majorityConsensus = val; } /** * @dev Sets the payout retry time */ function _setPayoutRetryTime(uint _time) internal { payoutRetryTime = _time; } /** * @dev Sets percentage of reward given for claim assessment */ function _setClaimRewardPerc(uint _val) internal { claimRewardPerc = _val; } /** * @dev Sets the time for which claim is deposited. */ function _setClaimDepositTime(uint _time) internal { claimDepositTime = _time; } /** * @dev Sets number of days claim assessment will be paused */ function _setPauseDaysCA(uint val) internal { pauseDaysCA = val; } } /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */
* @dev Gets the status number of a given claim. @param _claimId Claim id. @return statno Status Number./
function getClaimStatusNumber(uint _claimId) external view returns(uint claimId, uint statno) { return (_claimId, claimsStatus[_claimId]); }
5,407,128
[ 1, 3002, 326, 1267, 1300, 434, 279, 864, 7516, 18, 225, 389, 14784, 548, 18381, 612, 18, 327, 610, 2135, 2685, 3588, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 13674, 4581, 1482, 1854, 12, 11890, 389, 14784, 548, 13, 3903, 1476, 1135, 12, 11890, 7516, 548, 16, 2254, 610, 2135, 13, 288, 203, 3639, 327, 261, 67, 14784, 548, 16, 11955, 1482, 63, 67, 14784, 548, 19226, 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 ]
./full_match/1/0x8627e113715D6E5E6d59d8f34414160bac2415E4/sources/contracts/producers/crowdfunds/crowdfund-with-editions/CrowdfundWithEditionsStorage.sol
@notice Current reentrancy status -- used by the modifier.
uint256 internal reentrancy_status;
4,921,257
[ 1, 3935, 283, 8230, 12514, 1267, 1493, 1399, 635, 326, 9606, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 2713, 283, 8230, 12514, 67, 2327, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // ERC721URIStorage allows you to set tokenURI after minting // ERC721Holder ensures that a smart contract can hold NFTs import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; library CollaborativeMinterHolder { struct SalesTransaction { address from; // buyer address to; // recipient of token uint256[] tokenIds; // tokens for sale uint256 value; // price for token bool secondarySale; // check if we have a secondary sale bool revoked; bool executed; bool executing; // check if library is executing transation bool modifying; // check if transaction is being modified uint256 numConfirmations; } modifier onlyOwner(CollaborativeMinter _collaborativeMinter) { // restrict to only owners require(_collaborativeMinter.isOwner(msg.sender),'not an owner'); _; } // restrict only to transactions that exist modifier salesTransactionExists(uint256 _txIndex, SalesTransaction[] storage _salesTransactions) { require(_txIndex < _salesTransactions.length, "sales transaction does not exist"); _; } // restrict only to transactions that are not executed modifier salesTransactionNotExecuted(uint256 _txIndex, SalesTransaction[] storage _salesTransactions) { require(!_salesTransactions[_txIndex].executed, "sales transaction is already executed"); _; } // restrict only to transactions that are not confirmed by caller modifier salesTransactionNotConfirmed(uint256 _txIndex, CollaborativeMinter _collaborativeMinter) { require(!_collaborativeMinter.getConfirmation(_txIndex, msg.sender), "sales transaction is already confirmed"); _; } // restrict only to transactions that are not revoked by original buyer modifier salesTransactionNotRevoked(uint256 _txIndex, SalesTransaction[] storage _salesTransactions) { require(!_salesTransactions[_txIndex].revoked, "sales transaction is already revoked"); _; } // restrict to the sender of the sales transaction modifier onlySalesTransactionSender(uint256 _txIndex, SalesTransaction[] storage _salesTransactions) { require(_salesTransactions[_txIndex].from == msg.sender, "not the sales transaction sender"); _; } // check if token IDs are valid and are owned by contract modifier ownedByContract(uint256[] memory _tokenIds, CollaborativeMinter _collaborativeMinter) { for(uint256 i = 0; i < _tokenIds.length; i++){ require(_tokenIds[i] < _collaborativeMinter.tokenCounter(), "invalid token ID"); require(_collaborativeMinter.isApprovedOrOwner(address(_collaborativeMinter),_tokenIds[i]),"token not owned by contract"); } _; } modifier allOwnedByContract(CollaborativeMinter _collaborativeMinter) { // check if all NFTs are owned by the contract for(uint256 i = 0; i < _collaborativeMinter.tokenCounter(); i++){ require(_collaborativeMinter.isApprovedOrOwner(address(_collaborativeMinter),i),"not all tokens owned by contract"); } _; } function submitSalesTransaction(address _from, address _to, uint256[] memory _tokenIds, uint256 _value, SalesTransaction[] storage _salesTransactions, CollaborativeMinter _collaborativeMinter) ownedByContract(_tokenIds, _collaborativeMinter) public returns (uint256) { // buyer sends sales transaction, returns transaction index uint256 txIndex = _salesTransactions.length; _salesTransactions.push(SalesTransaction({ from: _from, to: _to, tokenIds: _tokenIds, value: _value, secondarySale: false, revoked: false, executed: false, executing: false, modifying: false, numConfirmations: 0 })); return txIndex; } function submitSecondarySalesTransaction(address _from, address _to, uint256[] memory _tokenIds, uint256 _value, SalesTransaction[] storage _salesTransactions) public returns (uint256) { // buyer sends sales transaction, returns transaction index uint256 txIndex = _salesTransactions.length; _salesTransactions.push(SalesTransaction({ from: _from, to: _to, tokenIds: _tokenIds, value: _value, secondarySale: true, revoked: false, executed: false, executing: false, modifying: false, numConfirmations: 0 })); return txIndex; } function approveSalesTransaction(uint256 _txIndex, SalesTransaction[] storage _salesTransactions, CollaborativeMinter _collaborativeMinter) onlyOwner(_collaborativeMinter) salesTransactionExists(_txIndex, _salesTransactions) salesTransactionNotExecuted(_txIndex, _salesTransactions) salesTransactionNotConfirmed(_txIndex, _collaborativeMinter) salesTransactionNotRevoked(_txIndex, _salesTransactions) public returns (bool) { // owner approves sales transaction // update confirmations and number of confirmations _salesTransactions[_txIndex].modifying = true; _collaborativeMinter.setConfirmation(_txIndex, msg.sender, true); _salesTransactions[_txIndex].modifying = false; _salesTransactions[_txIndex].numConfirmations += 1; if(_salesTransactions[_txIndex].numConfirmations == _collaborativeMinter.numberOfOwners()){ // execute if approved by all owners _salesTransactions[_txIndex].executing = true; executeSalesTransaction(_txIndex, _salesTransactions, _collaborativeMinter); _salesTransactions[_txIndex].executing = false; } return true; } function denySalesTransaction(uint256 _txIndex, SalesTransaction[] storage _salesTransactions, CollaborativeMinter _collaborativeMinter) onlyOwner(_collaborativeMinter) salesTransactionExists(_txIndex, _salesTransactions) salesTransactionNotExecuted(_txIndex, _salesTransactions) salesTransactionNotRevoked(_txIndex, _salesTransactions) public returns (bool) { // owner denies sales transaction // update confirmations and number of confirmations require(_collaborativeMinter.getConfirmation(_txIndex,msg.sender), "sales transaction not approved by owner"); _salesTransactions[_txIndex].modifying = true; _collaborativeMinter.setConfirmation(_txIndex, msg.sender, false); _salesTransactions[_txIndex].modifying = false; _salesTransactions[_txIndex].numConfirmations -= 1; return true; } // sender revoke sales transaction to get ETH back function revokeSalesTransaction(uint256 _txIndex, SalesTransaction[] storage _salesTransactions) public salesTransactionExists(_txIndex, _salesTransactions) salesTransactionNotExecuted(_txIndex, _salesTransactions) salesTransactionNotRevoked(_txIndex, _salesTransactions) returns (bool) { require(_salesTransactions[_txIndex].from == msg.sender, "must be account that submitted sales transaction"); uint256 amountToPay = _salesTransactions[_txIndex].value; bool success; (success, ) = _salesTransactions[_txIndex].from.call{value: amountToPay}(""); require(success, "Transfer failed."); _salesTransactions[_txIndex].revoked = true; return true; } function executeSalesTransaction(uint _txIndex, SalesTransaction[] storage _salesTransactions, CollaborativeMinter _collaborativeMinter) internal returns (bool) { uint256[] memory tokens = _salesTransactions[_txIndex].tokenIds; if(_salesTransactions[_txIndex].secondarySale == false) { // initial sale // send ETH to each owner uint256 amountToPay = _salesTransactions[_txIndex].value / _collaborativeMinter.numberOfOwners(); bool success; // pay each owner for(uint256 i = 0; i < _collaborativeMinter.numberOfOwners(); i++){ (success, ) = _collaborativeMinter.owners(i).call{value:amountToPay}(""); require(success, "Transfer failed."); } } else { // secondary sale // apply secondary sale fee and send ETH to each owner uint256 secondarySaleValue = _salesTransactions[_txIndex].value / 10; // 10% goes to owners uint256 amountToPay = secondarySaleValue / _collaborativeMinter.numberOfOwners(); bool success; // pay each owner for(uint256 i = 0; i < _collaborativeMinter.numberOfOwners(); i++){ (success, ) = _collaborativeMinter.owners(i).call{value:amountToPay}(""); require(success, "Transfer failed."); } } // send each NFT from the smart contract to the new owner for(uint256 i = 0; i < tokens.length; i++){ _collaborativeMinter.executingTransfer(_txIndex, address(_collaborativeMinter), _salesTransactions[_txIndex].to, tokens[i]); } _salesTransactions[_txIndex].executed = true; return true; } function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _latestReceived, SalesTransaction[] storage _salesTransactions, CollaborativeMinter _collaborativeMinter) public { require(_collaborativeMinter.isApprovedOrOwner(_from, _tokenId), "ERC721: transfer caller is not owner nor approved"); // create a secondary sales transaction, send NFT to contract, execute secondary sale uint256[] memory tokenIdArray = new uint256[](1); tokenIdArray[0] = _tokenId; uint256 secondarySaleId = submitSecondarySalesTransaction(_from, _to, tokenIdArray, _latestReceived, _salesTransactions); _salesTransactions[secondarySaleId].executing = true; _collaborativeMinter.executingTransfer(secondarySaleId, _from, address(_collaborativeMinter), _tokenId); executeSalesTransaction(secondarySaleId, _salesTransactions, _collaborativeMinter); _salesTransactions[secondarySaleId].executing = false; } } // NFT Smart Contract Constructor contract CollaborativeMinter is ERC721URIStorage, ERC721Holder{ uint256 public tokenCounter; uint256 public currentOwner; // define whose turn it is at the current time with owners index\ uint256 public numberOfOwners; bool public isMerged; // defines whether we have a composite NFT address[] public owners; // keep track of all owners of the NFT mapping(address => bool) public isOwner; // used to check if someone is an owner uint256 public latestReceived; // used to get the msg.value for secondary sales // create structs for use with CollaborativeMinterHolder library using CollaborativeMinterHolder for CollaborativeMinterHolder.SalesTransaction; CollaborativeMinterHolder.SalesTransaction[] public salesTransactions; mapping(uint => mapping(address => bool)) public isConfirmed; constructor (address[] memory _owners) ERC721 ("Collaborative Mint", "COMINT"){ require(_owners.length > 0, "owners required"); tokenCounter = 0; numberOfOwners = _owners.length; currentOwner = 0; // define the first owner to have an active turn isMerged = false; for(uint256 i = 0; i < _owners.length; i++){ // define the owners owners.push(_owners[i]); isOwner[_owners[i]] = true; } } modifier onlyCurrentOwner { // restrict to only the active owner require(msg.sender == owners[currentOwner], "not your turn"); _; } modifier onlyOwner { // restrict to only owners require(isOwner[msg.sender],'not an owner'); _; } modifier isNotMerged() { // check if we have a composite NFT require(!isMerged, "NFT is a completed composite"); _; } modifier hasBeenMinted(){ // check if an NFT has been minted require(tokenCounter > 0, "no NFTs have been minted"); _; } modifier allOwnedByContract() { // check if all NFTs are owned by the contract for(uint256 i = 0; i < tokenCounter; i++) { require(_isApprovedOrOwner(address(this),i),"not all tokens owned by contract"); } _; } modifier currentlyExecuting(uint256 _txIndex) { // check if the transaction is currently executing require(salesTransactions[_txIndex].executing,"transaction must be currently executing"); _; } modifier currentlyModifying(uint256 _txIndex) { // check if the transaction is currently being modified require(salesTransactions[_txIndex].modifying,"transaction must be being modified"); _; } receive() external payable { latestReceived = msg.value; } // NFT minting function where only the current owner can mint. Smart contract holds NFTs upon minting function collaborativeMint(string memory _tokenURI) public onlyCurrentOwner isNotMerged returns (uint256) { uint256 newItemId = tokenCounter; _safeMint(address(this), newItemId); // the owner of the NFT is the holder smart contract _setTokenURI(newItemId, _tokenURI); tokenCounter = tokenCounter + 1; uint256 nextOwnerId = (currentOwner + 1) % owners.length; // set up the next turn by getting the following ID currentOwner = nextOwnerId; // update whose turn it is return newItemId; } // NFT minting function where only the current owner can mint. Smart contract holds NFTs upon minting function _collaborativeMint(string memory _tokenURI) private returns (uint256) { uint256 newItemId = tokenCounter; _safeMint(address(this), newItemId); // the owner of the NFT is the holder smart contract _setTokenURI(newItemId, _tokenURI); tokenCounter = tokenCounter + 1; return newItemId; } // merge all collaborative mints and create a composite NFT function mergeCollaborativeMint(string memory _tokenURI) public onlyOwner hasBeenMinted isNotMerged allOwnedByContract returns (bool) { isMerged = true; // burn all collaborative mints for(uint256 i = 0; i < tokenCounter; i++) { _burn(i); } // create a composite NFT _collaborativeMint(_tokenURI); return true; } function isApprovedOrOwner(address _account, uint256 _tokenId) public view returns (bool) { return _isApprovedOrOwner(_account, _tokenId); } // used to transfer NFTs while a transaction is being executed function executingTransfer(uint256 _txIndex, address _from, address _to, uint256 _tokenId) currentlyExecuting(_txIndex) public returns (bool) { _safeTransfer(_from, _to, _tokenId, ""); return true; } // Override safeTransferFrom to allow for royalties from secondary sales function safeTransferFrom(address _from, address _to, uint256 _tokenId) public virtual override { CollaborativeMinterHolder.safeTransferFrom(_from, _to, _tokenId, latestReceived, salesTransactions, this); } // Override safeTransferFrom to allow for royalties from secondary sales function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public virtual override { CollaborativeMinterHolder.safeTransferFrom(_from, _to, _tokenId, latestReceived, salesTransactions, this); } // Override transferFrom to allow for royalties from secondary sales function transferFrom(address _from, address _to, uint256 _tokenId) public virtual override { CollaborativeMinterHolder.safeTransferFrom(_from, _to, _tokenId, latestReceived, salesTransactions, this); } // submit a sales transaction function submitSalesTransaction(address _to, uint256[] memory _tokenIds) payable public { CollaborativeMinterHolder.submitSalesTransaction(msg.sender, _to, _tokenIds, msg.value, salesTransactions, this); } function approveSalesTransaction(uint256 _txIndex) public returns (bool) { CollaborativeMinterHolder.approveSalesTransaction(_txIndex, salesTransactions, this); return true; } function denySalesTransaction(uint256 _txIndex) public returns (bool) { CollaborativeMinterHolder.denySalesTransaction(_txIndex, salesTransactions, this); return true; } function revokeSalesTransaction(uint256 _txIndex) public returns (bool) { CollaborativeMinterHolder.revokeSalesTransaction(_txIndex, salesTransactions); return true; } // Retreive the sales transaction data function getSalesTransaction(uint256 _txIndex) public view returns (CollaborativeMinterHolder.SalesTransaction memory) { return salesTransactions[_txIndex]; } function getConfirmation(uint256 _txIndex, address _owner) public view returns (bool) { return isConfirmed[_txIndex][_owner]; } function setConfirmation(uint256 _txIndex, address _owner, bool value) currentlyModifying(_txIndex) public returns (bool) { isConfirmed[_txIndex][_owner] = value; return true; } }
used to get the msg.value for secondary sales
uint256 public latestReceived;
1,783,572
[ 1, 3668, 358, 336, 326, 1234, 18, 1132, 364, 9946, 272, 5408, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 4891, 8872, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xBc42BC505C68B3D015C900223536D1ddd4caE152/sources/contracts/Contract.sol
uint256 tokenIdToMint = _currentIndex; Verify and process payload. address receiver = _req.to;
function mintWithSignature1( MintRequest calldata _req, bytes calldata _signature ) external returns (address signer) { signer = _processRequest(_req, _signature); return signer; }
5,622,324
[ 1, 11890, 5034, 1147, 28803, 49, 474, 273, 389, 2972, 1016, 31, 8553, 471, 1207, 2385, 18, 1758, 5971, 273, 389, 3658, 18, 869, 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 ]
[ 1, 1, 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, 312, 474, 1190, 5374, 21, 12, 203, 3639, 490, 474, 691, 745, 892, 389, 3658, 16, 203, 3639, 1731, 745, 892, 389, 8195, 203, 565, 262, 3903, 1135, 261, 2867, 10363, 13, 288, 203, 203, 3639, 10363, 273, 389, 2567, 691, 24899, 3658, 16, 389, 8195, 1769, 203, 3639, 327, 10363, 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 ]
./partial_match/1/0x5d2F6c3bEFAe73276baCC8017cCb907EE921149F/sources/CypherShia.sol
* @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() Ownable(msg.sender) { _mint(msg.sender, 100_000_000 * 10 ** decimals()); feeAddress = msg.sender; }
4,214,712
[ 1, 2785, 326, 924, 364, 288, 529, 97, 471, 288, 7175, 5496, 1021, 805, 460, 434, 288, 31734, 97, 353, 6549, 18, 2974, 2027, 279, 3775, 460, 364, 288, 31734, 97, 1846, 1410, 30402, 518, 18, 4826, 2795, 434, 4259, 924, 854, 11732, 30, 2898, 848, 1338, 506, 444, 3647, 4982, 16171, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 3885, 1435, 14223, 6914, 12, 3576, 18, 15330, 13, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 2130, 67, 3784, 67, 3784, 380, 1728, 2826, 15105, 10663, 203, 3639, 14036, 1887, 273, 1234, 18, 15330, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-07-06 */ // File: NFT_project/DEPLOYED_CONTRACTS/DEPLOYED_v2/Kami_MAINNET_deployed/For_publishing_etherscan/SpaceMonContract/ERC165/IERC165.sol pragma solidity ^0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: NFT_project/DEPLOYED_CONTRACTS/DEPLOYED_v2/Kami_MAINNET_deployed/For_publishing_etherscan/SpaceMonContract/utils/SafeMath.sol pragma solidity ^0.7.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: NFT_project/DEPLOYED_CONTRACTS/DEPLOYED_v2/Kami_MAINNET_deployed/For_publishing_etherscan/SpaceMonContract/IERC20.sol /** * @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); /** * TODO: Add comment */ function burn(uint256 burnQuantity) 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: NFT_project/DEPLOYED_CONTRACTS/DEPLOYED_v2/Kami_MAINNET_deployed/For_publishing_etherscan/SpaceMonContract/IERC721.sol /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: NFT_project/DEPLOYED_CONTRACTS/DEPLOYED_v2/Kami_MAINNET_deployed/For_publishing_etherscan/SpaceMonContract/IERC721Enumerable.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); } // File: NFT_project/DEPLOYED_CONTRACTS/DEPLOYED_v2/Kami_MAINNET_deployed/For_publishing_etherscan/SpaceMonContract/IKami.sol interface IKami is IERC721Enumerable { function isMintedBeforeReveal(uint256 index) external view returns (bool); function setNameTitle(uint256 tokenId, string memory newName, string memory newTitle) external; function _mintUnity(address winning_address) external; } // File: NFT_project/DEPLOYED_CONTRACTS/DEPLOYED_v2/Kami_MAINNET_deployed/For_publishing_etherscan/SpaceMonContract/utils/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: NFT_project/DEPLOYED_CONTRACTS/DEPLOYED_v2/Kami_MAINNET_deployed/For_publishing_etherscan/SpaceMonContract/utils/Ownable.sol pragma solidity ^0.7.0; contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: NFT_project/DEPLOYED_CONTRACTS/DEPLOYED_v2/Kami_MAINNET_deployed/For_publishing_etherscan/SpaceMonContract/SpaceMon.sol pragma solidity ^0.7.0; /** * * PowerToken Contract (The native token of Kami) * @dev Extends standard ERC20 contract */ contract SpaceMon is Context, Ownable, IERC20 { using SafeMath for uint256; // Constants uint256 public SECONDS_IN_A_DAY = 86400; uint256 public constant INITIAL_ALLOTMENT = 3000 * (10 ** 18); uint256 public constant mintedCap = 480000000*(10**18); // This is maximum amount of MON that can be bought uint256 public constant SpaceMonPrice = 4160000000000; // Public variables uint256 public currentMintedAmount; // This records the amount of SpaceMon that is minted in exchange of eth. uint256 public emissionStart; uint256 public puzzleEmissionEnd; uint256 public nameEmissionEnd; uint256 public monSaleStartTimestamp; uint256 public puzzleEmissionDaily = 5667 * (10 ** 18); uint256 public nameEmissionDaily = 83*(10**18); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping(uint256 => uint256) private _lastClaim; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; address private _kamiAddress; address private _platformAddress; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. Also initalizes {emissionStart} * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) { _name = name; _symbol = symbol; _decimals = 18; currentMintedAmount = 0; } function preRevealSet(uint256 emissionStartTimestamp, uint256 monSaleTS, address kamiAddress, address platformAddress) public onlyOwner { emissionStart = emissionStartTimestamp; puzzleEmissionEnd = emissionStartTimestamp + (86400 * 90); nameEmissionEnd = emissionStartTimestamp + (86400 * 3650); monSaleStartTimestamp = monSaleTS; _platformAddress = platformAddress; _kamiAddress = kamiAddress; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev When accumulated SpaceMon tokens have last been claimed for a Kami index */ function lastClaim(uint256 tokenIndex) public view returns (uint256) { require(IKami(_kamiAddress).ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address"); require(tokenIndex < IKami(_kamiAddress).totalSupply(), "NFT at index has not been minted yet"); uint256 lastClaimed = uint256(_lastClaim[tokenIndex]) != 0 ? uint256(_lastClaim[tokenIndex]) : emissionStart; return lastClaimed; } /** * @dev Accumulated Power tokens for a Kami token index. */ function accumulated(uint256 tokenIndex) public view returns (uint256) { require(block.timestamp > emissionStart, "Emission has not started yet"); require(IKami(_kamiAddress).ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address"); require(tokenIndex < IKami(_kamiAddress).totalSupply(), "NFT at index has not been minted yet"); uint256 lastClaimed = lastClaim(tokenIndex); // Sanity check if last claim was on or after name emission end if (lastClaimed >= nameEmissionEnd) return 0; uint256 puzzleAccumulationPeriod = block.timestamp < puzzleEmissionEnd ? block.timestamp : puzzleEmissionEnd; // Getting the min value of both uint256 nameAccumulationPeriod = block.timestamp < nameEmissionEnd ? block.timestamp : nameEmissionEnd; // Getting the min value of both uint256 puzzleTotalAccumulated = puzzleAccumulationPeriod.sub(lastClaimed).mul(puzzleEmissionDaily).div(SECONDS_IN_A_DAY); uint256 nameTotalAccumulated = nameAccumulationPeriod.sub(lastClaimed).mul(nameEmissionDaily).div(SECONDS_IN_A_DAY); uint256 totalAccumulated = puzzleTotalAccumulated.add(nameTotalAccumulated); // If claim hasn't been done before for the index, add initial allotment (plus prereveal multiplier if applicable) //uint256 puzzleAllotment = getPuzzleAllotment(tokenIndex); if (lastClaimed == emissionStart) { uint256 initialAllotment = IKami(_kamiAddress).isMintedBeforeReveal(tokenIndex) == true ? 3000 : 0; totalAccumulated = totalAccumulated.add(initialAllotment); } return totalAccumulated; } /** * @dev Claim mints SpaceMon and supports multiple token indices at once. */ function claim(uint256[] memory tokenIndices) public returns (uint256) { require(block.timestamp > emissionStart, "Emission has not started yet"); uint256 totalClaimQty = 0; for (uint i = 0; i < tokenIndices.length; i++) { // Sanity check for non-minted index require(tokenIndices[i] < IKami(_kamiAddress).totalSupply(), "NFT at index has not been minted yet"); // Duplicate token index check for (uint j = i + 1; j < tokenIndices.length; j++) { require(tokenIndices[i] != tokenIndices[j], "Duplicate token index"); } uint tokenIndex = tokenIndices[i]; require(IKami(_kamiAddress).ownerOf(tokenIndex) == msg.sender, "Sender is not the owner"); uint256 claimQty = accumulated(tokenIndex); if (claimQty != 0) { totalClaimQty = totalClaimQty.add(claimQty); _lastClaim[tokenIndex] = block.timestamp; } } require(totalClaimQty != 0, "Sorry, No accumulated SpaceMon"); _mint(msg.sender, totalClaimQty); return totalClaimQty; } /** * @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 Withdraw ether from this contract (Callable by owner) */ function withdraw() onlyOwner public { uint balance = address(this).balance; msg.sender.transfer(balance); } /** * @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); // Approval check is skipped if the caller of transferFrom is the Platform contract. For better UX. if (msg.sender != _platformAddress) { _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 Burns a quantity of tokens held by the caller. * * Emits an {Transfer} event to 0 address * */ function burn(uint256 burnQuantity) public virtual override returns (bool) { _burn(msg.sender, burnQuantity); 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, "SpaceMon balance is insufficient"); _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 Mints SpaceMon */ function mintSpaceMon(uint256 tokenQuantity) public payable { require(block.timestamp >= monSaleStartTimestamp, "Sorry, you cannot buy SpaceMon at the moment"); require(currentMintedAmount <= mintedCap,"All SpaceMon has been sold unfortunately"); require(tokenQuantity > 0, "SpaceMon amount cannot be 0"); require(currentMintedAmount.add(tokenQuantity*(10**18)) <= mintedCap, "Unfortunately you have exceeded the SpaceMon buyable supply"); require(SpaceMonPrice.mul(tokenQuantity) == msg.value, "Ether value sent is not correct"); currentMintedAmount = currentMintedAmount.add(tokenQuantity*(10**18)); _mint(msg.sender, tokenQuantity*(10**18)); } /** * @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 When accumulated SpaceMon tokens have last been claimed for a Kami index/
function lastClaim(uint256 tokenIndex) public view returns (uint256) { require(IKami(_kamiAddress).ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address"); require(tokenIndex < IKami(_kamiAddress).totalSupply(), "NFT at index has not been minted yet"); uint256 lastClaimed = uint256(_lastClaim[tokenIndex]) != 0 ? uint256(_lastClaim[tokenIndex]) : emissionStart; return lastClaimed; }
15,204,758
[ 1, 9434, 24893, 14059, 11415, 2430, 1240, 1142, 2118, 7516, 329, 364, 279, 25188, 77, 770, 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, 1142, 9762, 12, 11890, 5034, 1147, 1016, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 45, 47, 26223, 24899, 79, 26223, 1887, 2934, 8443, 951, 12, 2316, 1016, 13, 480, 1758, 12, 20, 3631, 315, 5541, 2780, 506, 374, 1758, 8863, 203, 3639, 2583, 12, 2316, 1016, 411, 467, 47, 26223, 24899, 79, 26223, 1887, 2934, 4963, 3088, 1283, 9334, 315, 50, 4464, 622, 770, 711, 486, 2118, 312, 474, 329, 4671, 8863, 203, 203, 3639, 2254, 5034, 1142, 9762, 329, 273, 2254, 5034, 24899, 2722, 9762, 63, 2316, 1016, 5717, 480, 374, 692, 2254, 5034, 24899, 2722, 9762, 63, 2316, 1016, 5717, 294, 801, 19710, 1685, 31, 203, 3639, 327, 1142, 9762, 329, 31, 203, 565, 289, 203, 1377, 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 ]
./full_match/3/0x063FE4544C683B0AFcf7b2Fba4648313E35CA3aE/sources/browser/KeyStoreHRMSUpdated.sol
Modifier Check for Adding and Getting Individual (Own) Data from Blockchain/
) { require( access[_address] == true, "No Access" ); bytes32 keyCheck; keyCheck = keyAddr[_address]; require( keyCheck == keccak256(abi.encode(_smartkey)), "Smart key is incorrect" ); _; }
14,131,431
[ 1, 9829, 2073, 364, 21240, 471, 26602, 24147, 261, 5460, 13, 1910, 628, 3914, 5639, 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, 262, 288, 203, 3639, 2583, 12, 203, 5411, 2006, 63, 67, 2867, 65, 422, 638, 16, 203, 5411, 315, 2279, 5016, 6, 203, 3639, 11272, 203, 3639, 1731, 1578, 225, 498, 1564, 31, 203, 3639, 498, 1564, 273, 498, 3178, 63, 67, 2867, 15533, 203, 3639, 2583, 12, 203, 5411, 498, 1564, 422, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 24899, 26416, 856, 13, 3631, 203, 5411, 315, 23824, 498, 353, 11332, 6, 203, 3639, 11272, 203, 4202, 389, 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 ]
/** * Kleros Liquid * https://contributing.kleros.io/smart-contract-workflow * @reviewers: [@clesaege] * @auditors: [] * @bounties: [{duration: 14days, link: https://github.com/kleros/kleros/issues/117, max_payout: 50ETH}] * @deployments: [] */ /* solium-disable error-reason */ /* solium-disable security/no-block-members */ pragma solidity ^0.4.25; /** * @title SortitionSumTreeFactory * @author Enrique Piqueras - <[email protected]> * @dev A factory of trees that keep track of staked values for sortition. */ library SortitionSumTreeFactory { /* Structs */ struct SortitionSumTree { uint K; // The maximum number of childs per node. // We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around. uint[] stack; uint[] nodes; // Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node. mapping(bytes32 => uint) IDsToNodeIndexes; mapping(uint => bytes32) nodeIndexesToIDs; } /* Storage */ struct SortitionSumTrees { mapping(bytes32 => SortitionSumTree) sortitionSumTrees; } /* Public */ /** * @dev Create a sortition sum tree at the specified key. * @param _key The key of the new tree. * @param _K The number of children each node in the tree should have. */ function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) public { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; require(tree.K == 0, "Tree already exists."); require(_K > 1, "K must be greater than one."); tree.K = _K; tree.stack.length = 0; tree.nodes.length = 0; tree.nodes.push(0); } /** * @dev Set a value of a tree. * @param _key The key of the tree. * @param _value The new value. * @param _ID The ID of the value. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) public { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) { // No existing node. if (_value != 0) { // Non zero value. // Append. // Add node. if (tree.stack.length == 0) { // No vacant spots. // Get the index and append the value. treeIndex = tree.nodes.length; tree.nodes.push(_value); // Potentially append a new node and make the parent a sum node. if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; } } else { // Some vacant spot. // Pop the stack and append the value. treeIndex = tree.stack[tree.stack.length - 1]; tree.stack.length--; tree.nodes[treeIndex] = _value; } // Add label. tree.IDsToNodeIndexes[_ID] = treeIndex; tree.nodeIndexesToIDs[treeIndex] = _ID; updateParents(self, _key, treeIndex, true, _value); } } else { // Existing node. if (_value == 0) { // Zero value. // Remove. // Remember value and set to 0. uint value = tree.nodes[treeIndex]; tree.nodes[treeIndex] = 0; // Push to stack. tree.stack.push(treeIndex); // Clear label. delete tree.IDsToNodeIndexes[_ID]; delete tree.nodeIndexesToIDs[treeIndex]; updateParents(self, _key, treeIndex, false, value); } else if (_value != tree.nodes[treeIndex]) { // New, non zero value. // Set. bool plusOrMinus = tree.nodes[treeIndex] <= _value; uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value; tree.nodes[treeIndex] = _value; updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue); } } } /* Public Views */ /** * @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned. * @param _key The key of the tree to get the leaves from. * @param _cursor The pagination cursor. * @param _count The number of items to return. * @return The index at which leaves start, the values of the returned leaves, and whether there are more for pagination. * `O(n)` where * `n` is the maximum number of nodes ever appended. */ function queryLeafs( SortitionSumTrees storage self, bytes32 _key, uint _cursor, uint _count ) public view returns(uint startIndex, uint[] values, bool hasMore) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; // Find the start index. for (uint i = 0; i < tree.nodes.length; i++) { if ((tree.K * i) + 1 >= tree.nodes.length) { startIndex = i; break; } } // Get the values. uint loopStartIndex = startIndex + _cursor; values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count); uint valuesIndex = 0; for (uint j = loopStartIndex; j < tree.nodes.length; j++) { if (valuesIndex < _count) { values[valuesIndex] = tree.nodes[j]; valuesIndex++; } else { hasMore = true; break; } } } /** * @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0. * @param _key The key of the tree. * @param _drawnNumber The drawn number. * @return The drawn ID. * `O(k * log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) public view returns(bytes32 ID) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = 0; uint currentDrawnNumber = _drawnNumber % tree.nodes[0]; while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children. for (uint i = 1; i <= tree.K; i++) { // Loop over children. uint nodeIndex = (tree.K * treeIndex) + i; uint nodeValue = tree.nodes[nodeIndex]; if (currentDrawnNumber >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child. else { // Pick this child. treeIndex = nodeIndex; break; } } ID = tree.nodeIndexesToIDs[treeIndex]; } /** @dev Gets a specified ID's associated value. * @param _key The key of the tree. * @param _ID The ID of the value. * @return The associated value. */ function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) public view returns(uint value) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) value = 0; else value = tree.nodes[treeIndex]; } /* Private */ /** * @dev Update all the parents of a node. * @param _key The key of the tree to update. * @param _treeIndex The index of the node to start from. * @param _plusOrMinus Wether to add (true) or substract (false). * @param _value The value to add or substract. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint parentIndex = _treeIndex; while (parentIndex != 0) { parentIndex = (parentIndex - 1) / tree.K; tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value; } } } contract RNG{ /** @dev Contribute to the reward of a random number. * @param _block Block the random number is linked to. */ function contribute(uint _block) public payable; /** @dev Request a random number. * @param _block Block linked to the request. */ function requestRN(uint _block) public payable { contribute(_block); } /** @dev Get the random number. * @param _block Block the random number is linked to. * @return RN Random Number. If the number is not ready or has not been required 0 instead. */ function getRN(uint _block) public returns (uint RN); /** @dev Get a uncorrelated random number. Act like getRN but give a different number for each sender. * This is to prevent users from getting correlated numbers. * @param _block Block the random number is linked to. * @return RN Random Number. If the number is not ready or has not been required 0 instead. */ function getUncorrelatedRN(uint _block) public returns (uint RN) { uint baseRN = getRN(_block); if (baseRN == 0) return 0; else return uint(keccak256(msg.sender,baseRN)); } } /** @title Arbitrator * Arbitrator abstract contract. * When developing arbitrator contracts we need to: * -Define the functions for dispute creation (createDispute) and appeal (appeal). Don't forget to store the arbitrated contract and the disputeID (which should be unique, use nbDisputes). * -Define the functions for cost display (arbitrationCost and appealCost). * -Allow giving rulings. For this a function must call arbitrable.rule(disputeID, ruling). */ contract Arbitrator { enum DisputeStatus {Waiting, Appealable, Solved} modifier requireArbitrationFee(bytes _extraData) { require(msg.value >= arbitrationCost(_extraData), "Not enough ETH to cover arbitration costs."); _; } modifier requireAppealFee(uint _disputeID, bytes _extraData) { require(msg.value >= appealCost(_disputeID, _extraData), "Not enough ETH to cover appeal costs."); _; } /** @dev To be raised when a dispute is created. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event DisputeCreation(uint indexed _disputeID, Arbitrable indexed _arbitrable); /** @dev To be raised when a dispute can be appealed. * @param _disputeID ID of the dispute. */ event AppealPossible(uint indexed _disputeID, Arbitrable indexed _arbitrable); /** @dev To be raised when the current ruling is appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealDecision(uint indexed _disputeID, Arbitrable indexed _arbitrable); /** @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(_extraData). * @param _choices Amount of choices the arbitrator can make in this dispute. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint _choices, bytes _extraData) public requireArbitrationFee(_extraData) payable returns(uint disputeID) {} /** @dev Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _extraData Can be used to give additional info on the dispute to be created. * @return fee Amount to be paid. */ function arbitrationCost(bytes _extraData) public view returns(uint fee); /** @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give extra info on the appeal. */ function appeal(uint _disputeID, bytes _extraData) public requireAppealFee(_disputeID,_extraData) payable { emit AppealDecision(_disputeID, Arbitrable(msg.sender)); } /** @dev Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give additional info on the dispute to be created. * @return fee Amount to be paid. */ function appealCost(uint _disputeID, bytes _extraData) public view returns(uint fee); /** @dev Compute the start and end of the dispute's current or next appeal period, if possible. * @param _disputeID ID of the dispute. * @return The start and end of the period. */ function appealPeriod(uint _disputeID) public view returns(uint start, uint end) {} /** @dev Return the status of a dispute. * @param _disputeID ID of the dispute to rule. * @return status The status of the dispute. */ function disputeStatus(uint _disputeID) public view returns(DisputeStatus status); /** @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal. * @param _disputeID ID of the dispute. * @return ruling The ruling which has been given or the one which will be given if there is no appeal. */ function currentRuling(uint _disputeID) public view returns(uint ruling); } /** * @title IArbitrable * @author Enrique Piqueras - <[email protected]> * Bug Bounties: This code hasn't undertaken a bug bounty program yet. */ /** @title IArbitrable * Arbitrable interface. * When developing arbitrable contracts, we need to: * -Define the action taken when a ruling is received by the contract. We should do so in executeRuling. * -Allow dispute creation. For this a function must: * -Call arbitrator.createDispute.value(_fee)(_choices,_extraData); * -Create the event Dispute(_arbitrator,_disputeID,_rulingOptions); */ interface IArbitrable { /** @dev To be emmited when meta-evidence is submitted. * @param _metaEvidenceID Unique identifier of meta-evidence. * @param _evidence A link to the meta-evidence JSON. */ event MetaEvidence(uint indexed _metaEvidenceID, string _evidence); /** @dev To be emmited when a dispute is created to link the correct meta-evidence to the disputeID * @param _arbitrator The arbitrator of the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _metaEvidenceID Unique identifier of meta-evidence. * @param _evidenceGroupID Unique identifier of the evidence group that is linked to this dispute. */ event Dispute(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _metaEvidenceID, uint _evidenceGroupID); /** @dev To be raised when evidence are submitted. Should point to the ressource (evidences are not to be stored on chain due to gas considerations). * @param _arbitrator The arbitrator of the contract. * @param _evidenceGroupID Unique identifier of the evidence group the evidence belongs to. * @param _party The address of the party submiting the evidence. Note that 0x0 refers to evidence not submitted by any party. * @param _evidence A URI to the evidence JSON file whose name should be its keccak256 hash followed by .json. */ event Evidence(Arbitrator indexed _arbitrator, uint indexed _evidenceGroupID, address indexed _party, string _evidence); /** @dev To be raised when a ruling is given. * @param _arbitrator The arbitrator giving the ruling. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling The ruling which was given. */ event Ruling(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _ruling); /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) public; } /** @title Arbitrable * Arbitrable abstract contract. * When developing arbitrable contracts, we need to: * -Define the action taken when a ruling is received by the contract. We should do so in executeRuling. * -Allow dispute creation. For this a function must: * -Call arbitrator.createDispute.value(_fee)(_choices,_extraData); * -Create the event Dispute(_arbitrator,_disputeID,_rulingOptions); */ contract Arbitrable is IArbitrable { Arbitrator public arbitrator; bytes public arbitratorExtraData; // Extra data to require particular dispute and appeal behaviour. modifier onlyArbitrator {require(msg.sender == address(arbitrator), "Can only be called by the arbitrator."); _;} /** @dev Constructor. Choose the arbitrator. * @param _arbitrator The arbitrator of the contract. * @param _arbitratorExtraData Extra data for the arbitrator. */ constructor(Arbitrator _arbitrator, bytes _arbitratorExtraData) public { arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; } /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) public onlyArbitrator { emit Ruling(Arbitrator(msg.sender),_disputeID,_ruling); executeRuling(_disputeID,_ruling); } /** @dev Execute a ruling of a dispute. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function executeRuling(uint _disputeID, uint _ruling) internal; } /* Copyright 2016, Jordi Baylina. Slight modification by Clément Lesaege. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) public payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) public onlyController { controller = _newController; } } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = 'MMT_0.2'; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); doTransfer(msg.sender, _to, _amount); return true; } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount ) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount ) internal { if (_amount == 0) { Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0 return; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws var previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // Alerts the token controller of the transfer if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is the standard version to allow backward compatibility. /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken); } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) public onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount ) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) public onlyController { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () public payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public onlyController { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } /** * @title KlerosLiquid * @author Enrique Piqueras - <[email protected]> * @dev The main Kleros contract with dispute resolution logic for the Athena release. */ contract KlerosLiquid is TokenController, Arbitrator { /* Enums */ // General enum Phase { staking, // Stake sum trees can be updated. Pass after `minStakingTime` passes and there is at least one dispute without jurors. generating, // Waiting for a random number. Pass as soon as it is ready. drawing // Jurors can be drawn. Pass after all disputes have jurors or `maxDrawingTime` passes. } // Dispute enum Period { evidence, // Evidence can be submitted. This is also when drawing has to take place. commit, // Jurors commit a hashed vote. This is skipped for courts without hidden votes. vote, // Jurors reveal/cast their vote depending on whether the court has hidden votes or not. appeal, // The dispute can be appealed. execution // Tokens are redistributed and the ruling is executed. } /* Structs */ // General struct Court { uint96 parent; // The parent court. uint[] children; // List of child courts. bool hiddenVotes; // Whether to use commit and reveal or not. uint minStake; // Minimum tokens needed to stake in the court. uint alpha; // Basis point of tokens that are lost when incoherent. uint feeForJuror; // Arbitration fee paid per juror. // The appeal after the one that reaches this number of jurors will go to the parent court if any, otherwise, no more appeals are possible. uint jurorsForCourtJump; uint[4] timesPerPeriod; // The time allotted to each dispute period in the form `timesPerPeriod[period]`. } struct DelayedSetStake { address account; // The address of the juror. uint96 subcourtID; // The ID of the subcourt. uint128 stake; // The new stake. } // Dispute struct Vote { address account; // The address of the juror. bytes32 commit; // The commit of the juror. For courts with hidden votes. uint choice; // The choice of the juror. bool voted; // True if the vote has been cast or revealed, false otherwise. } struct VoteCounter { // The choice with the most votes. Note that in the case of a tie, it is the choice that reached the tied number of votes first. uint winningChoice; mapping(uint => uint) counts; // The sum of votes for each choice in the form `counts[choice]`. bool tied; // True if there is a tie, false otherwise. } struct Dispute { // Note that appeal `0` is equivalent to the first round of the dispute. uint96 subcourtID; // The ID of the subcourt the dispute is in. Arbitrable arbitrated; // The arbitrated arbitrable contract. // The number of choices jurors have when voting. This does not include choice `0` which is reserved for "refuse to arbitrate"/"no ruling". uint numberOfChoices; Period period; // The current period of the dispute. uint lastPeriodChange; // The last time the period was changed. // The votes in the form `votes[appeal][voteID]`. On each round, a new list is pushed and packed with as many empty votes as there are draws. We use `dispute.votes.length` to get the number of appeals plus 1 for the first round. Vote[][] votes; VoteCounter[] voteCounters; // The vote counters in the form `voteCounters[appeal]`. uint[] tokensAtStakePerJuror; // The amount of tokens at stake for each juror in the form `tokensAtStakePerJuror[appeal]`. uint[] totalFeesForJurors; // The total juror fees paid in the form `totalFeesForJurors[appeal]`. uint drawsInRound; // A counter of draws made in the current round. uint commitsInRound; // A counter of commits made in the current round. uint[] votesInEachRound; // A counter of votes made in each round in the form `votesInEachRound[appeal]`. // A counter of vote reward repartitions made in each round in the form `repartitionsInEachRound[appeal]`. uint[] repartitionsInEachRound; uint[] penaltiesInEachRound; // The amount of tokens collected from penalties in each round in the form `penaltiesInEachRound[appeal]`. bool ruled; // True if the ruling has been executed, false otherwise. } // Juror struct Juror { // The IDs of subcourts where the juror has stake path ends. A stake path is a path from the general court to a court the juror directly staked in using `_setStake`. uint96[] subcourtIDs; uint stakedTokens; // The juror's total amount of tokens staked in subcourts. uint lockedTokens; // The juror's total amount of tokens locked in disputes. } /* Events */ /** @dev Emitted when we pass to a new phase. * @param _phase The new phase. */ event NewPhase(Phase _phase); /** @dev Emitted when a dispute passes to a new period. * @param _disputeID The ID of the dispute. * @param _period The new period. */ event NewPeriod(uint indexed _disputeID, Period _period); /** @dev Emitted when a juror's stake is set. * @param _address The address of the juror. * @param _subcourtID The ID of the subcourt at the end of the stake path. * @param _stake The new stake. * @param _newTotalStake The new total stake. */ event StakeSet(address indexed _address, uint _subcourtID, uint128 _stake, uint _newTotalStake); /** @dev Emitted when a juror is drawn. * @param _address The drawn address. * @param _disputeID The ID of the dispute. * @param _appeal The appeal the draw is for. 0 is for the first round. * @param _voteID The vote ID. */ event Draw(address indexed _address, uint indexed _disputeID, uint _appeal, uint _voteID); /** @dev Emitted when a juror wins or loses tokens and ETH from a dispute. * @param _address The juror affected. * @param _disputeID The ID of the dispute. * @param _tokenAmount The amount of tokens won or lost. * @param _ETHAmount The amount of ETH won or lost. */ event TokenAndETHShift(address indexed _address, uint indexed _disputeID, int _tokenAmount, int _ETHAmount); /* Storage */ // General Constants uint public constant MAX_STAKE_PATHS = 4; // The maximum number of stake paths a juror can have. uint public constant MIN_JURORS = 3; // The global default minimum number of jurors in a dispute. uint public constant NON_PAYABLE_AMOUNT = (2 ** 256 - 2) / 2; // An amount higher than the supply of ETH. uint public constant ALPHA_DIVISOR = 1e4; // The number to divide `Court.alpha` by. // General Contracts address public governor; // The governor of the contract. MiniMeToken public pinakion; // The Pinakion token contract. RNG public RNGenerator; // The random number generator contract. // General Dynamic Phase public phase; // The current phase. uint public lastPhaseChange; // The last time the phase was changed. uint public disputesWithoutJurors; // The number of disputes that have not finished drawing jurors. // The block number to get the next random number from. Used so there is at least a 1 block difference from the staking phase. uint public RNBlock; uint public RN; // The current random number. uint public minStakingTime; // The minimum staking time. uint public maxDrawingTime; // The maximum drawing time. // True if insolvent (`balance < stakedTokens || balance < lockedTokens`) token transfers should be blocked. Used to avoid blocking penalties. bool public lockInsolventTransfers = true; // General Storage Court[] public courts; // The subcourts. using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees; // Use library functions for sortition sum trees. SortitionSumTreeFactory.SortitionSumTrees internal sortitionSumTrees; // The sortition sum trees. // The delayed calls to `_setStake`. Used to schedule `_setStake`s when not in the staking phase. mapping(uint => DelayedSetStake) public delayedSetStakes; // The index of the next `delayedSetStakes` item to execute. Starts at 1 because `lastDelayedSetStake` starts at 0. uint public nextDelayedSetStake = 1; uint public lastDelayedSetStake; // The index of the last `delayedSetStakes` item. 0 is skipped because it is the initial value. // Dispute Dispute[] public disputes; // The disputes. // Juror mapping(address => Juror) public jurors; // The jurors. /* Modifiers */ /** @dev Requires a specific phase. * @param _phase The required phase. */ modifier onlyDuringPhase(Phase _phase) {require(phase == _phase); _;} /** @dev Requires a specific period in a dispute. * @param _disputeID The ID of the dispute. * @param _period The required period. */ modifier onlyDuringPeriod(uint _disputeID, Period _period) {require(disputes[_disputeID].period == _period); _;} /** @dev Requires that the sender is the governor. Note that the governor is expected to not be malicious. */ modifier onlyByGovernor() {require(governor == msg.sender); _;} /* Constructor */ /** @dev Constructs the KlerosLiquid contract. * @param _governor The governor's address. * @param _pinakion The address of the token contract. * @param _RNGenerator The address of the RNG contract. * @param _minStakingTime The minimum time that the staking phase should last. * @param _maxDrawingTime The maximum time that the drawing phase should last. * @param _hiddenVotes The `hiddenVotes` property value of the general court. * @param _minStake The `minStake` property value of the general court. * @param _alpha The `alpha` property value of the general court. * @param _feeForJuror The `feeForJuror` property value of the general court. * @param _jurorsForCourtJump The `jurorsForCourtJump` property value of the general court. * @param _timesPerPeriod The `timesPerPeriod` property value of the general court. * @param _sortitionSumTreeK The number of children per node of the general court's sortition sum tree. */ constructor( address _governor, MiniMeToken _pinakion, RNG _RNGenerator, uint _minStakingTime, uint _maxDrawingTime, bool _hiddenVotes, uint _minStake, uint _alpha, uint _feeForJuror, uint _jurorsForCourtJump, uint[4] _timesPerPeriod, uint _sortitionSumTreeK ) public { // Initialize contract. governor = _governor; pinakion = _pinakion; RNGenerator = _RNGenerator; minStakingTime = _minStakingTime; maxDrawingTime = _maxDrawingTime; lastPhaseChange = now; // Create the general court. courts.push(Court({ parent: 0, children: new uint[](0), hiddenVotes: _hiddenVotes, minStake: _minStake, alpha: _alpha, feeForJuror: _feeForJuror, jurorsForCourtJump: _jurorsForCourtJump, timesPerPeriod: _timesPerPeriod })); sortitionSumTrees.createTree(bytes32(0), _sortitionSumTreeK); } /* External */ /** @dev Lets the governor call anything on behalf of the contract. * @param _destination The destination of the call. * @param _amount The value sent with the call. * @param _data The data sent with the call. */ function executeGovernorProposal(address _destination, uint _amount, bytes _data) external onlyByGovernor { require(_destination.call.value(_amount)(_data)); // solium-disable-line security/no-call-value } /** @dev Changes the `governor` storage variable. * @param _governor The new value for the `governor` storage variable. */ function changeGovernor(address _governor) external onlyByGovernor { governor = _governor; } /** @dev Changes the `pinakion` storage variable. * @param _pinakion The new value for the `pinakion` storage variable. */ function changePinakion(MiniMeToken _pinakion) external onlyByGovernor { pinakion = _pinakion; } /** @dev Changes the `RNGenerator` storage variable. * @param _RNGenerator The new value for the `RNGenerator` storage variable. */ function changeRNGenerator(RNG _RNGenerator) external onlyByGovernor { RNGenerator = _RNGenerator; if (phase == Phase.generating) { RNBlock = block.number + 1; RNGenerator.requestRN(RNBlock); } } /** @dev Changes the `minStakingTime` storage variable. * @param _minStakingTime The new value for the `minStakingTime` storage variable. */ function changeMinStakingTime(uint _minStakingTime) external onlyByGovernor { minStakingTime = _minStakingTime; } /** @dev Changes the `maxDrawingTime` storage variable. * @param _maxDrawingTime The new value for the `maxDrawingTime` storage variable. */ function changeMaxDrawingTime(uint _maxDrawingTime) external onlyByGovernor { maxDrawingTime = _maxDrawingTime; } /** @dev Creates a subcourt under a specified parent court. * @param _parent The `parent` property value of the subcourt. * @param _hiddenVotes The `hiddenVotes` property value of the subcourt. * @param _minStake The `minStake` property value of the subcourt. * @param _alpha The `alpha` property value of the subcourt. * @param _feeForJuror The `feeForJuror` property value of the subcourt. * @param _jurorsForCourtJump The `jurorsForCourtJump` property value of the subcourt. * @param _timesPerPeriod The `timesPerPeriod` property value of the subcourt. * @param _sortitionSumTreeK The number of children per node of the subcourt's sortition sum tree. */ function createSubcourt( uint96 _parent, bool _hiddenVotes, uint _minStake, uint _alpha, uint _feeForJuror, uint _jurorsForCourtJump, uint[4] _timesPerPeriod, uint _sortitionSumTreeK ) external onlyByGovernor { require(courts[_parent].minStake <= _minStake, "A subcourt cannot be a child of a subcourt with a higher minimum stake."); // Create the subcourt. uint96 subcourtID = uint96( courts.push(Court({ parent: _parent, children: new uint[](0), hiddenVotes: _hiddenVotes, minStake: _minStake, alpha: _alpha, feeForJuror: _feeForJuror, jurorsForCourtJump: _jurorsForCourtJump, timesPerPeriod: _timesPerPeriod })) - 1 ); sortitionSumTrees.createTree(bytes32(subcourtID), _sortitionSumTreeK); // Update the parent. courts[_parent].children.push(subcourtID); } /** @dev Changes the `minStake` property value of a specified subcourt. Don't set to a value lower than its parent's `minStake` property value. * @param _subcourtID The ID of the subcourt. * @param _minStake The new value for the `minStake` property value. */ function changeSubcourtMinStake(uint96 _subcourtID, uint _minStake) external onlyByGovernor { require(_subcourtID == 0 || courts[courts[_subcourtID].parent].minStake <= _minStake); for (uint i = 0; i < courts[_subcourtID].children.length; i++) { require( courts[courts[_subcourtID].children[i]].minStake >= _minStake, "A subcourt cannot be the parent of a subcourt with a lower minimum stake." ); } courts[_subcourtID].minStake = _minStake; } /** @dev Changes the `alpha` property value of a specified subcourt. * @param _subcourtID The ID of the subcourt. * @param _alpha The new value for the `alpha` property value. */ function changeSubcourtAlpha(uint96 _subcourtID, uint _alpha) external onlyByGovernor { courts[_subcourtID].alpha = _alpha; } /** @dev Changes the `feeForJuror` property value of a specified subcourt. * @param _subcourtID The ID of the subcourt. * @param _feeForJuror The new value for the `feeForJuror` property value. */ function changeSubcourtJurorFee(uint96 _subcourtID, uint _feeForJuror) external onlyByGovernor { courts[_subcourtID].feeForJuror = _feeForJuror; } /** @dev Changes the `jurorsForCourtJump` property value of a specified subcourt. * @param _subcourtID The ID of the subcourt. * @param _jurorsForCourtJump The new value for the `jurorsForCourtJump` property value. */ function changeSubcourtJurorsForJump(uint96 _subcourtID, uint _jurorsForCourtJump) external onlyByGovernor { courts[_subcourtID].jurorsForCourtJump = _jurorsForCourtJump; } /** @dev Changes the `timesPerPeriod` property value of a specified subcourt. * @param _subcourtID The ID of the subcourt. * @param _timesPerPeriod The new value for the `timesPerPeriod` property value. */ function changeSubcourtTimesPerPeriod(uint96 _subcourtID, uint[4] _timesPerPeriod) external onlyByGovernor { courts[_subcourtID].timesPerPeriod = _timesPerPeriod; } /** @dev Passes the phase. TRUSTED */ function passPhase() external { if (phase == Phase.staking) { require(now - lastPhaseChange >= minStakingTime, "The minimum staking time has not passed yet."); require(disputesWithoutJurors > 0, "There are no disputes that need jurors."); RNBlock = block.number + 1; RNGenerator.requestRN(RNBlock); phase = Phase.generating; } else if (phase == Phase.generating) { RN = RNGenerator.getUncorrelatedRN(RNBlock); require(RN != 0, "Random number is not ready yet."); phase = Phase.drawing; } else if (phase == Phase.drawing) { require(disputesWithoutJurors == 0 || now - lastPhaseChange >= maxDrawingTime, "There are still disputes without jurors and the maximum drawing time has not passed yet."); phase = Phase.staking; } lastPhaseChange = now; emit NewPhase(phase); } /** @dev Passes the period of a specified dispute. * @param _disputeID The ID of the dispute. */ function passPeriod(uint _disputeID) external { Dispute storage dispute = disputes[_disputeID]; if (dispute.period == Period.evidence) { require( dispute.votes.length > 1 || now - dispute.lastPeriodChange >= courts[dispute.subcourtID].timesPerPeriod[uint(dispute.period)], "The evidence period time has not passed yet and it is not an appeal." ); require(dispute.drawsInRound == dispute.votes[dispute.votes.length - 1].length, "The dispute has not finished drawing yet."); dispute.period = courts[dispute.subcourtID].hiddenVotes ? Period.commit : Period.vote; } else if (dispute.period == Period.commit) { require( now - dispute.lastPeriodChange >= courts[dispute.subcourtID].timesPerPeriod[uint(dispute.period)] || dispute.commitsInRound == dispute.votes[dispute.votes.length - 1].length, "The commit period time has not passed yet and not every juror has committed yet." ); dispute.period = Period.vote; } else if (dispute.period == Period.vote) { require( now - dispute.lastPeriodChange >= courts[dispute.subcourtID].timesPerPeriod[uint(dispute.period)] || dispute.votesInEachRound[dispute.votes.length - 1] == dispute.votes[dispute.votes.length - 1].length, "The vote period time has not passed yet and not every juror has voted yet." ); dispute.period = Period.appeal; emit AppealPossible(_disputeID, dispute.arbitrated); } else if (dispute.period == Period.appeal) { require(now - dispute.lastPeriodChange >= courts[dispute.subcourtID].timesPerPeriod[uint(dispute.period)], "The appeal period time has not passed yet."); dispute.period = Period.execution; } else if (dispute.period == Period.execution) { revert("The dispute is already in the last period."); } dispute.lastPeriodChange = now; emit NewPeriod(_disputeID, dispute.period); } /** @dev Sets the caller's stake in a subcourt. * @param _subcourtID The ID of the subcourt. * @param _stake The new stake. */ function setStake(uint96 _subcourtID, uint128 _stake) external { require(_setStake(msg.sender, _subcourtID, _stake)); } /** @dev Executes the next delayed set stakes. * @param _iterations The number of delayed set stakes to execute. */ function executeDelayedSetStakes(uint _iterations) external onlyDuringPhase(Phase.staking) { uint actualIterations = (nextDelayedSetStake + _iterations) - 1 > lastDelayedSetStake ? (lastDelayedSetStake - nextDelayedSetStake) + 1 : _iterations; uint newNextDelayedSetStake = nextDelayedSetStake + actualIterations; require(newNextDelayedSetStake >= nextDelayedSetStake); for (uint i = nextDelayedSetStake; i < newNextDelayedSetStake; i++) { DelayedSetStake storage delayedSetStake = delayedSetStakes[i]; _setStake(delayedSetStake.account, delayedSetStake.subcourtID, delayedSetStake.stake); delete delayedSetStakes[i]; } nextDelayedSetStake = newNextDelayedSetStake; } /** @dev Draws jurors for a dispute. Can be called in parts. * `O(n * k * log_k(j))` where * `n` is the number of iterations to run, * `k` is the number of children per node of the dispute's court's sortition sum tree, * and `j` is the maximum number of jurors that ever staked in it simultaneously. * @param _disputeID The ID of the dispute. * @param _iterations The number of iterations to run. */ function drawJurors( uint _disputeID, uint _iterations ) external onlyDuringPhase(Phase.drawing) onlyDuringPeriod(_disputeID, Period.evidence) { Dispute storage dispute = disputes[_disputeID]; uint endIndex = dispute.drawsInRound + _iterations; require(endIndex >= dispute.drawsInRound); // Avoid going out of range. if (endIndex > dispute.votes[dispute.votes.length - 1].length) endIndex = dispute.votes[dispute.votes.length - 1].length; for (uint i = dispute.drawsInRound; i < endIndex; i++) { // Draw from sortition tree. ( address drawnAddress, uint subcourtID ) = stakePathIDToAccountAndSubcourtID(sortitionSumTrees.draw(bytes32(dispute.subcourtID), uint(keccak256(RN, _disputeID, i)))); // Save the vote. dispute.votes[dispute.votes.length - 1][i].account = drawnAddress; jurors[drawnAddress].lockedTokens += dispute.tokensAtStakePerJuror[dispute.tokensAtStakePerJuror.length - 1]; emit Draw(drawnAddress, _disputeID, dispute.votes.length - 1, i); // If dispute is fully drawn. if (i == dispute.votes[dispute.votes.length - 1].length - 1) disputesWithoutJurors--; } dispute.drawsInRound = endIndex; } /** @dev Sets the caller's commit for the specified votes. * `O(n)` where * `n` is the number of votes. * @param _disputeID The ID of the dispute. * @param _voteIDs The IDs of the votes. * @param _commit The commit. */ function castCommit(uint _disputeID, uint[] _voteIDs, bytes32 _commit) external onlyDuringPeriod(_disputeID, Period.commit) { Dispute storage dispute = disputes[_disputeID]; require(_commit != bytes32(0)); for (uint i = 0; i < _voteIDs.length; i++) { require(dispute.votes[dispute.votes.length - 1][_voteIDs[i]].account == msg.sender, "The caller has to own the vote."); require(dispute.votes[dispute.votes.length - 1][_voteIDs[i]].commit == bytes32(0), "Already committed this vote."); dispute.votes[dispute.votes.length - 1][_voteIDs[i]].commit = _commit; } dispute.commitsInRound += _voteIDs.length; } /** @dev Sets the caller's choices for the specified votes. * `O(n)` where * `n` is the number of votes. * @param _disputeID The ID of the dispute. * @param _voteIDs The IDs of the votes. * @param _choice The choice. * @param _salt The salt for the commit if the votes were hidden. */ function castVote(uint _disputeID, uint[] _voteIDs, uint _choice, uint _salt) external onlyDuringPeriod(_disputeID, Period.vote) { Dispute storage dispute = disputes[_disputeID]; require(_voteIDs.length > 0); require(_choice <= dispute.numberOfChoices, "The choice has to be less than or equal to the number of choices for the dispute."); // Save the votes. for (uint i = 0; i < _voteIDs.length; i++) { require(dispute.votes[dispute.votes.length - 1][_voteIDs[i]].account == msg.sender, "The caller has to own the vote."); require( !courts[dispute.subcourtID].hiddenVotes || dispute.votes[dispute.votes.length - 1][_voteIDs[i]].commit == keccak256(_choice, _salt), "The commit must match the choice in subcourts with hidden votes." ); require(!dispute.votes[dispute.votes.length - 1][_voteIDs[i]].voted, "Vote already cast."); dispute.votes[dispute.votes.length - 1][_voteIDs[i]].choice = _choice; dispute.votes[dispute.votes.length - 1][_voteIDs[i]].voted = true; } dispute.votesInEachRound[dispute.votes.length - 1] += _voteIDs.length; // Update winning choice. VoteCounter storage voteCounter = dispute.voteCounters[dispute.voteCounters.length - 1]; voteCounter.counts[_choice] += _voteIDs.length; if (_choice == voteCounter.winningChoice) { // Voted for the winning choice. if (voteCounter.tied) voteCounter.tied = false; // Potentially broke tie. } else { // Voted for another choice. if (voteCounter.counts[_choice] == voteCounter.counts[voteCounter.winningChoice]) { // Tie. if (!voteCounter.tied) voteCounter.tied = true; } else if (voteCounter.counts[_choice] > voteCounter.counts[voteCounter.winningChoice]) { // New winner. voteCounter.winningChoice = _choice; voteCounter.tied = false; } } } /** @dev Computes the token and ETH rewards for a specified appeal in a specified dispute. * @param _disputeID The ID of the dispute. * @param _appeal The appeal. * @return The token and ETH rewards. */ function computeTokenAndETHRewards(uint _disputeID, uint _appeal) private view returns(uint tokenReward, uint ETHReward) { Dispute storage dispute = disputes[_disputeID]; // Distribute penalties and arbitration fees. if (dispute.voteCounters[dispute.voteCounters.length - 1].tied) { // Distribute penalties and fees evenly between active jurors. uint activeCount = dispute.votesInEachRound[_appeal]; if (activeCount > 0) { tokenReward = dispute.penaltiesInEachRound[_appeal] / activeCount; ETHReward = dispute.totalFeesForJurors[_appeal] / activeCount; } else { tokenReward = 0; ETHReward = 0; } } else { // Distribute penalties and fees evenly between coherent jurors. uint winningChoice = dispute.voteCounters[dispute.voteCounters.length - 1].winningChoice; uint coherentCount = dispute.voteCounters[_appeal].counts[winningChoice]; tokenReward = dispute.penaltiesInEachRound[_appeal] / coherentCount; ETHReward = dispute.totalFeesForJurors[_appeal] / coherentCount; } } /** @dev Repartitions tokens and ETH for a specified appeal in a specified dispute. Can be called in parts. * `O(i + u * n * (n + p * log_k(j)))` where * `i` is the number of iterations to run, * `u` is the number of jurors that need to be unstaked, * `n` is the maximum number of subcourts one of these jurors has staked in, * `p` is the depth of the subcourt tree, * `k` is the minimum number of children per node of one of these subcourts' sortition sum tree, * and `j` is the maximum number of jurors that ever staked in one of these subcourts simultaneously. * @param _disputeID The ID of the dispute. * @param _appeal The appeal. * @param _iterations The number of iterations to run. */ function execute(uint _disputeID, uint _appeal, uint _iterations) external onlyDuringPeriod(_disputeID, Period.execution) { lockInsolventTransfers = false; Dispute storage dispute = disputes[_disputeID]; uint end = dispute.repartitionsInEachRound[_appeal] + _iterations; require(end >= dispute.repartitionsInEachRound[_appeal]); uint penaltiesInRoundCache = dispute.penaltiesInEachRound[_appeal]; // For saving gas. (uint tokenReward, uint ETHReward) = (0, 0); // Avoid going out of range. if ( !dispute.voteCounters[dispute.voteCounters.length - 1].tied && dispute.voteCounters[_appeal].counts[dispute.voteCounters[dispute.voteCounters.length - 1].winningChoice] == 0 ) { // We loop over the votes once as there are no rewards because it is not a tie and no one in this round is coherent with the final outcome. if (end > dispute.votes[_appeal].length) end = dispute.votes[_appeal].length; } else { // We loop over the votes twice, first to collect penalties, and second to distribute them as rewards along with arbitration fees. (tokenReward, ETHReward) = dispute.repartitionsInEachRound[_appeal] >= dispute.votes[_appeal].length ? computeTokenAndETHRewards(_disputeID, _appeal) : (0, 0); // Compute rewards if rewarding. if (end > dispute.votes[_appeal].length * 2) end = dispute.votes[_appeal].length * 2; } for (uint i = dispute.repartitionsInEachRound[_appeal]; i < end; i++) { Vote storage vote = dispute.votes[_appeal][i % dispute.votes[_appeal].length]; if ( vote.voted && (vote.choice == dispute.voteCounters[dispute.voteCounters.length - 1].winningChoice || dispute.voteCounters[dispute.voteCounters.length - 1].tied) ) { // Juror was active, and voted coherently or it was a tie. if (i >= dispute.votes[_appeal].length) { // Only execute in the second half of the iterations. // Reward. pinakion.transfer(vote.account, tokenReward); // Intentional use to avoid blocking. vote.account.send(ETHReward); // solium-disable-line security/no-send emit TokenAndETHShift(vote.account, _disputeID, int(tokenReward), int(ETHReward)); jurors[vote.account].lockedTokens -= dispute.tokensAtStakePerJuror[_appeal]; } } else { // Juror was inactive, or voted incoherently and it was not a tie. if (i < dispute.votes[_appeal].length) { // Only execute in the first half of the iterations. // Penalize. uint penalty = dispute.tokensAtStakePerJuror[_appeal] > pinakion.balanceOf(vote.account) ? pinakion.balanceOf(vote.account) : dispute.tokensAtStakePerJuror[_appeal]; pinakion.transferFrom(vote.account, this, penalty); emit TokenAndETHShift(vote.account, _disputeID, -int(penalty), 0); penaltiesInRoundCache += penalty; jurors[vote.account].lockedTokens -= dispute.tokensAtStakePerJuror[_appeal]; // Unstake juror if his penalty made balance less than his total stake or if he lost due to inactivity. if (pinakion.balanceOf(vote.account) < jurors[vote.account].stakedTokens || !vote.voted) for (uint j = 0; j < jurors[vote.account].subcourtIDs.length; j++) _setStake(vote.account, jurors[vote.account].subcourtIDs[j], 0); } } if (i == dispute.votes[_appeal].length - 1) { // Send fees and tokens to the governor if no one was coherent. if (dispute.votesInEachRound[_appeal] == 0 || !dispute.voteCounters[dispute.voteCounters.length - 1].tied && dispute.voteCounters[_appeal].counts[dispute.voteCounters[dispute.voteCounters.length - 1].winningChoice] == 0) { // Intentional use to avoid blocking. governor.send(dispute.totalFeesForJurors[_appeal]); // solium-disable-line security/no-send pinakion.transfer(governor, penaltiesInRoundCache); } else if (i + 1 < end) { // Compute rewards because we are going into rewarding. dispute.penaltiesInEachRound[_appeal] = penaltiesInRoundCache; (tokenReward, ETHReward) = computeTokenAndETHRewards(_disputeID, _appeal); } } } if (dispute.penaltiesInEachRound[_appeal] != penaltiesInRoundCache) dispute.penaltiesInEachRound[_appeal] = penaltiesInRoundCache; dispute.repartitionsInEachRound[_appeal] = end; lockInsolventTransfers = true; } /** @dev Executes a specified dispute's ruling. UNTRUSTED. * @param _disputeID The ID of the dispute. */ function executeRuling(uint _disputeID) external onlyDuringPeriod(_disputeID, Period.execution) { Dispute storage dispute = disputes[_disputeID]; require(!dispute.ruled, "Ruling already executed."); dispute.ruled = true; uint winningChoice = dispute.voteCounters[dispute.voteCounters.length - 1].tied ? 0 : dispute.voteCounters[dispute.voteCounters.length - 1].winningChoice; dispute.arbitrated.rule(_disputeID, winningChoice); } /* Public */ /** @dev Creates a dispute. Must be called by the arbitrable contract. * @param _numberOfChoices Number of choices to choose from in the dispute to be created. * @param _extraData Additional info about the dispute to be created. We use it to pass the ID of the subcourt to create the dispute in (first 32 bytes) and the minimum number of jurors required (next 32 bytes). * @return The ID of the created dispute. */ function createDispute( uint _numberOfChoices, bytes _extraData ) public payable requireArbitrationFee(_extraData) returns(uint disputeID) { (uint96 subcourtID, uint minJurors) = extraDataToSubcourtIDAndMinJurors(_extraData); disputeID = disputes.length++; Dispute storage dispute = disputes[disputeID]; dispute.subcourtID = subcourtID; dispute.arbitrated = Arbitrable(msg.sender); dispute.numberOfChoices = _numberOfChoices; dispute.period = Period.evidence; dispute.lastPeriodChange = now; // As many votes that can be afforded by the provided funds. dispute.votes[dispute.votes.length++].length = msg.value / courts[dispute.subcourtID].feeForJuror; dispute.voteCounters[dispute.voteCounters.length++].tied = true; dispute.tokensAtStakePerJuror.push((courts[dispute.subcourtID].minStake * courts[dispute.subcourtID].alpha) / ALPHA_DIVISOR); dispute.totalFeesForJurors.push(msg.value); dispute.votesInEachRound.push(0); dispute.repartitionsInEachRound.push(0); dispute.penaltiesInEachRound.push(0); disputesWithoutJurors++; emit DisputeCreation(disputeID, Arbitrable(msg.sender)); } /** @dev Appeals the ruling of a specified dispute. * @param _disputeID The ID of the dispute. * @param _extraData Additional info about the appeal. Not used by this contract. */ function appeal( uint _disputeID, bytes _extraData ) public payable requireAppealFee(_disputeID, _extraData) onlyDuringPeriod(_disputeID, Period.appeal) { Dispute storage dispute = disputes[_disputeID]; require( msg.sender == address(dispute.arbitrated), "Can only be called by the arbitrable contract." ); if (dispute.votes[dispute.votes.length - 1].length >= courts[dispute.subcourtID].jurorsForCourtJump) // Jump to parent subcourt. dispute.subcourtID = courts[dispute.subcourtID].parent; dispute.period = Period.evidence; dispute.lastPeriodChange = now; // As many votes that can be afforded by the provided funds. dispute.votes[dispute.votes.length++].length = msg.value / courts[dispute.subcourtID].feeForJuror; dispute.voteCounters[dispute.voteCounters.length++].tied = true; dispute.tokensAtStakePerJuror.push((courts[dispute.subcourtID].minStake * courts[dispute.subcourtID].alpha) / ALPHA_DIVISOR); dispute.totalFeesForJurors.push(msg.value); dispute.drawsInRound = 0; dispute.commitsInRound = 0; dispute.votesInEachRound.push(0); dispute.repartitionsInEachRound.push(0); dispute.penaltiesInEachRound.push(0); disputesWithoutJurors++; emit AppealDecision(_disputeID, Arbitrable(msg.sender)); } /** @dev Called when `_owner` sends ether to the MiniMe Token contract. * @param _owner The address that sent the ether to create tokens. * @return Whether the operation should be allowed or not. */ function proxyPayment(address _owner) public payable returns(bool allowed) { allowed = false; } /** @dev Notifies the controller about a token transfer allowing the controller to react if desired. * @param _from The origin of the transfer. * @param _to The destination of the transfer. * @param _amount The amount of the transfer. * @return Whether the operation should be allowed or not. */ function onTransfer(address _from, address _to, uint _amount) public returns(bool allowed) { if (lockInsolventTransfers) { // Never block penalties or rewards. uint newBalance = pinakion.balanceOf(_from) - _amount; if (newBalance < jurors[_from].stakedTokens || newBalance < jurors[_from].lockedTokens) return false; } allowed = true; } /** @dev Notifies the controller about an approval allowing the controller to react if desired. * @param _owner The address that calls `approve()`. * @param _spender The spender in the `approve()` call. * @param _amount The amount in the `approve()` call. * @return Whether the operation should be allowed or not. */ function onApprove(address _owner, address _spender, uint _amount) public returns(bool allowed) { allowed = true; } /* Public Views */ /** @dev Gets the cost of arbitration in a specified subcourt. * @param _extraData Additional info about the dispute. We use it to pass the ID of the subcourt to create the dispute in (first 32 bytes) and the minimum number of jurors required (next 32 bytes). * @return The cost. */ function arbitrationCost(bytes _extraData) public view returns(uint cost) { (uint96 subcourtID, uint minJurors) = extraDataToSubcourtIDAndMinJurors(_extraData); cost = courts[subcourtID].feeForJuror * minJurors; } /** @dev Gets the cost of appealing a specified dispute. * @param _disputeID The ID of the dispute. * @param _extraData Additional info about the appeal. Not used by this contract. * @return The cost. */ function appealCost(uint _disputeID, bytes _extraData) public view returns(uint cost) { Dispute storage dispute = disputes[_disputeID]; uint lastNumberOfJurors = dispute.votes[dispute.votes.length - 1].length; if (lastNumberOfJurors >= courts[dispute.subcourtID].jurorsForCourtJump) { // Jump to parent subcourt. if (dispute.subcourtID == 0) // Already in the general court. cost = NON_PAYABLE_AMOUNT; else // Get the cost of the parent subcourt. cost = courts[courts[dispute.subcourtID].parent].feeForJuror * ((lastNumberOfJurors * 2) + 1); } else // Stay in current subcourt. cost = courts[dispute.subcourtID].feeForJuror * ((lastNumberOfJurors * 2) + 1); } /** @dev Gets the start and end of a specified dispute's current appeal period. * @param _disputeID The ID of the dispute. * @return The start and end of the appeal period. */ function appealPeriod(uint _disputeID) public view returns(uint start, uint end) { Dispute storage dispute = disputes[_disputeID]; if (dispute.period == Period.appeal) { start = dispute.lastPeriodChange; end = dispute.lastPeriodChange + courts[dispute.subcourtID].timesPerPeriod[uint(Period.appeal)]; } else { start = 0; end = 0; } } /** @dev Gets the status of a specified dispute. * @param _disputeID The ID of the dispute. * @return The status. */ function disputeStatus(uint _disputeID) public view returns(DisputeStatus status) { Dispute storage dispute = disputes[_disputeID]; if (dispute.period < Period.appeal) status = DisputeStatus.Waiting; else if (dispute.period < Period.execution) status = DisputeStatus.Appealable; else status = DisputeStatus.Solved; } /** @dev Gets the current ruling of a specified dispute. * @param _disputeID The ID of the dispute. * @return The current ruling. */ function currentRuling(uint _disputeID) public view returns(uint ruling) { Dispute storage dispute = disputes[_disputeID]; ruling = dispute.voteCounters[dispute.voteCounters.length - 1].tied ? 0 : dispute.voteCounters[dispute.voteCounters.length - 1].winningChoice; } /* Internal */ /** @dev Sets the specified juror's stake in a subcourt. * `O(n + p * log_k(j))` where * `n` is the number of subcourts the juror has staked in, * `p` is the depth of the subcourt tree, * `k` is the minimum number of children per node of one of these subcourts' sortition sum tree, * and `j` is the maximum number of jurors that ever staked in one of these subcourts simultaneously. * @param _account The address of the juror. * @param _subcourtID The ID of the subcourt. * @param _stake The new stake. * @return True if the call succeeded, false otherwise. */ function _setStake(address _account, uint96 _subcourtID, uint128 _stake) internal returns(bool succeeded) { if (!(_subcourtID < courts.length)) return false; // Delayed action logic. if (phase != Phase.staking) { delayedSetStakes[++lastDelayedSetStake] = DelayedSetStake({ account: _account, subcourtID: _subcourtID, stake: _stake }); return true; } if (!(_stake == 0 || courts[_subcourtID].minStake <= _stake)) return false; // The juror's stake cannot be lower than the minimum stake for the subcourt. Juror storage juror = jurors[_account]; bytes32 stakePathID = accountAndSubcourtIDToStakePathID(_account, _subcourtID); uint currentStake = sortitionSumTrees.stakeOf(bytes32(_subcourtID), stakePathID); if (!(_stake == 0 || currentStake > 0 || juror.subcourtIDs.length < MAX_STAKE_PATHS)) return false; // Maximum stake paths reached. uint newTotalStake = juror.stakedTokens - currentStake + _stake; // Can't overflow because _stake is a uint128. if (!(_stake == 0 || pinakion.balanceOf(_account) >= newTotalStake)) return false; // The juror's total amount of staked tokens cannot be higher than the juror's balance. // Update juror's records. juror.stakedTokens = newTotalStake; if (_stake == 0) { for (uint i = 0; i < juror.subcourtIDs.length; i++) if (juror.subcourtIDs[i] == _subcourtID) { juror.subcourtIDs[i] = juror.subcourtIDs[juror.subcourtIDs.length - 1]; juror.subcourtIDs.length--; break; } } else if (currentStake == 0) juror.subcourtIDs.push(_subcourtID); // Update subcourt parents. bool finished = false; uint currentSubcourtID = _subcourtID; while (!finished) { sortitionSumTrees.set(bytes32(currentSubcourtID), _stake, stakePathID); if (currentSubcourtID == 0) finished = true; else currentSubcourtID = courts[currentSubcourtID].parent; } emit StakeSet(_account, _subcourtID, _stake, newTotalStake); return true; } /** @dev Gets a subcourt ID and the minimum number of jurors required from a specified extra data bytes array. * @param _extraData The extra data bytes array. The first 32 bytes are the subcourt ID and the next 32 bytes are the minimum number of jurors. * @return The subcourt ID and the minimum number of jurors required. */ function extraDataToSubcourtIDAndMinJurors(bytes _extraData) internal view returns (uint96 subcourtID, uint minJurors) { if (_extraData.length >= 64) { assembly { // solium-disable-line security/no-inline-assembly subcourtID := mload(add(_extraData, 0x20)) minJurors := mload(add(_extraData, 0x40)) } if (subcourtID >= courts.length) subcourtID = 0; if (minJurors == 0) minJurors = MIN_JURORS; } else { subcourtID = 0; minJurors = MIN_JURORS; } } /** @dev Packs an account and a subcourt ID into a stake path ID. * @param _account The account to pack. * @param _subcourtID The subcourt ID to pack. * @return The stake path ID. */ function accountAndSubcourtIDToStakePathID(address _account, uint96 _subcourtID) internal pure returns (bytes32 stakePathID) { assembly { // solium-disable-line security/no-inline-assembly let ptr := mload(0x40) for { let i := 0x00 } lt(i, 0x14) { i := add(i, 0x01) } { mstore8(add(ptr, i), byte(add(0x0c, i), _account)) } for { let i := 0x14 } lt(i, 0x20) { i := add(i, 0x01) } { mstore8(add(ptr, i), byte(i, _subcourtID)) } stakePathID := mload(ptr) } } /** @dev Unpacks a stake path ID into an account and a subcourt ID. * @param _stakePathID The stake path ID to unpack. * @return The account and subcourt ID. */ function stakePathIDToAccountAndSubcourtID(bytes32 _stakePathID) internal pure returns (address account, uint96 subcourtID) { assembly { // solium-disable-line security/no-inline-assembly let ptr := mload(0x40) for { let i := 0x00 } lt(i, 0x14) { i := add(i, 0x01) } { mstore8(add(add(ptr, 0x0c), i), byte(i, _stakePathID)) } account := mload(ptr) subcourtID := _stakePathID } } /* Interface Views */ /** @dev Gets a specified subcourt's non primitive properties. * @param _subcourtID The ID of the subcourt. * @return The subcourt's non primitive properties. */ function getSubcourt(uint96 _subcourtID) external view returns( uint[] children, uint[4] timesPerPeriod ) { Court storage subcourt = courts[_subcourtID]; children = subcourt.children; timesPerPeriod = subcourt.timesPerPeriod; } /** @dev Gets a specified vote for a specified appeal in a specified dispute. * @param _disputeID The ID of the dispute. * @param _appeal The appeal. * @param _voteID The ID of the vote. * @return The vote. */ function getVote(uint _disputeID, uint _appeal, uint _voteID) external view returns( address account, bytes32 commit, uint choice, bool voted ) { Vote storage vote = disputes[_disputeID].votes[_appeal][_voteID]; account = vote.account; commit = vote.commit; choice = vote.choice; voted = vote.voted; } /** @dev Gets the vote counter for a specified appeal in a specified dispute. * Note: This function is only to be used by the interface and it won't work if the number of choices is too high. * @param _disputeID The ID of the dispute. * @param _appeal The appeal. * @return The vote counter. * `O(n)` where * `n` is the number of choices of the dispute. */ function getVoteCounter(uint _disputeID, uint _appeal) external view returns( uint winningChoice, uint[] counts, bool tied ) { Dispute storage dispute = disputes[_disputeID]; VoteCounter storage voteCounter = dispute.voteCounters[_appeal]; winningChoice = voteCounter.winningChoice; counts = new uint[](dispute.numberOfChoices + 1); for (uint i = 0; i <= dispute.numberOfChoices; i++) counts[i] = voteCounter.counts[i]; tied = voteCounter.tied; } /** @dev Gets a specified dispute's non primitive properties. * @param _disputeID The ID of the dispute. * @return The dispute's non primitive properties. * `O(a)` where * `a` is the number of appeals of the dispute. */ function getDispute(uint _disputeID) external view returns( uint[] votesLengths, uint[] tokensAtStakePerJuror, uint[] totalFeesForJurors, uint[] votesInEachRound, uint[] repartitionsInEachRound, uint[] penaltiesInEachRound ) { Dispute storage dispute = disputes[_disputeID]; votesLengths = new uint[](dispute.votes.length); for (uint i = 0; i < dispute.votes.length; i++) votesLengths[i] = dispute.votes[i].length; tokensAtStakePerJuror = dispute.tokensAtStakePerJuror; totalFeesForJurors = dispute.totalFeesForJurors; votesInEachRound = dispute.votesInEachRound; repartitionsInEachRound = dispute.repartitionsInEachRound; penaltiesInEachRound = dispute.penaltiesInEachRound; } /** @dev Gets a specified juror's non primitive properties. * @param _account The address of the juror. * @return The juror's non primitive properties. */ function getJuror(address _account) external view returns( uint96[] subcourtIDs ) { Juror storage juror = jurors[_account]; subcourtIDs = juror.subcourtIDs; } /** @dev Gets the stake of a specified juror in a specified subcourt. * @param _account The address of the juror. * @param _subcourtID The ID of the subcourt. * @return The stake. */ function stakeOf(address _account, uint96 _subcourtID) external view returns(uint stake) { return sortitionSumTrees.stakeOf(bytes32(_subcourtID), accountAndSubcourtIDToStakePathID(_account, _subcourtID)); } }
* @dev Changes the `RNGenerator` storage variable. @param _RNGenerator The new value for the `RNGenerator` storage variable./
function changeRNGenerator(RNG _RNGenerator) external onlyByGovernor { RNGenerator = _RNGenerator; if (phase == Phase.generating) { RNBlock = block.number + 1; RNGenerator.requestRN(RNBlock); } }
5,495,841
[ 1, 7173, 326, 1375, 54, 50, 3908, 68, 2502, 2190, 18, 282, 389, 54, 50, 3908, 1021, 394, 460, 364, 326, 1375, 54, 50, 3908, 68, 2502, 2190, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2549, 54, 50, 3908, 12, 54, 4960, 389, 54, 50, 3908, 13, 3903, 1338, 858, 43, 1643, 29561, 288, 203, 3639, 534, 50, 3908, 273, 389, 54, 50, 3908, 31, 203, 3639, 309, 261, 13961, 422, 19459, 18, 3441, 1776, 13, 288, 203, 5411, 534, 50, 1768, 273, 1203, 18, 2696, 397, 404, 31, 203, 5411, 534, 50, 3908, 18, 2293, 54, 50, 12, 54, 50, 1768, 1769, 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 ]
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; /** * @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]; } } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/DegenDonkeys.sol pragma solidity ^0.8.10; contract DegenDonkeys is ERC721Enumerable, Ownable { using Strings for uint256; using Address for address; struct Conf { uint16 supply; uint16 _reserved; uint64 price; } address private controller; address public fundsWallet; bool public mintEnabled = false; bool public whitelistMintEnabled = false; uint public perWhitelistAccount = 5; uint8 public perMint = 50; uint16 public phase = 420; uint16 public maxDonks = 6969; uint256 public imagesHash; string private defaultURI; string private baseURI; string private metaURI; mapping (address => bool) public whitelist; mapping(uint256 => uint256) private metaHashes; Conf private conf; event updateMetaHash(address, uint256, uint256); modifier isController(address sender) { require( sender != address(0) && (sender == owner() || sender == controller) ); _; } /** * @notice Setup ERC721 and initial config */ constructor( string memory name, string memory symbol, string memory _defaultURI, address _fundsWallet ) ERC721(name, symbol) { require(_fundsWallet != address(0), "Zero address error"); fundsWallet = _fundsWallet; conf = Conf(0, 100, 42000000000000000); defaultURI = _defaultURI; } /** * @notice Send ETH to owners wallet */ function ownerWithdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @notice send contract eth to fundswallet */ function fundsWithdraw() public onlyOwner { uint256 balance = address(this).balance; payable(fundsWallet).transfer(balance); } /** * @notice Send reserved donks * @param _to address to send reserved nfts to. * @param _amount number of nfts to send */ function fetchReserved(address _to, uint16 _amount) public onlyOwner { require( _to != address(0), "Zero address error"); require( _amount <= conf._reserved, "Exceeds reserved donks supply"); require( conf.supply + _amount <= phase, "Amount exceeds maximum supply of Donks in this phase." ); uint16 supply = conf.supply; unchecked { for (uint8 i = 0; i < _amount; i++) { _safeMint(_to, supply++); } } conf.supply = supply; conf._reserved -= _amount; } /** * @notice Bring new Donks into the world. * @param amount Number of Donks to mint. * @dev Utilize unchecked {} and calldata for gas savings. */ function mint(uint256 amount) public payable { require(mintEnabled, "Minting is disabled."); require( conf.supply + amount <= maxDonks - conf._reserved, "Amount exceeds maximum supply of Donks." ); require( conf.supply + amount <= phase, "Amount exceeds maximum supply of Donks in this phase." ); require( amount <= perMint, "Amount exceeds current maximum Donks per mint." ); require( conf.price * amount <= msg.value, "Ether value sent is not correct." ); uint16 supply = conf.supply; unchecked { for (uint16 i = 0; i < amount; i++) { _safeMint(msg.sender, supply++); } } conf.supply = supply; } // Whitelist functions /** * @notice add addresses to whitelist in bulk. * @param addresses Arrary of whitelisted addresses * @dev Only authorized accounts. */ function bulkWhitelist(address[] memory addresses) public onlyOwner { for(uint i=0; i < addresses.length; i++){ address addr = addresses[i]; if(whitelist[addr] != true && addr != address(0)){ whitelist[addr] = true; } } } /** * @notice Whitelist minting function. * @param amount Number of Donks to mint. * @dev Utilize unchecked {} and calldata for gas savings. */ function whitelistMint(uint256 amount) public payable { require(whitelistMintEnabled, "Whitelist Minting is disabled."); require( whitelist[msg.sender] == true, "Only whitelist can mint" ); require( conf.supply + amount <= phase, "Amount exceeds maximum supply of Donks in this phase." ); require( conf.supply + amount <= maxDonks - conf._reserved, "Amount exceeds maximum supply of Donks." ); require( balanceOf(msg.sender) + amount <= perWhitelistAccount, "Amount exceeds current maximum mints per account." ); require( amount <= perMint, "Amount exceeds current maximum Donks per mint." ); require( conf.price * amount <= msg.value, "Ether value sent is not correct." ); uint16 supply = conf.supply; unchecked { for (uint16 i = 0; i < amount; i++) { _safeMint(msg.sender, supply++); } } conf.supply = supply; } /** * @notice Toggle white list mint status. * @dev Only authorized accounts. */ function toggleWhitelistMintEnabled() public onlyOwner { whitelistMintEnabled = !whitelistMintEnabled; } /** * @notice Set per whitelist account * @param _perWhitelist new minting phase * @dev Only authorized accounts. */ function setPerWhitelistAccount(uint16 _perWhitelist) public onlyOwner { perWhitelistAccount = _perWhitelist; } /** * @notice Set phase. * @param _phase new minting phase * @dev Only authorized accounts. */ function setPhase(uint16 _phase) public onlyOwner { phase = _phase; } /** * @notice Set reserved. * @param reserved new reserved amount. * @dev Only authorized accounts. */ function setReserved(uint16 reserved) public onlyOwner { conf._reserved = reserved; } /** * @notice Set price. * @param newPrice new minting price * @dev Only authorized accounts. */ function setPrice(uint64 newPrice) public onlyOwner { conf.price = newPrice; } /** * @notice Set funds wallet. * @param _fundsWallet new funds wallet address * @dev Only authorized accounts. */ function setFundsWallet(address _fundsWallet) public onlyOwner { require(_fundsWallet != address(0), "Zero address error"); fundsWallet = _fundsWallet; } /** * @notice Set meta hash for token. * @param id Token id. * @param _hash Hash value. * @dev Only authorized accounts. */ function setMetaHash(uint256 id, uint256 _hash) public isController(msg.sender) { require(_exists(id), "Token does not exist."); metaHashes[id] = _hash; emit updateMetaHash(msg.sender, id, _hash); } /** * @notice Return mint price. */ function getMintPrice() public view returns (uint64) { return conf.price; } /** * @notice Return meta hash for token. */ function getMetaHash(uint256 id) public view returns (uint256) { return metaHashes[id]; } /** * @notice Sets URI for image hashes. */ function setImagesHash(uint256 _imagesHash) public onlyOwner { imagesHash = _imagesHash; } /** * @notice Toggles minting state. */ function toggleMintEnabled() public onlyOwner { mintEnabled = !mintEnabled; } /** * @notice Sets max Donks per mint. */ function setPerMint(uint8 _perMint) public onlyOwner { perMint = _perMint; } /** * @notice Set base URI. */ function setBaseURI(string memory _baseURI) public onlyOwner { baseURI = _baseURI; } /** * @notice Set default URI. */ function setDefaultURI(string memory _defaultURI) public onlyOwner { defaultURI = _defaultURI; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist."); if (bytes(baseURI).length == 0) { return defaultURI; } else { return string(abi.encodePacked(baseURI, (tokenId + 1).toString())); } } }
* @notice Return mint price./
function getMintPrice() public view returns (uint64) { return conf.price; }
10,053,782
[ 1, 990, 312, 474, 6205, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2108, 474, 5147, 1435, 1071, 1476, 1135, 261, 11890, 1105, 13, 288, 203, 3639, 327, 2195, 18, 8694, 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 ]
./partial_match/1/0x34D8e6DEF2dBB1973887aD22d0903713C27602DF/sources/MITRO.sol
* @dev Standard ERC20 token with burning and optional functions implemented. For full specification of ERC-20 standard see:/
contract MITRO is ERC20 { string private _name; string private _symbol; uint8 private _decimals; pragma solidity ^0.5.6; constructor(string memory name, string memory symbol, uint8 decimals, uint256 totalSupply, address payable feeReceiver, address tokenOwnerAddress) public payable { _name = name; _symbol = symbol; _decimals = decimals; _mint(tokenOwnerAddress, totalSupply); feeReceiver.transfer(msg.value); } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function burn(uint256 value) public { _burn(msg.sender, value); } function name() public view returns (string memory) { return _name; } }
9,310,906
[ 1, 8336, 4232, 39, 3462, 1147, 598, 18305, 310, 471, 3129, 4186, 8249, 18, 2457, 1983, 7490, 434, 4232, 39, 17, 3462, 4529, 2621, 27824, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 490, 1285, 1457, 353, 4232, 39, 3462, 288, 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, 683, 9454, 18035, 560, 3602, 20, 18, 25, 18, 26, 31, 203, 565, 3885, 12, 1080, 3778, 508, 16, 533, 3778, 3273, 16, 2254, 28, 15105, 16, 2254, 5034, 2078, 3088, 1283, 16, 1758, 8843, 429, 14036, 12952, 16, 1758, 1147, 5541, 1887, 13, 1071, 8843, 429, 288, 203, 1377, 389, 529, 273, 508, 31, 203, 1377, 389, 7175, 273, 3273, 31, 203, 1377, 389, 31734, 273, 15105, 31, 203, 203, 1377, 389, 81, 474, 12, 2316, 5541, 1887, 16, 2078, 3088, 1283, 1769, 203, 203, 1377, 14036, 12952, 18, 13866, 12, 3576, 18, 1132, 1769, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 1377, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 1135, 261, 11890, 28, 13, 288, 203, 1377, 327, 389, 31734, 31, 203, 565, 289, 203, 203, 565, 445, 18305, 12, 11890, 5034, 460, 13, 1071, 288, 203, 1377, 389, 70, 321, 12, 3576, 18, 15330, 16, 460, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 508, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 1377, 327, 389, 529, 31, 203, 565, 289, 203, 203, 7010, 27699, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xaF1f5e1c19cB68B30aAD73846eFfDf78a5863319/sources/VaultRegistry.sol
get the latest vault for a token and type. legacy is type 0. type 0 are legacy, not from this registry
function _latestVaultOfType( address _token, uint256 _type ) internal view returns (address) { if (_type == 0) { return _fetchFromLegacy(_token); } uint256 length = _numVaults(_token); if (length == 0) { return address(0); } uint256 i = length - 1; while (true) { address vault = vaults[_token][i]; if (vaultType[vault] == _type) { return vault; } if (i == 0) { break; } unchecked { i--; } } return address(0); }
2,622,048
[ 1, 588, 326, 4891, 9229, 364, 279, 1147, 471, 618, 18, 8866, 353, 618, 374, 18, 618, 374, 854, 8866, 16, 486, 628, 333, 4023, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 13550, 12003, 18859, 12, 203, 3639, 1758, 389, 2316, 16, 203, 3639, 2254, 5034, 389, 723, 203, 565, 262, 2713, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 309, 261, 67, 723, 422, 374, 13, 288, 203, 5411, 327, 389, 5754, 1265, 12235, 24899, 2316, 1769, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 769, 273, 389, 2107, 12003, 87, 24899, 2316, 1769, 203, 3639, 309, 261, 2469, 422, 374, 13, 288, 203, 5411, 327, 1758, 12, 20, 1769, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 277, 273, 769, 300, 404, 31, 203, 3639, 1323, 261, 3767, 13, 288, 203, 5411, 1758, 9229, 273, 9229, 87, 63, 67, 2316, 6362, 77, 15533, 203, 5411, 309, 261, 26983, 559, 63, 26983, 65, 422, 389, 723, 13, 288, 203, 7734, 327, 9229, 31, 203, 5411, 289, 203, 5411, 309, 261, 77, 422, 374, 13, 288, 203, 7734, 898, 31, 203, 5411, 289, 203, 5411, 22893, 288, 203, 7734, 277, 413, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Copyright 2018 Parity Technologies 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. // A validator set contract that relays calls to a relayed validator set // contract, which allows upgrading the relayed validator set contract. It // provides an `initiateChange` function that allows the relayed contract to // trigger a change, since the engine will be listening for events emitted by // the outer relay contract. pragma solidity ^0.4.22; import "./interfaces/Owned.sol"; import "./interfaces/ValidatorSet.sol"; import "./RelayedOwnedSet.sol"; contract RelaySet is Owned, ValidatorSet { // EVENTS event NewRelayed(address indexed old, address indexed current); // STATE // System address, used by the block sealer. address public systemAddress; // Address of the inner validator set contract RelayedOwnedSet public relayedSet; // MODIFIERS modifier onlySystem() { require(msg.sender == systemAddress); _; } modifier onlyRelayed() { require(msg.sender == address(relayedSet)); _; } constructor() public { systemAddress = 0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE; } // For innerSet function initiateChange(bytes32 _parentHash, address[] _newSet) external onlyRelayed { emit InitiateChange(_parentHash, _newSet); } // For sealer function finalizeChange() external onlySystem { relayedSet.finalizeChange(); } function reportBenign(address _validator, uint256 _blockNumber) external { relayedSet.relayReportBenign(msg.sender, _validator, _blockNumber); } function reportMalicious(address _validator, uint256 _blockNumber, bytes _proof) external { relayedSet.relayReportMalicious( msg.sender, _validator, _blockNumber, _proof ); } function setRelayed(address _relayedSet) external onlyOwner { emit NewRelayed(relayedSet, _relayedSet); relayedSet = RelayedOwnedSet(_relayedSet); } function getValidators() external view returns (address[]) { return relayedSet.getValidators(); } }
EVENTS STATE System address, used by the block sealer. Address of the inner validator set contract MODIFIERS
contract RelaySet is Owned, ValidatorSet { event NewRelayed(address indexed old, address indexed current); address public systemAddress; RelayedOwnedSet public relayedSet; modifier onlySystem() { require(msg.sender == systemAddress); _; } modifier onlyRelayed() { require(msg.sender == address(relayedSet)); _; } constructor() public { systemAddress = 0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE; } function initiateChange(bytes32 _parentHash, address[] _newSet) external onlyRelayed { emit InitiateChange(_parentHash, _newSet); } function finalizeChange() external onlySystem { relayedSet.finalizeChange(); } function reportBenign(address _validator, uint256 _blockNumber) external { relayedSet.relayReportBenign(msg.sender, _validator, _blockNumber); } function reportMalicious(address _validator, uint256 _blockNumber, bytes _proof) external { relayedSet.relayReportMalicious( msg.sender, _validator, _blockNumber, _proof ); } function setRelayed(address _relayedSet) external onlyOwner { emit NewRelayed(relayedSet, _relayedSet); relayedSet = RelayedOwnedSet(_relayedSet); } function getValidators() external view returns (address[]) { return relayedSet.getValidators(); } }
12,604,763
[ 1, 29221, 7442, 2332, 1758, 16, 1399, 635, 326, 1203, 695, 6774, 18, 5267, 434, 326, 3443, 4213, 444, 6835, 8663, 10591, 55, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4275, 528, 694, 353, 14223, 11748, 16, 9150, 694, 288, 203, 202, 2575, 1166, 27186, 329, 12, 2867, 8808, 1592, 16, 1758, 8808, 783, 1769, 203, 203, 203, 202, 2867, 1071, 2619, 1887, 31, 203, 202, 27186, 329, 5460, 329, 694, 1071, 18874, 329, 694, 31, 203, 203, 203, 203, 202, 20597, 1338, 3163, 1435, 288, 203, 202, 202, 6528, 12, 3576, 18, 15330, 422, 2619, 1887, 1769, 203, 202, 202, 67, 31, 203, 202, 97, 203, 203, 202, 20597, 1338, 27186, 329, 1435, 288, 203, 202, 202, 6528, 12, 3576, 18, 15330, 422, 1758, 12, 2878, 528, 329, 694, 10019, 203, 202, 202, 67, 31, 203, 202, 97, 203, 203, 202, 12316, 1435, 203, 202, 202, 482, 203, 202, 95, 203, 202, 202, 4299, 1887, 273, 374, 20431, 2246, 42, 74, 2246, 9460, 9460, 18217, 42, 74, 2246, 42, 25449, 2246, 42, 74, 2246, 74, 41, 31, 203, 202, 97, 203, 203, 202, 915, 18711, 3043, 12, 3890, 1578, 389, 2938, 2310, 16, 1758, 8526, 389, 2704, 694, 13, 203, 202, 202, 9375, 203, 202, 202, 3700, 27186, 329, 203, 202, 95, 203, 202, 202, 18356, 26615, 3043, 24899, 2938, 2310, 16, 389, 2704, 694, 1769, 203, 202, 97, 203, 203, 202, 915, 12409, 3043, 1435, 203, 202, 202, 9375, 203, 202, 202, 3700, 3163, 203, 202, 95, 203, 202, 202, 2878, 528, 329, 694, 18, 30343, 3043, 5621, 203, 202, 97, 203, 203, 202, 915, 2605, 38, 275, 724, 12, 2867, 389, 7357, 16, 2254, 5034, 389, 2629, 1854, 13, 203, 2 ]
/// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; contract TimeRestricted { uint immutable public timeRestrictionEnds; /// @notice deploy `TimeRestricted` contract. /// @param _timeRestrictionEnds Unix time for restriction to lift. constructor(uint _timeRestrictionEnds) { timeRestrictionEnds = _timeRestrictionEnds; } /// @notice Requires modified function to be called *at* `timeRestrictionEnds` in unix time or after. modifier timeRestricted { require(block.timestamp >= timeRestrictionEnds, 'TimeRestricted:!time'); _; } }
@notice deploy `TimeRestricted` contract. @param _timeRestrictionEnds Unix time for restriction to lift.
constructor(uint _timeRestrictionEnds) { timeRestrictionEnds = _timeRestrictionEnds; }
1,823,765
[ 1, 12411, 1375, 950, 18784, 68, 6835, 18, 225, 389, 957, 11670, 24980, 9480, 813, 364, 9318, 358, 28080, 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 ]
[ 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, 3885, 12, 11890, 389, 957, 11670, 24980, 13, 288, 203, 3639, 813, 11670, 24980, 273, 389, 957, 11670, 24980, 31, 21281, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-02-02 */ // File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/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: @bancor/token-governance/contracts/IClaimable.sol pragma solidity 0.6.12; /// @title Claimable contract interface interface IClaimable { function owner() external view returns (address); function transferOwnership(address newOwner) external; function acceptOwnership() external; } // File: @bancor/token-governance/contracts/IMintableToken.sol pragma solidity 0.6.12; /// @title Mintable Token interface interface IMintableToken is IERC20, IClaimable { function issue(address to, uint256 amount) external; function destroy(address from, uint256 amount) external; } // File: @bancor/token-governance/contracts/ITokenGovernance.sol pragma solidity 0.6.12; /// @title The interface for mintable/burnable token governance. interface ITokenGovernance { // The address of the mintable ERC20 token. function token() external view returns (IMintableToken); /// @dev Mints new tokens. /// /// @param to Account to receive the new amount. /// @param amount Amount to increase the supply by. /// function mint(address to, uint256 amount) external; /// @dev Burns tokens from the caller. /// /// @param amount Amount to decrease the supply by. /// function burn(uint256 amount) external; } // File: solidity/contracts/utility/interfaces/ICheckpointStore.sol pragma solidity 0.6.12; /** * @dev Checkpoint store contract interface */ interface ICheckpointStore { function addCheckpoint(address _address) external; function addPastCheckpoint(address _address, uint256 _time) external; function addPastCheckpoints(address[] calldata _addresses, uint256[] calldata _times) external; function checkpoint(address _address) external view returns (uint256); } // File: solidity/contracts/utility/MathEx.sol pragma solidity 0.6.12; /** * @dev This library provides a set of complex math operations. */ library MathEx { /** * @dev returns the largest integer smaller than or equal to the square root of a positive integer * * @param _num a positive integer * * @return the largest integer smaller than or equal to the square root of the positive integer */ function floorSqrt(uint256 _num) internal pure returns (uint256) { uint256 x = _num / 2 + 1; uint256 y = (x + _num / x) / 2; while (x > y) { x = y; y = (x + _num / x) / 2; } return x; } /** * @dev returns the smallest integer larger than or equal to the square root of a positive integer * * @param _num a positive integer * * @return the smallest integer larger than or equal to the square root of the positive integer */ function ceilSqrt(uint256 _num) internal pure returns (uint256) { uint256 x = floorSqrt(_num); return x * x == _num ? x : x + 1; } /** * @dev computes a reduced-scalar ratio * * @param _n ratio numerator * @param _d ratio denominator * @param _max maximum desired scalar * * @return ratio's numerator and denominator */ function reducedRatio( uint256 _n, uint256 _d, uint256 _max ) internal pure returns (uint256, uint256) { (uint256 n, uint256 d) = (_n, _d); if (n > _max || d > _max) { (n, d) = normalizedRatio(n, d, _max); } if (n != d) { return (n, d); } return (1, 1); } /** * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)". */ function normalizedRatio( uint256 _a, uint256 _b, uint256 _scale ) internal pure returns (uint256, uint256) { if (_a <= _b) { return accurateRatio(_a, _b, _scale); } (uint256 y, uint256 x) = accurateRatio(_b, _a, _scale); return (x, y); } /** * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)", assuming that "a <= b". */ function accurateRatio( uint256 _a, uint256 _b, uint256 _scale ) internal pure returns (uint256, uint256) { uint256 maxVal = uint256(-1) / _scale; if (_a > maxVal) { uint256 c = _a / (maxVal + 1) + 1; _a /= c; // we can now safely compute `_a * _scale` _b /= c; } if (_a != _b) { uint256 n = _a * _scale; uint256 d = _a + _b; // can overflow if (d >= _a) { // no overflow in `_a + _b` uint256 x = roundDiv(n, d); // we can now safely compute `_scale - x` uint256 y = _scale - x; return (x, y); } if (n < _b - (_b - _a) / 2) { return (0, _scale); // `_a * _scale < (_a + _b) / 2 < MAX_UINT256 < _a + _b` } return (1, _scale - 1); // `(_a + _b) / 2 < _a * _scale < MAX_UINT256 < _a + _b` } return (_scale / 2, _scale / 2); // allow reduction to `(1, 1)` in the calling function } /** * @dev computes the nearest integer to a given quotient without overflowing or underflowing. */ function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) { return _n / _d + (_n % _d) / (_d - _d / 2); } /** * @dev returns the average number of decimal digits in a given list of positive integers * * @param _values list of positive integers * * @return the average number of decimal digits in the given list of positive integers */ function geometricMean(uint256[] memory _values) internal pure returns (uint256) { uint256 numOfDigits = 0; uint256 length = _values.length; for (uint256 i = 0; i < length; i++) { numOfDigits += decimalLength(_values[i]); } return uint256(10)**(roundDivUnsafe(numOfDigits, length) - 1); } /** * @dev returns the number of decimal digits in a given positive integer * * @param _x positive integer * * @return the number of decimal digits in the given positive integer */ function decimalLength(uint256 _x) internal pure returns (uint256) { uint256 y = 0; for (uint256 x = _x; x > 0; x /= 10) { y++; } return y; } /** * @dev returns the nearest integer to a given quotient * the computation is overflow-safe assuming that the input is sufficiently small * * @param _n quotient numerator * @param _d quotient denominator * * @return the nearest integer to the given quotient */ function roundDivUnsafe(uint256 _n, uint256 _d) internal pure returns (uint256) { return (_n + _d / 2) / _d; } /** * @dev returns the larger of two values * * @param _val1 the first value * @param _val2 the second value */ function max(uint256 _val1, uint256 _val2) internal pure returns (uint256) { return _val1 > _val2 ? _val1 : _val2; } } // File: solidity/contracts/utility/ReentrancyGuard.sol pragma solidity 0.6.12; /** * @dev This contract provides protection against calling a function * (directly or indirectly) from within itself. */ contract ReentrancyGuard { uint256 private constant UNLOCKED = 1; uint256 private constant LOCKED = 2; // LOCKED while protected code is being executed, UNLOCKED otherwise uint256 private state = UNLOCKED; /** * @dev ensures instantiation only by sub-contracts */ constructor() internal {} // protects a function against reentrancy attacks modifier protected() { _protected(); state = LOCKED; _; state = UNLOCKED; } // error message binary size optimization function _protected() internal view { require(state == UNLOCKED, "ERR_REENTRANCY"); } } // File: solidity/contracts/utility/interfaces/IOwned.sol pragma solidity 0.6.12; /* Owned contract interface */ interface IOwned { // this function isn't since the compiler emits automatically generated getter functions as external function owner() external view returns (address); function transferOwnership(address _newOwner) external; function acceptOwnership() external; } // File: solidity/contracts/utility/Owned.sol pragma solidity 0.6.12; /** * @dev This contract provides support and utilities for contract ownership. */ contract Owned is IOwned { address public override owner; address public newOwner; /** * @dev triggered when the owner is updated * * @param _prevOwner previous owner * @param _newOwner new owner */ event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** * @dev initializes a new Owned instance */ constructor() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { _ownerOnly(); _; } // error message binary size optimization function _ownerOnly() internal view { require(msg.sender == owner, "ERR_ACCESS_DENIED"); } /** * @dev allows transferring the contract ownership * the new owner still needs to accept the transfer * can only be called by the contract owner * * @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public override ownerOnly { require(_newOwner != owner, "ERR_SAME_OWNER"); newOwner = _newOwner; } /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public override { require(msg.sender == newOwner, "ERR_ACCESS_DENIED"); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: solidity/contracts/token/interfaces/IERC20Token.sol pragma solidity 0.6.12; /* ERC20 Standard Token interface */ interface IERC20Token { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); } // File: solidity/contracts/utility/TokenHandler.sol pragma solidity 0.6.12; contract TokenHandler { bytes4 private constant APPROVE_FUNC_SELECTOR = bytes4(keccak256("approve(address,uint256)")); bytes4 private constant TRANSFER_FUNC_SELECTOR = bytes4(keccak256("transfer(address,uint256)")); bytes4 private constant TRANSFER_FROM_FUNC_SELECTOR = bytes4(keccak256("transferFrom(address,address,uint256)")); /** * @dev executes the ERC20 token's `approve` function and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _spender approved address * @param _value allowance amount */ function safeApprove( IERC20Token _token, address _spender, uint256 _value ) internal { (bool success, bytes memory data) = address(_token).call( abi.encodeWithSelector(APPROVE_FUNC_SELECTOR, _spender, _value) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "ERR_APPROVE_FAILED"); } /** * @dev executes the ERC20 token's `transfer` function and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _to target address * @param _value transfer amount */ function safeTransfer( IERC20Token _token, address _to, uint256 _value ) internal { (bool success, bytes memory data) = address(_token).call( abi.encodeWithSelector(TRANSFER_FUNC_SELECTOR, _to, _value) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "ERR_TRANSFER_FAILED"); } /** * @dev executes the ERC20 token's `transferFrom` function and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _from source address * @param _to target address * @param _value transfer amount */ function safeTransferFrom( IERC20Token _token, address _from, address _to, uint256 _value ) internal { (bool success, bytes memory data) = address(_token).call( abi.encodeWithSelector(TRANSFER_FROM_FUNC_SELECTOR, _from, _to, _value) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "ERR_TRANSFER_FROM_FAILED"); } } // File: solidity/contracts/utility/Types.sol pragma solidity 0.6.12; /** * @dev This contract provides types which can be used by various contracts. */ struct Fraction { uint256 n; // numerator uint256 d; // denominator } // File: solidity/contracts/utility/Time.sol pragma solidity 0.6.12; /* Time implementing contract */ contract Time { /** * @dev returns the current time */ function time() internal view virtual returns (uint256) { return block.timestamp; } } // File: solidity/contracts/utility/Utils.sol pragma solidity 0.6.12; /** * @dev Utilities & Common Modifiers */ contract Utils { // verifies that a value is greater than zero modifier greaterThanZero(uint256 _value) { _greaterThanZero(_value); _; } // error message binary size optimization function _greaterThanZero(uint256 _value) internal pure { require(_value > 0, "ERR_ZERO_VALUE"); } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { _validAddress(_address); _; } // error message binary size optimization function _validAddress(address _address) internal pure { require(_address != address(0), "ERR_INVALID_ADDRESS"); } // verifies that the address is different than this contract address modifier notThis(address _address) { _notThis(_address); _; } // error message binary size optimization function _notThis(address _address) internal view { require(_address != address(this), "ERR_ADDRESS_IS_SELF"); } // validates an external address - currently only checks that it isn't null or this modifier validExternalAddress(address _address) { _validExternalAddress(_address); _; } // error message binary size optimization function _validExternalAddress(address _address) internal view { require(_address != address(0) && _address != address(this), "ERR_INVALID_EXTERNAL_ADDRESS"); } } // File: solidity/contracts/converter/interfaces/IConverterAnchor.sol pragma solidity 0.6.12; /* Converter Anchor interface */ interface IConverterAnchor is IOwned { } // File: solidity/contracts/token/interfaces/IDSToken.sol pragma solidity 0.6.12; /* DSToken interface */ interface IDSToken is IConverterAnchor, IERC20Token { function issue(address _to, uint256 _amount) external; function destroy(address _from, uint256 _amount) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionStore.sol pragma solidity 0.6.12; /* Liquidity Protection Store interface */ interface ILiquidityProtectionStore is IOwned { function withdrawTokens( IERC20Token _token, address _to, uint256 _amount ) external; function protectedLiquidity(uint256 _id) external view returns ( address, IDSToken, IERC20Token, uint256, uint256, uint256, uint256, uint256 ); function addProtectedLiquidity( address _provider, IDSToken _poolToken, IERC20Token _reserveToken, uint256 _poolAmount, uint256 _reserveAmount, uint256 _reserveRateN, uint256 _reserveRateD, uint256 _timestamp ) external returns (uint256); function updateProtectedLiquidityAmounts( uint256 _id, uint256 _poolNewAmount, uint256 _reserveNewAmount ) external; function removeProtectedLiquidity(uint256 _id) external; function lockedBalance(address _provider, uint256 _index) external view returns (uint256, uint256); function lockedBalanceRange( address _provider, uint256 _startIndex, uint256 _endIndex ) external view returns (uint256[] memory, uint256[] memory); function addLockedBalance( address _provider, uint256 _reserveAmount, uint256 _expirationTime ) external returns (uint256); function removeLockedBalance(address _provider, uint256 _index) external; function systemBalance(IERC20Token _poolToken) external view returns (uint256); function incSystemBalance(IERC20Token _poolToken, uint256 _poolAmount) external; function decSystemBalance(IERC20Token _poolToken, uint256 _poolAmount) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionStats.sol pragma solidity 0.6.12; /* Liquidity Protection Stats interface */ interface ILiquidityProtectionStats { function increaseTotalAmounts( address provider, IDSToken poolToken, IERC20Token reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; function decreaseTotalAmounts( address provider, IDSToken poolToken, IERC20Token reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; function addProviderPool(address provider, IDSToken poolToken) external returns (bool); function removeProviderPool(address provider, IDSToken poolToken) external returns (bool); function totalPoolAmount(IDSToken poolToken) external view returns (uint256); function totalReserveAmount(IDSToken poolToken, IERC20Token reserveToken) external view returns (uint256); function totalProviderAmount( address provider, IDSToken poolToken, IERC20Token reserveToken ) external view returns (uint256); function providerPools(address provider) external view returns (IDSToken[] memory); } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionSettings.sol pragma solidity 0.6.12; /* Liquidity Protection Store Settings interface */ interface ILiquidityProtectionSettings { function addPoolToWhitelist(IConverterAnchor _poolAnchor) external; function removePoolFromWhitelist(IConverterAnchor _poolAnchor) external; function isPoolWhitelisted(IConverterAnchor _poolAnchor) external view returns (bool); function poolWhitelist() external view returns (address[] memory); function isPoolSupported(IConverterAnchor _poolAnchor) external view returns (bool); function minNetworkTokenLiquidityForMinting() external view returns (uint256); function defaultNetworkTokenMintingLimit() external view returns (uint256); function networkTokenMintingLimits(IConverterAnchor _poolAnchor) external view returns (uint256); function networkTokensMinted(IConverterAnchor _poolAnchor) external view returns (uint256); function incNetworkTokensMinted(IConverterAnchor _poolAnchor, uint256 _amount) external; function decNetworkTokensMinted(IConverterAnchor _poolAnchor, uint256 _amount) external; function minProtectionDelay() external view returns (uint256); function maxProtectionDelay() external view returns (uint256); function setProtectionDelays(uint256 _minProtectionDelay, uint256 _maxProtectionDelay) external; function minNetworkCompensation() external view returns (uint256); function setMinNetworkCompensation(uint256 _minCompensation) external; function lockDuration() external view returns (uint256); function setLockDuration(uint256 _lockDuration) external; function averageRateMaxDeviation() external view returns (uint32); function setAverageRateMaxDeviation(uint32 _averageRateMaxDeviation) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionSystemStore.sol pragma solidity 0.6.12; /* Liquidity Protection System Store interface */ interface ILiquidityProtectionSystemStore { function systemBalance(IERC20Token poolToken) external view returns (uint256); function incSystemBalance(IERC20Token poolToken, uint256 poolAmount) external; function decSystemBalance(IERC20Token poolToken, uint256 poolAmount) external; function networkTokensMinted(IConverterAnchor poolAnchor) external view returns (uint256); function incNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external; function decNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external; } // File: solidity/contracts/utility/interfaces/ITokenHolder.sol pragma solidity 0.6.12; /* Token Holder interface */ interface ITokenHolder is IOwned { function withdrawTokens( IERC20Token _token, address _to, uint256 _amount ) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtection.sol pragma solidity 0.6.12; /* Liquidity Protection interface */ interface ILiquidityProtection { function store() external view returns (ILiquidityProtectionStore); function stats() external view returns (ILiquidityProtectionStats); function settings() external view returns (ILiquidityProtectionSettings); function systemStore() external view returns (ILiquidityProtectionSystemStore); function wallet() external view returns (ITokenHolder); function addLiquidityFor( address owner, IConverterAnchor poolAnchor, IERC20Token reserveToken, uint256 amount ) external payable returns (uint256); function addLiquidity( IConverterAnchor poolAnchor, IERC20Token reserveToken, uint256 amount ) external payable returns (uint256); function removeLiquidity(uint256 id, uint32 portion) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionEventsSubscriber.sol pragma solidity 0.6.12; /** * @dev Liquidity protection events subscriber interface */ interface ILiquidityProtectionEventsSubscriber { function onAddingLiquidity( address provider, IConverterAnchor poolAnchor, IERC20Token reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; function onRemovingLiquidity( uint256 id, address provider, IConverterAnchor poolAnchor, IERC20Token reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; } // File: solidity/contracts/converter/interfaces/IConverter.sol pragma solidity 0.6.12; /* Converter interface */ interface IConverter is IOwned { function converterType() external pure returns (uint16); function anchor() external view returns (IConverterAnchor); function isActive() external view returns (bool); function targetAmountAndFee( IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount ) external view returns (uint256, uint256); function convert( IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address payable _beneficiary ) external payable returns (uint256); function conversionFee() external view returns (uint32); function maxConversionFee() external view returns (uint32); function reserveBalance(IERC20Token _reserveToken) external view returns (uint256); receive() external payable; function transferAnchorOwnership(address _newOwner) external; function acceptAnchorOwnership() external; function setConversionFee(uint32 _conversionFee) external; function withdrawTokens( IERC20Token _token, address _to, uint256 _amount ) external; function withdrawETH(address payable _to) external; function addReserve(IERC20Token _token, uint32 _ratio) external; // deprecated, backward compatibility function token() external view returns (IConverterAnchor); function transferTokenOwnership(address _newOwner) external; function acceptTokenOwnership() external; function connectors(IERC20Token _address) external view returns ( uint256, uint32, bool, bool, bool ); function getConnectorBalance(IERC20Token _connectorToken) external view returns (uint256); function connectorTokens(uint256 _index) external view returns (IERC20Token); function connectorTokenCount() external view returns (uint16); /** * @dev triggered when the converter is activated * * @param _type converter type * @param _anchor converter anchor * @param _activated true if the converter was activated, false if it was deactivated */ event Activation(uint16 indexed _type, IConverterAnchor indexed _anchor, bool indexed _activated); /** * @dev triggered when a conversion between two tokens occurs * * @param _fromToken source ERC20 token * @param _toToken target ERC20 token * @param _trader wallet that initiated the trade * @param _amount input amount in units of the source token * @param _return output amount minus conversion fee in units of the target token * @param _conversionFee conversion fee in units of the target token */ event Conversion( IERC20Token indexed _fromToken, IERC20Token indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return, int256 _conversionFee ); /** * @dev triggered when the rate between two tokens in the converter changes * note that the event might be dispatched for rate updates between any two tokens in the converter * * @param _token1 address of the first token * @param _token2 address of the second token * @param _rateN rate of 1 unit of `_token1` in `_token2` (numerator) * @param _rateD rate of 1 unit of `_token1` in `_token2` (denominator) */ event TokenRateUpdate(IERC20Token indexed _token1, IERC20Token indexed _token2, uint256 _rateN, uint256 _rateD); /** * @dev triggered when the conversion fee is updated * * @param _prevFee previous fee percentage, represented in ppm * @param _newFee new fee percentage, represented in ppm */ event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee); } // File: solidity/contracts/converter/interfaces/IConverterRegistry.sol pragma solidity 0.6.12; interface IConverterRegistry { function getAnchorCount() external view returns (uint256); function getAnchors() external view returns (address[] memory); function getAnchor(uint256 _index) external view returns (IConverterAnchor); function isAnchor(address _value) external view returns (bool); function getLiquidityPoolCount() external view returns (uint256); function getLiquidityPools() external view returns (address[] memory); function getLiquidityPool(uint256 _index) external view returns (IConverterAnchor); function isLiquidityPool(address _value) external view returns (bool); function getConvertibleTokenCount() external view returns (uint256); function getConvertibleTokens() external view returns (address[] memory); function getConvertibleToken(uint256 _index) external view returns (IERC20Token); function isConvertibleToken(address _value) external view returns (bool); function getConvertibleTokenAnchorCount(IERC20Token _convertibleToken) external view returns (uint256); function getConvertibleTokenAnchors(IERC20Token _convertibleToken) external view returns (address[] memory); function getConvertibleTokenAnchor(IERC20Token _convertibleToken, uint256 _index) external view returns (IConverterAnchor); function isConvertibleTokenAnchor(IERC20Token _convertibleToken, address _value) external view returns (bool); } // File: solidity/contracts/liquidity-protection/LiquidityProtection.sol pragma solidity 0.6.12; interface ILiquidityPoolConverter is IConverter { function addLiquidity( IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _minReturn ) external payable; function removeLiquidity( uint256 _amount, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts ) external; function recentAverageRate(IERC20Token _reserveToken) external view returns (uint256, uint256); } /** * @dev This contract implements the liquidity protection mechanism. */ contract LiquidityProtection is ILiquidityProtection, TokenHandler, Utils, Owned, ReentrancyGuard, Time { using SafeMath for uint256; using MathEx for *; struct ProtectedLiquidity { address provider; // liquidity provider IDSToken poolToken; // pool token address IERC20Token reserveToken; // reserve token address uint256 poolAmount; // pool token amount uint256 reserveAmount; // reserve token amount uint256 reserveRateN; // rate of 1 protected reserve token in units of the other reserve token (numerator) uint256 reserveRateD; // rate of 1 protected reserve token in units of the other reserve token (denominator) uint256 timestamp; // timestamp } // various rates between the two reserve tokens. the rate is of 1 unit of the protected reserve token in units of the other reserve token struct PackedRates { uint128 addSpotRateN; // spot rate of 1 A in units of B when liquidity was added (numerator) uint128 addSpotRateD; // spot rate of 1 A in units of B when liquidity was added (denominator) uint128 removeSpotRateN; // spot rate of 1 A in units of B when liquidity is removed (numerator) uint128 removeSpotRateD; // spot rate of 1 A in units of B when liquidity is removed (denominator) uint128 removeAverageRateN; // average rate of 1 A in units of B when liquidity is removed (numerator) uint128 removeAverageRateD; // average rate of 1 A in units of B when liquidity is removed (denominator) } IERC20Token internal constant ETH_RESERVE_ADDRESS = IERC20Token(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); uint32 internal constant PPM_RESOLUTION = 1000000; uint256 internal constant MAX_UINT128 = 2**128 - 1; uint256 internal constant MAX_UINT256 = uint256(-1); ILiquidityProtectionSettings public immutable override settings; ILiquidityProtectionStore public immutable override store; ILiquidityProtectionStats public immutable override stats; ILiquidityProtectionSystemStore public immutable override systemStore; ITokenHolder public immutable override wallet; IERC20Token public immutable networkToken; ITokenGovernance public immutable networkTokenGovernance; IERC20Token public immutable govToken; ITokenGovernance public immutable govTokenGovernance; ICheckpointStore public immutable lastRemoveCheckpointStore; ILiquidityProtectionEventsSubscriber public eventsSubscriber; // true if the contract is currently adding/removing liquidity from a converter, used for accepting ETH bool private updatingLiquidity = false; /** * @dev updates the event subscriber * * @param _prevEventsSubscriber the previous events subscriber * @param _newEventsSubscriber the new events subscriber */ event EventSubscriberUpdated( ILiquidityProtectionEventsSubscriber indexed _prevEventsSubscriber, ILiquidityProtectionEventsSubscriber indexed _newEventsSubscriber ); /** * @dev initializes a new LiquidityProtection contract * * @param _contractAddresses: * - [0] liquidity protection settings * - [1] liquidity protection store * - [2] liquidity protection stats * - [3] liquidity protection system store * - [4] liquidity protection wallet * - [5] network token governance * - [6] governance token governance * - [7] last liquidity removal/unprotection checkpoints store */ constructor(address[8] memory _contractAddresses) public { for (uint256 i = 0; i < _contractAddresses.length; i++) { _validAddress(_contractAddresses[i]); } settings = ILiquidityProtectionSettings(_contractAddresses[0]); store = ILiquidityProtectionStore(_contractAddresses[1]); stats = ILiquidityProtectionStats(_contractAddresses[2]); systemStore = ILiquidityProtectionSystemStore(_contractAddresses[3]); wallet = ITokenHolder(_contractAddresses[4]); networkTokenGovernance = ITokenGovernance(_contractAddresses[5]); govTokenGovernance = ITokenGovernance(_contractAddresses[6]); lastRemoveCheckpointStore = ICheckpointStore(_contractAddresses[7]); networkToken = IERC20Token(address(ITokenGovernance(_contractAddresses[5]).token())); govToken = IERC20Token(address(ITokenGovernance(_contractAddresses[6]).token())); } // ensures that the contract is currently removing liquidity from a converter modifier updatingLiquidityOnly() { require(updatingLiquidity, "ERR_NOT_UPDATING_LIQUIDITY"); _; } // ensures that the portion is valid modifier validPortion(uint32 _portion) { _validPortion(_portion); _; } // error message binary size optimization function _validPortion(uint32 _portion) internal pure { require(_portion > 0 && _portion <= PPM_RESOLUTION, "ERR_INVALID_PORTION"); } // ensures that the pool is supported and whitelisted modifier poolSupportedAndWhitelisted(IConverterAnchor _poolAnchor) { _poolSupported(_poolAnchor); _poolWhitelisted(_poolAnchor); _; } // error message binary size optimization function _poolSupported(IConverterAnchor _poolAnchor) internal view { require(settings.isPoolSupported(_poolAnchor), "ERR_POOL_NOT_SUPPORTED"); } // error message binary size optimization function _poolWhitelisted(IConverterAnchor _poolAnchor) internal view { require(settings.isPoolWhitelisted(_poolAnchor), "ERR_POOL_NOT_WHITELISTED"); } // error message binary size optimization function verifyEthAmount(uint256 _value) internal view { require(msg.value == _value, "ERR_ETH_AMOUNT_MISMATCH"); } /** * @dev accept ETH * used when removing liquidity from ETH converters */ receive() external payable updatingLiquidityOnly() {} /** * @dev transfers the ownership of the store * can only be called by the contract owner * * @param _newOwner the new owner of the store */ function transferStoreOwnership(address _newOwner) external ownerOnly { store.transferOwnership(_newOwner); } /** * @dev accepts the ownership of the store * can only be called by the contract owner */ function acceptStoreOwnership() external ownerOnly { store.acceptOwnership(); } /** * @dev transfers the ownership of the wallet * can only be called by the contract owner * * @param _newOwner the new owner of the wallet */ function transferWalletOwnership(address _newOwner) external ownerOnly { wallet.transferOwnership(_newOwner); } /** * @dev accepts the ownership of the wallet * can only be called by the contract owner */ function acceptWalletOwnership() external ownerOnly { wallet.acceptOwnership(); } /** * @dev migrates all funds from the store to the wallet * @dev migrates system balances from the store to the system-store * @dev migrates minted amounts from the settings to the system-store */ function migrateData() external { // save local copies of storage variables address storeAddress = address(store); address walletAddress = address(wallet); IERC20Token networkTokenLocal = networkToken; address[] memory poolWhitelist = settings.poolWhitelist(); for (uint256 i = 0; i < poolWhitelist.length; i++) { IERC20Token poolToken = IERC20Token(poolWhitelist[i]); store.withdrawTokens(poolToken, walletAddress, poolToken.balanceOf(storeAddress)); uint256 systemBalance = store.systemBalance(poolToken); systemStore.incSystemBalance(poolToken, systemBalance); store.decSystemBalance(poolToken, systemBalance); uint256 networkTokensMinted = settings.networkTokensMinted(IConverterAnchor(address(poolToken))); systemStore.incNetworkTokensMinted(IConverterAnchor(address(poolToken)), networkTokensMinted); settings.decNetworkTokensMinted(IConverterAnchor(address(poolToken)), networkTokensMinted); } store.withdrawTokens(networkTokenLocal, walletAddress, networkTokenLocal.balanceOf(storeAddress)); } /** * @dev sets the events subscriber */ function setEventsSubscriber(ILiquidityProtectionEventsSubscriber _eventsSubscriber) external ownerOnly validAddress(address(_eventsSubscriber)) notThis(address(_eventsSubscriber)) { emit EventSubscriberUpdated(eventsSubscriber, _eventsSubscriber); eventsSubscriber = _eventsSubscriber; } /** * @dev adds protected liquidity to a pool for a specific recipient * also mints new governance tokens for the caller if the caller adds network tokens * * @param _owner protected liquidity owner * @param _poolAnchor anchor of the pool * @param _reserveToken reserve token to add to the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addLiquidityFor( address _owner, IConverterAnchor _poolAnchor, IERC20Token _reserveToken, uint256 _amount ) external payable override protected validAddress(_owner) poolSupportedAndWhitelisted(_poolAnchor) greaterThanZero(_amount) returns (uint256) { return addLiquidity(_owner, _poolAnchor, _reserveToken, _amount); } /** * @dev adds protected liquidity to a pool * also mints new governance tokens for the caller if the caller adds network tokens * * @param _poolAnchor anchor of the pool * @param _reserveToken reserve token to add to the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addLiquidity( IConverterAnchor _poolAnchor, IERC20Token _reserveToken, uint256 _amount ) external payable override protected poolSupportedAndWhitelisted(_poolAnchor) greaterThanZero(_amount) returns (uint256) { return addLiquidity(msg.sender, _poolAnchor, _reserveToken, _amount); } /** * @dev adds protected liquidity to a pool for a specific recipient * also mints new governance tokens for the caller if the caller adds network tokens * * @param _owner protected liquidity owner * @param _poolAnchor anchor of the pool * @param _reserveToken reserve token to add to the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addLiquidity( address _owner, IConverterAnchor _poolAnchor, IERC20Token _reserveToken, uint256 _amount ) private returns (uint256) { // save a local copy of `networkToken` IERC20Token networkTokenLocal = networkToken; if (_reserveToken == networkTokenLocal) { verifyEthAmount(0); return addNetworkTokenLiquidity(_owner, _poolAnchor, networkTokenLocal, _amount); } // verify that ETH was passed with the call if needed verifyEthAmount(_reserveToken == ETH_RESERVE_ADDRESS ? _amount : 0); return addBaseTokenLiquidity(_owner, _poolAnchor, _reserveToken, networkTokenLocal, _amount); } /** * @dev adds protected network token liquidity to a pool * also mints new governance tokens for the caller * * @param _owner protected liquidity owner * @param _poolAnchor anchor of the pool * @param _networkToken the network reserve token of the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addNetworkTokenLiquidity( address _owner, IConverterAnchor _poolAnchor, IERC20Token _networkToken, uint256 _amount ) internal returns (uint256) { IDSToken poolToken = IDSToken(address(_poolAnchor)); // get the rate between the pool token and the reserve Fraction memory poolRate = poolTokenRate(poolToken, _networkToken); // calculate the amount of pool tokens based on the amount of reserve tokens uint256 poolTokenAmount = _amount.mul(poolRate.d).div(poolRate.n); // remove the pool tokens from the system's ownership (will revert if not enough tokens are available) systemStore.decSystemBalance(poolToken, poolTokenAmount); // add protected liquidity for the recipient uint256 id = addProtectedLiquidity(_owner, poolToken, _networkToken, poolTokenAmount, _amount); // burns the network tokens from the caller. we need to transfer the tokens to the contract itself, since only // token holders can burn their tokens safeTransferFrom(_networkToken, msg.sender, address(this), _amount); burnNetworkTokens(_poolAnchor, _amount); // mint governance tokens to the recipient govTokenGovernance.mint(_owner, _amount); return id; } /** * @dev adds protected base token liquidity to a pool * * @param _owner protected liquidity owner * @param _poolAnchor anchor of the pool * @param _baseToken the base reserve token of the pool * @param _networkToken the network reserve token of the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addBaseTokenLiquidity( address _owner, IConverterAnchor _poolAnchor, IERC20Token _baseToken, IERC20Token _networkToken, uint256 _amount ) internal returns (uint256) { IDSToken poolToken = IDSToken(address(_poolAnchor)); // get the reserve balances ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolAnchor))); (uint256 reserveBalanceBase, uint256 reserveBalanceNetwork) = converterReserveBalances(converter, _baseToken, _networkToken); require(reserveBalanceNetwork >= settings.minNetworkTokenLiquidityForMinting(), "ERR_NOT_ENOUGH_LIQUIDITY"); // calculate and mint the required amount of network tokens for adding liquidity uint256 newNetworkLiquidityAmount = _amount.mul(reserveBalanceNetwork).div(reserveBalanceBase); // verify network token minting limit uint256 mintingLimit = settings.networkTokenMintingLimits(_poolAnchor); if (mintingLimit == 0) { mintingLimit = settings.defaultNetworkTokenMintingLimit(); } uint256 newNetworkTokensMinted = systemStore.networkTokensMinted(_poolAnchor).add(newNetworkLiquidityAmount); require(newNetworkTokensMinted <= mintingLimit, "ERR_MAX_AMOUNT_REACHED"); // issue new network tokens to the system mintNetworkTokens(address(this), _poolAnchor, newNetworkLiquidityAmount); // transfer the base tokens from the caller and approve the converter ensureAllowance(_networkToken, address(converter), newNetworkLiquidityAmount); if (_baseToken != ETH_RESERVE_ADDRESS) { safeTransferFrom(_baseToken, msg.sender, address(this), _amount); ensureAllowance(_baseToken, address(converter), _amount); } // add liquidity addLiquidity(converter, _baseToken, _networkToken, _amount, newNetworkLiquidityAmount, msg.value); // transfer the new pool tokens to the wallet uint256 poolTokenAmount = poolToken.balanceOf(address(this)); safeTransfer(poolToken, address(wallet), poolTokenAmount); // the system splits the pool tokens with the caller // increase the system's pool token balance and add protected liquidity for the caller systemStore.incSystemBalance(poolToken, poolTokenAmount - poolTokenAmount / 2); // account for rounding errors return addProtectedLiquidity(_owner, poolToken, _baseToken, poolTokenAmount / 2, _amount); } /** * @dev returns the single-side staking limits of a given pool * * @param _poolAnchor anchor of the pool * @return maximum amount of base tokens that can be single-side staked in the pool * @return maximum amount of network tokens that can be single-side staked in the pool */ function poolAvailableSpace(IConverterAnchor _poolAnchor) external view poolSupportedAndWhitelisted(_poolAnchor) returns (uint256, uint256) { IERC20Token networkTokenLocal = networkToken; return ( baseTokenAvailableSpace(_poolAnchor, networkTokenLocal), networkTokenAvailableSpace(_poolAnchor, networkTokenLocal) ); } /** * @dev returns the base-token staking limits of a given pool * * @param _poolAnchor anchor of the pool * @return maximum amount of base tokens that can be single-side staked in the pool */ function baseTokenAvailableSpace(IConverterAnchor _poolAnchor) external view poolSupportedAndWhitelisted(_poolAnchor) returns (uint256) { return baseTokenAvailableSpace(_poolAnchor, networkToken); } /** * @dev returns the network-token staking limits of a given pool * * @param _poolAnchor anchor of the pool * @return maximum amount of network tokens that can be single-side staked in the pool */ function networkTokenAvailableSpace(IConverterAnchor _poolAnchor) external view poolSupportedAndWhitelisted(_poolAnchor) returns (uint256) { return networkTokenAvailableSpace(_poolAnchor, networkToken); } /** * @dev returns the base-token staking limits of a given pool * * @param _poolAnchor anchor of the pool * @param _networkToken the network token * @return maximum amount of base tokens that can be single-side staked in the pool */ function baseTokenAvailableSpace(IConverterAnchor _poolAnchor, IERC20Token _networkToken) internal view returns (uint256) { // get the pool converter ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolAnchor))); // get the base token IERC20Token baseToken = converterOtherReserve(converter, _networkToken); // get the reserve balances (uint256 reserveBalanceBase, uint256 reserveBalanceNetwork) = converterReserveBalances(converter, baseToken, _networkToken); // get the network token minting limit uint256 mintingLimit = settings.networkTokenMintingLimits(_poolAnchor); if (mintingLimit == 0) { mintingLimit = settings.defaultNetworkTokenMintingLimit(); } // get the amount of network tokens already minted for the pool uint256 networkTokensMinted = systemStore.networkTokensMinted(_poolAnchor); // get the amount of network tokens which can minted for the pool uint256 networkTokensCanBeMinted = MathEx.max(mintingLimit, networkTokensMinted) - networkTokensMinted; // return the maximum amount of base token liquidity that can be single-sided staked in the pool return networkTokensCanBeMinted.mul(reserveBalanceBase).div(reserveBalanceNetwork); } /** * @dev returns the network-token staking limits of a given pool * * @param _poolAnchor anchor of the pool * @param _networkToken the network token * @return maximum amount of network tokens that can be single-side staked in the pool */ function networkTokenAvailableSpace(IConverterAnchor _poolAnchor, IERC20Token _networkToken) internal view returns (uint256) { // get the pool token IDSToken poolToken = IDSToken(address(_poolAnchor)); // get the pool token rate Fraction memory poolRate = poolTokenRate(poolToken, _networkToken); // return the maximum amount of network token liquidity that can be single-sided staked in the pool return systemStore.systemBalance(poolToken).mul(poolRate.n).add(poolRate.n).sub(1).div(poolRate.d); } /** * @dev returns the expected/actual amounts the provider will receive for removing liquidity * it's also possible to provide the remove liquidity time to get an estimation * for the return at that given point * * @param _id protected liquidity id * @param _portion portion of liquidity to remove, in PPM * @param _removeTimestamp time at which the liquidity is removed * @return expected return amount in the reserve token * @return actual return amount in the reserve token * @return compensation in the network token */ function removeLiquidityReturn( uint256 _id, uint32 _portion, uint256 _removeTimestamp ) external view validPortion(_portion) returns ( uint256, uint256, uint256 ) { ProtectedLiquidity memory liquidity = protectedLiquidity(_id); // verify input require(liquidity.provider != address(0), "ERR_INVALID_ID"); require(_removeTimestamp >= liquidity.timestamp, "ERR_INVALID_TIMESTAMP"); // calculate the portion of the liquidity to remove if (_portion != PPM_RESOLUTION) { liquidity.poolAmount = liquidity.poolAmount.mul(_portion) / PPM_RESOLUTION; liquidity.reserveAmount = liquidity.reserveAmount.mul(_portion) / PPM_RESOLUTION; } // get the various rates between the reserves upon adding liquidity and now PackedRates memory packedRates = packRates( liquidity.poolToken, liquidity.reserveToken, liquidity.reserveRateN, liquidity.reserveRateD, false ); uint256 targetAmount = removeLiquidityTargetAmount( liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount, packedRates, liquidity.timestamp, _removeTimestamp ); // for network token, the return amount is identical to the target amount if (liquidity.reserveToken == networkToken) { return (targetAmount, targetAmount, 0); } // handle base token return // calculate the amount of pool tokens required for liquidation // note that the amount is doubled since it's not possible to liquidate one reserve only Fraction memory poolRate = poolTokenRate(liquidity.poolToken, liquidity.reserveToken); uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2); // limit the amount of pool tokens by the amount the system/caller holds uint256 availableBalance = systemStore.systemBalance(liquidity.poolToken).add(liquidity.poolAmount); poolAmount = poolAmount > availableBalance ? availableBalance : poolAmount; // calculate the base token amount received by liquidating the pool tokens // note that the amount is divided by 2 since the pool amount represents both reserves uint256 baseAmount = poolAmount.mul(poolRate.n / 2).div(poolRate.d); uint256 networkAmount = getNetworkCompensation(targetAmount, baseAmount, packedRates); return (targetAmount, baseAmount, networkAmount); } /** * @dev removes protected liquidity from a pool * also burns governance tokens from the caller if the caller removes network tokens * * @param _id id in the caller's list of protected liquidity * @param _portion portion of liquidity to remove, in PPM */ function removeLiquidity(uint256 _id, uint32 _portion) external override protected validPortion(_portion) { removeLiquidity(msg.sender, _id, _portion); } /** * @dev removes protected liquidity from a pool * also burns governance tokens from the caller if the caller removes network tokens * * @param _provider protected liquidity provider * @param _id id in the caller's list of protected liquidity * @param _portion portion of liquidity to remove, in PPM */ function removeLiquidity( address payable _provider, uint256 _id, uint32 _portion ) internal { ProtectedLiquidity memory liquidity = protectedLiquidity(_id, _provider); // save a local copy of `networkToken` IERC20Token networkTokenLocal = networkToken; // verify that the pool is whitelisted _poolWhitelisted(liquidity.poolToken); // verify that the protected liquidity is not removed on the same block in which it was added require(liquidity.timestamp < time(), "ERR_TOO_EARLY"); if (_portion == PPM_RESOLUTION) { // notify event subscribers if (address(eventsSubscriber) != address(0)) { eventsSubscriber.onRemovingLiquidity( _id, _provider, liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount ); } // remove the protected liquidity from the provider store.removeProtectedLiquidity(_id); } else { // remove a portion of the protected liquidity from the provider uint256 fullPoolAmount = liquidity.poolAmount; uint256 fullReserveAmount = liquidity.reserveAmount; liquidity.poolAmount = liquidity.poolAmount.mul(_portion) / PPM_RESOLUTION; liquidity.reserveAmount = liquidity.reserveAmount.mul(_portion) / PPM_RESOLUTION; // notify event subscribers if (address(eventsSubscriber) != address(0)) { eventsSubscriber.onRemovingLiquidity( _id, _provider, liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount ); } store.updateProtectedLiquidityAmounts( _id, fullPoolAmount - liquidity.poolAmount, fullReserveAmount - liquidity.reserveAmount ); } // update the statistics stats.decreaseTotalAmounts( liquidity.provider, liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount ); // update last liquidity removal checkpoint lastRemoveCheckpointStore.addCheckpoint(_provider); // add the pool tokens to the system systemStore.incSystemBalance(liquidity.poolToken, liquidity.poolAmount); // if removing network token liquidity, burn the governance tokens from the caller. we need to transfer the // tokens to the contract itself, since only token holders can burn their tokens if (liquidity.reserveToken == networkTokenLocal) { safeTransferFrom(govToken, _provider, address(this), liquidity.reserveAmount); govTokenGovernance.burn(liquidity.reserveAmount); } // get the various rates between the reserves upon adding liquidity and now PackedRates memory packedRates = packRates( liquidity.poolToken, liquidity.reserveToken, liquidity.reserveRateN, liquidity.reserveRateD, true ); // get the target token amount uint256 targetAmount = removeLiquidityTargetAmount( liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount, packedRates, liquidity.timestamp, time() ); // remove network token liquidity if (liquidity.reserveToken == networkTokenLocal) { // mint network tokens for the caller and lock them mintNetworkTokens(address(wallet), liquidity.poolToken, targetAmount); lockTokens(_provider, targetAmount); return; } // remove base token liquidity // calculate the amount of pool tokens required for liquidation // note that the amount is doubled since it's not possible to liquidate one reserve only Fraction memory poolRate = poolTokenRate(liquidity.poolToken, liquidity.reserveToken); uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2); // limit the amount of pool tokens by the amount the system holds uint256 systemBalance = systemStore.systemBalance(liquidity.poolToken); poolAmount = poolAmount > systemBalance ? systemBalance : poolAmount; // withdraw the pool tokens from the wallet systemStore.decSystemBalance(liquidity.poolToken, poolAmount); wallet.withdrawTokens(liquidity.poolToken, address(this), poolAmount); // remove liquidity removeLiquidity(liquidity.poolToken, poolAmount, liquidity.reserveToken, networkTokenLocal); // transfer the base tokens to the caller uint256 baseBalance; if (liquidity.reserveToken == ETH_RESERVE_ADDRESS) { baseBalance = address(this).balance; _provider.transfer(baseBalance); } else { baseBalance = liquidity.reserveToken.balanceOf(address(this)); safeTransfer(liquidity.reserveToken, _provider, baseBalance); } // compensate the caller with network tokens if still needed uint256 delta = getNetworkCompensation(targetAmount, baseBalance, packedRates); if (delta > 0) { // check if there's enough network token balance, otherwise mint more uint256 networkBalance = networkTokenLocal.balanceOf(address(this)); if (networkBalance < delta) { networkTokenGovernance.mint(address(this), delta - networkBalance); } // lock network tokens for the caller safeTransfer(networkTokenLocal, address(wallet), delta); lockTokens(_provider, delta); } // if the contract still holds network tokens, burn them uint256 networkBalance = networkTokenLocal.balanceOf(address(this)); if (networkBalance > 0) { burnNetworkTokens(liquidity.poolToken, networkBalance); } } /** * @dev returns the amount the provider will receive for removing liquidity * it's also possible to provide the remove liquidity rate & time to get an estimation * for the return at that given point * * @param _poolToken pool token * @param _reserveToken reserve token * @param _poolAmount pool token amount when the liquidity was added * @param _reserveAmount reserve token amount that was added * @param _packedRates see `struct PackedRates` * @param _addTimestamp time at which the liquidity was added * @param _removeTimestamp time at which the liquidity is removed * @return amount received for removing liquidity */ function removeLiquidityTargetAmount( IDSToken _poolToken, IERC20Token _reserveToken, uint256 _poolAmount, uint256 _reserveAmount, PackedRates memory _packedRates, uint256 _addTimestamp, uint256 _removeTimestamp ) internal view returns (uint256) { // get the rate between the pool token and the reserve token Fraction memory poolRate = poolTokenRate(_poolToken, _reserveToken); // get the rate between the reserves upon adding liquidity and now Fraction memory addSpotRate = Fraction({ n: _packedRates.addSpotRateN, d: _packedRates.addSpotRateD }); Fraction memory removeSpotRate = Fraction({ n: _packedRates.removeSpotRateN, d: _packedRates.removeSpotRateD }); Fraction memory removeAverageRate = Fraction({ n: _packedRates.removeAverageRateN, d: _packedRates.removeAverageRateD }); // calculate the protected amount of reserve tokens plus accumulated fee before compensation uint256 total = protectedAmountPlusFee(_poolAmount, poolRate, addSpotRate, removeSpotRate); // calculate the impermanent loss Fraction memory loss = impLoss(addSpotRate, removeAverageRate); // calculate the protection level Fraction memory level = protectionLevel(_addTimestamp, _removeTimestamp); // calculate the compensation amount return compensationAmount(_reserveAmount, MathEx.max(_reserveAmount, total), loss, level); } /** * @dev allows the caller to claim network token balance that is no longer locked * note that the function can revert if the range is too large * * @param _startIndex start index in the caller's list of locked balances * @param _endIndex end index in the caller's list of locked balances (exclusive) */ function claimBalance(uint256 _startIndex, uint256 _endIndex) external protected { // get the locked balances from the store (uint256[] memory amounts, uint256[] memory expirationTimes) = store.lockedBalanceRange(msg.sender, _startIndex, _endIndex); uint256 totalAmount = 0; uint256 length = amounts.length; assert(length == expirationTimes.length); // reverse iteration since we're removing from the list for (uint256 i = length; i > 0; i--) { uint256 index = i - 1; if (expirationTimes[index] > time()) { continue; } // remove the locked balance item store.removeLockedBalance(msg.sender, _startIndex + index); totalAmount = totalAmount.add(amounts[index]); } if (totalAmount > 0) { // transfer the tokens to the caller in a single call wallet.withdrawTokens(networkToken, msg.sender, totalAmount); } } /** * @dev returns the ROI for removing liquidity in the current state after providing liquidity with the given args * the function assumes full protection is in effect * return value is in PPM and can be larger than PPM_RESOLUTION for positive ROI, 1M = 0% ROI * * @param _poolToken pool token * @param _reserveToken reserve token * @param _reserveAmount reserve token amount that was added * @param _poolRateN rate of 1 pool token in reserve token units when the liquidity was added (numerator) * @param _poolRateD rate of 1 pool token in reserve token units when the liquidity was added (denominator) * @param _reserveRateN rate of 1 reserve token in the other reserve token units when the liquidity was added (numerator) * @param _reserveRateD rate of 1 reserve token in the other reserve token units when the liquidity was added (denominator) * @return ROI in PPM */ function poolROI( IDSToken _poolToken, IERC20Token _reserveToken, uint256 _reserveAmount, uint256 _poolRateN, uint256 _poolRateD, uint256 _reserveRateN, uint256 _reserveRateD ) external view returns (uint256) { // calculate the amount of pool tokens based on the amount of reserve tokens uint256 poolAmount = _reserveAmount.mul(_poolRateD).div(_poolRateN); // get the various rates between the reserves upon adding liquidity and now PackedRates memory packedRates = packRates(_poolToken, _reserveToken, _reserveRateN, _reserveRateD, false); // get the current return uint256 protectedReturn = removeLiquidityTargetAmount( _poolToken, _reserveToken, poolAmount, _reserveAmount, packedRates, time().sub(settings.maxProtectionDelay()), time() ); // calculate the ROI as the ratio between the current fully protected return and the initial amount return protectedReturn.mul(PPM_RESOLUTION).div(_reserveAmount); } /** * @dev adds protected liquidity for the caller to the store * * @param _provider protected liquidity provider * @param _poolToken pool token * @param _reserveToken reserve token * @param _poolAmount amount of pool tokens to protect * @param _reserveAmount amount of reserve tokens to protect * @return new protected liquidity id */ function addProtectedLiquidity( address _provider, IDSToken _poolToken, IERC20Token _reserveToken, uint256 _poolAmount, uint256 _reserveAmount ) internal returns (uint256) { // notify event subscribers if (address(eventsSubscriber) != address(0)) { eventsSubscriber.onAddingLiquidity(_provider, _poolToken, _reserveToken, _poolAmount, _reserveAmount); } Fraction memory rate = reserveTokenAverageRate(_poolToken, _reserveToken, true); stats.increaseTotalAmounts(_provider, _poolToken, _reserveToken, _poolAmount, _reserveAmount); stats.addProviderPool(_provider, _poolToken); return store.addProtectedLiquidity( _provider, _poolToken, _reserveToken, _poolAmount, _reserveAmount, rate.n, rate.d, time() ); } /** * @dev locks network tokens for the provider and emits the tokens locked event * * @param _provider tokens provider * @param _amount amount of network tokens */ function lockTokens(address _provider, uint256 _amount) internal { uint256 expirationTime = time().add(settings.lockDuration()); store.addLockedBalance(_provider, _amount, expirationTime); } /** * @dev returns the rate of 1 pool token in reserve token units * * @param _poolToken pool token * @param _reserveToken reserve token */ function poolTokenRate(IDSToken _poolToken, IERC20Token _reserveToken) internal view virtual returns (Fraction memory) { // get the pool token supply uint256 poolTokenSupply = _poolToken.totalSupply(); // get the reserve balance IConverter converter = IConverter(payable(ownedBy(_poolToken))); uint256 reserveBalance = converter.getConnectorBalance(_reserveToken); // for standard pools, 50% of the pool supply value equals the value of each reserve return Fraction({ n: reserveBalance.mul(2), d: poolTokenSupply }); } /** * @dev returns the average rate of 1 reserve token in the other reserve token units * * @param _poolToken pool token * @param _reserveToken reserve token * @param _validateAverageRate true to validate the average rate; false otherwise */ function reserveTokenAverageRate( IDSToken _poolToken, IERC20Token _reserveToken, bool _validateAverageRate ) internal view returns (Fraction memory) { (, , uint256 averageRateN, uint256 averageRateD) = reserveTokenRates(_poolToken, _reserveToken, _validateAverageRate); return Fraction(averageRateN, averageRateD); } /** * @dev returns the spot rate and average rate of 1 reserve token in the other reserve token units * * @param _poolToken pool token * @param _reserveToken reserve token * @param _validateAverageRate true to validate the average rate; false otherwise */ function reserveTokenRates( IDSToken _poolToken, IERC20Token _reserveToken, bool _validateAverageRate ) internal view returns ( uint256, uint256, uint256, uint256 ) { ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolToken))); IERC20Token otherReserve = converterOtherReserve(converter, _reserveToken); (uint256 spotRateN, uint256 spotRateD) = converterReserveBalances(converter, otherReserve, _reserveToken); (uint256 averageRateN, uint256 averageRateD) = converter.recentAverageRate(_reserveToken); require( !_validateAverageRate || averageRateInRange( spotRateN, spotRateD, averageRateN, averageRateD, settings.averageRateMaxDeviation() ), "ERR_INVALID_RATE" ); return (spotRateN, spotRateD, averageRateN, averageRateD); } /** * @dev returns the various rates between the reserves * * @param _poolToken pool token * @param _reserveToken reserve token * @param _addSpotRateN add spot rate numerator * @param _addSpotRateD add spot rate denominator * @param _validateAverageRate true to validate the average rate; false otherwise * @return see `struct PackedRates` */ function packRates( IDSToken _poolToken, IERC20Token _reserveToken, uint256 _addSpotRateN, uint256 _addSpotRateD, bool _validateAverageRate ) internal view returns (PackedRates memory) { (uint256 removeSpotRateN, uint256 removeSpotRateD, uint256 removeAverageRateN, uint256 removeAverageRateD) = reserveTokenRates(_poolToken, _reserveToken, _validateAverageRate); require( (_addSpotRateN <= MAX_UINT128 && _addSpotRateD <= MAX_UINT128) && (removeSpotRateN <= MAX_UINT128 && removeSpotRateD <= MAX_UINT128) && (removeAverageRateN <= MAX_UINT128 && removeAverageRateD <= MAX_UINT128), "ERR_INVALID_RATE" ); return PackedRates({ addSpotRateN: uint128(_addSpotRateN), addSpotRateD: uint128(_addSpotRateD), removeSpotRateN: uint128(removeSpotRateN), removeSpotRateD: uint128(removeSpotRateD), removeAverageRateN: uint128(removeAverageRateN), removeAverageRateD: uint128(removeAverageRateD) }); } /** * @dev returns whether or not the deviation of the average rate from the spot rate is within range * for example, if the maximum permitted deviation is 5%, then return `95/100 <= average/spot <= 100/95` * * @param _spotRateN spot rate numerator * @param _spotRateD spot rate denominator * @param _averageRateN average rate numerator * @param _averageRateD average rate denominator * @param _maxDeviation the maximum permitted deviation of the average rate from the spot rate */ function averageRateInRange( uint256 _spotRateN, uint256 _spotRateD, uint256 _averageRateN, uint256 _averageRateD, uint32 _maxDeviation ) internal pure returns (bool) { uint256 ppmDelta = PPM_RESOLUTION - _maxDeviation; uint256 min = _spotRateN.mul(_averageRateD).mul(ppmDelta).mul(ppmDelta); uint256 mid = _spotRateD.mul(_averageRateN).mul(ppmDelta).mul(PPM_RESOLUTION); uint256 max = _spotRateN.mul(_averageRateD).mul(PPM_RESOLUTION).mul(PPM_RESOLUTION); return min <= mid && mid <= max; } /** * @dev utility to add liquidity to a converter * * @param _converter converter * @param _reserveToken1 reserve token 1 * @param _reserveToken2 reserve token 2 * @param _reserveAmount1 reserve amount 1 * @param _reserveAmount2 reserve amount 2 * @param _value ETH amount to add */ function addLiquidity( ILiquidityPoolConverter _converter, IERC20Token _reserveToken1, IERC20Token _reserveToken2, uint256 _reserveAmount1, uint256 _reserveAmount2, uint256 _value ) internal { // ensure that the contract can receive ETH updatingLiquidity = true; IERC20Token[] memory reserveTokens = new IERC20Token[](2); uint256[] memory amounts = new uint256[](2); reserveTokens[0] = _reserveToken1; reserveTokens[1] = _reserveToken2; amounts[0] = _reserveAmount1; amounts[1] = _reserveAmount2; _converter.addLiquidity{ value: _value }(reserveTokens, amounts, 1); // ensure that the contract can receive ETH updatingLiquidity = false; } /** * @dev utility to remove liquidity from a converter * * @param _poolToken pool token of the converter * @param _poolAmount amount of pool tokens to remove * @param _reserveToken1 reserve token 1 * @param _reserveToken2 reserve token 2 */ function removeLiquidity( IDSToken _poolToken, uint256 _poolAmount, IERC20Token _reserveToken1, IERC20Token _reserveToken2 ) internal { ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolToken))); // ensure that the contract can receive ETH updatingLiquidity = true; IERC20Token[] memory reserveTokens = new IERC20Token[](2); uint256[] memory minReturns = new uint256[](2); reserveTokens[0] = _reserveToken1; reserveTokens[1] = _reserveToken2; minReturns[0] = 1; minReturns[1] = 1; converter.removeLiquidity(_poolAmount, reserveTokens, minReturns); // ensure that the contract can receive ETH updatingLiquidity = false; } /** * @dev returns a protected liquidity from the store * * @param _id protected liquidity id * @return protected liquidity */ function protectedLiquidity(uint256 _id) internal view returns (ProtectedLiquidity memory) { ProtectedLiquidity memory liquidity; ( liquidity.provider, liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount, liquidity.reserveRateN, liquidity.reserveRateD, liquidity.timestamp ) = store.protectedLiquidity(_id); return liquidity; } /** * @dev returns a protected liquidity from the store * * @param _id protected liquidity id * @param _provider authorized provider * @return protected liquidity */ function protectedLiquidity(uint256 _id, address _provider) internal view returns (ProtectedLiquidity memory) { ProtectedLiquidity memory liquidity = protectedLiquidity(_id); require(liquidity.provider == _provider, "ERR_ACCESS_DENIED"); return liquidity; } /** * @dev returns the protected amount of reserve tokens plus accumulated fee before compensation * * @param _poolAmount pool token amount when the liquidity was added * @param _poolRate rate of 1 pool token in the related reserve token units * @param _addRate rate of 1 reserve token in the other reserve token units when the liquidity was added * @param _removeRate rate of 1 reserve token in the other reserve token units when the liquidity is removed * @return protected amount of reserve tokens plus accumulated fee = sqrt(_removeRate / _addRate) * _poolRate * _poolAmount */ function protectedAmountPlusFee( uint256 _poolAmount, Fraction memory _poolRate, Fraction memory _addRate, Fraction memory _removeRate ) internal pure returns (uint256) { uint256 n = MathEx.ceilSqrt(_addRate.d.mul(_removeRate.n)).mul(_poolRate.n); uint256 d = MathEx.floorSqrt(_addRate.n.mul(_removeRate.d)).mul(_poolRate.d); uint256 x = n * _poolAmount; if (x / n == _poolAmount) { return x / d; } (uint256 hi, uint256 lo) = n > _poolAmount ? (n, _poolAmount) : (_poolAmount, n); (uint256 p, uint256 q) = MathEx.reducedRatio(hi, d, MAX_UINT256 / lo); uint256 min = (hi / d).mul(lo); if (q > 0) { return MathEx.max(min, (p * lo) / q); } return min; } /** * @dev returns the impermanent loss incurred due to the change in rates between the reserve tokens * * @param _prevRate previous rate between the reserves * @param _newRate new rate between the reserves * @return impermanent loss (as a ratio) */ function impLoss(Fraction memory _prevRate, Fraction memory _newRate) internal pure returns (Fraction memory) { uint256 ratioN = _newRate.n.mul(_prevRate.d); uint256 ratioD = _newRate.d.mul(_prevRate.n); uint256 prod = ratioN * ratioD; uint256 root = prod / ratioN == ratioD ? MathEx.floorSqrt(prod) : MathEx.floorSqrt(ratioN) * MathEx.floorSqrt(ratioD); uint256 sum = ratioN.add(ratioD); // the arithmetic below is safe because `x + y >= sqrt(x * y) * 2` if (sum % 2 == 0) { sum /= 2; return Fraction({ n: sum - root, d: sum }); } return Fraction({ n: sum - root * 2, d: sum }); } /** * @dev returns the protection level based on the timestamp and protection delays * * @param _addTimestamp time at which the liquidity was added * @param _removeTimestamp time at which the liquidity is removed * @return protection level (as a ratio) */ function protectionLevel(uint256 _addTimestamp, uint256 _removeTimestamp) internal view returns (Fraction memory) { uint256 timeElapsed = _removeTimestamp.sub(_addTimestamp); uint256 minProtectionDelay = settings.minProtectionDelay(); uint256 maxProtectionDelay = settings.maxProtectionDelay(); if (timeElapsed < minProtectionDelay) { return Fraction({ n: 0, d: 1 }); } if (timeElapsed >= maxProtectionDelay) { return Fraction({ n: 1, d: 1 }); } return Fraction({ n: timeElapsed, d: maxProtectionDelay }); } /** * @dev returns the compensation amount based on the impermanent loss and the protection level * * @param _amount protected amount in units of the reserve token * @param _total amount plus fee in units of the reserve token * @param _loss protection level (as a ratio between 0 and 1) * @param _level impermanent loss (as a ratio between 0 and 1) * @return compensation amount */ function compensationAmount( uint256 _amount, uint256 _total, Fraction memory _loss, Fraction memory _level ) internal pure returns (uint256) { uint256 levelN = _level.n.mul(_amount); uint256 levelD = _level.d; uint256 maxVal = MathEx.max(MathEx.max(levelN, levelD), _total); (uint256 lossN, uint256 lossD) = MathEx.reducedRatio(_loss.n, _loss.d, MAX_UINT256 / maxVal); return _total.mul(lossD.sub(lossN)).div(lossD).add(lossN.mul(levelN).div(lossD.mul(levelD))); } function getNetworkCompensation( uint256 _targetAmount, uint256 _baseAmount, PackedRates memory _packedRates ) internal view returns (uint256) { if (_targetAmount <= _baseAmount) { return 0; } // calculate the delta in network tokens uint256 delta = (_targetAmount - _baseAmount).mul(_packedRates.removeAverageRateN).div(_packedRates.removeAverageRateD); // the delta might be very small due to precision loss // in which case no compensation will take place (gas optimization) if (delta >= settings.minNetworkCompensation()) { return delta; } return 0; } /** * @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't. * note that we use the non standard erc-20 interface in which `approve` has no return value so that * this function will work for both standard and non standard tokens * * @param _token token to check the allowance in * @param _spender approved address * @param _value allowance amount */ function ensureAllowance( IERC20Token _token, address _spender, uint256 _value ) private { uint256 allowance = _token.allowance(address(this), _spender); if (allowance < _value) { if (allowance > 0) safeApprove(_token, _spender, 0); safeApprove(_token, _spender, _value); } } // utility to mint network tokens function mintNetworkTokens( address _owner, IConverterAnchor _poolAnchor, uint256 _amount ) private { networkTokenGovernance.mint(_owner, _amount); systemStore.incNetworkTokensMinted(_poolAnchor, _amount); } // utility to burn network tokens function burnNetworkTokens(IConverterAnchor _poolAnchor, uint256 _amount) private { networkTokenGovernance.burn(_amount); systemStore.decNetworkTokensMinted(_poolAnchor, _amount); } // utility to get the reserve balances function converterReserveBalances( IConverter _converter, IERC20Token _reserveToken1, IERC20Token _reserveToken2 ) private view returns (uint256, uint256) { return (_converter.getConnectorBalance(_reserveToken1), _converter.getConnectorBalance(_reserveToken2)); } // utility to get the other reserve function converterOtherReserve(IConverter _converter, IERC20Token _thisReserve) private view returns (IERC20Token) { IERC20Token otherReserve = _converter.connectorTokens(0); return otherReserve != _thisReserve ? otherReserve : _converter.connectorTokens(1); } // utility to get the owner function ownedBy(IOwned _owned) private view returns (address) { return _owned.owner(); } }
utility to burn network tokens
function burnNetworkTokens(IConverterAnchor _poolAnchor, uint256 _amount) private { networkTokenGovernance.burn(_amount); systemStore.decNetworkTokensMinted(_poolAnchor, _amount); }
2,294,322
[ 1, 1367, 560, 358, 18305, 2483, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 18305, 3906, 5157, 12, 45, 5072, 11605, 389, 6011, 11605, 16, 2254, 5034, 389, 8949, 13, 3238, 288, 203, 3639, 2483, 1345, 43, 1643, 82, 1359, 18, 70, 321, 24899, 8949, 1769, 203, 3639, 2619, 2257, 18, 4924, 3906, 5157, 49, 474, 329, 24899, 6011, 11605, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x65BCe046253f7B644a062252E89a8C2337F08A3d/sources/RewardEscrowV2.sol
Views Restricted functions Inheritance Internal references https:docs.peri.finance/contracts/RewardEscrow
contract RewardEscrowV2 is BaseRewardEscrowV2 { mapping(address => uint256) public totalBalancePendingMigration; bytes32 private constant CONTRACT_PERIFINANCE_BRIDGE_OPTIMISM = "PeriFinanceBridgeToOptimism"; bytes32 private constant CONTRACT_REWARD_ESCROW = "RewardEscrow"; bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; constructor(address _owner, address _resolver) public BaseRewardEscrowV2(_owner, _resolver) {} function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume); function requireSystemActive() external view; function requireIssuanceActive() external view; function requireExchangeActive() external view; function requireExchangeBetweenPynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function requirePynthActive(bytes32 currencyKey) external view; function requirePynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function systemSuspension() external view returns (bool suspended, uint248 reason); function issuanceSuspension() external view returns (bool suspended, uint248 reason); function exchangeSuspension() external view returns (bool suspended, uint248 reason); function pynthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function pynthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function getPynthExchangeSuspensions(bytes32[] calldata pynths) external view returns (bool[] memory exchangeSuspensions, uint256[] memory reasons); function getPynthSuspensions(bytes32[] calldata pynths) external view returns (bool[] memory suspensions, uint256[] memory reasons); function suspendPynth(bytes32 currencyKey, uint256 reason) external; function updateAccessControl( bytes32 section, address account, bool canSuspend, bool canResume ) external; } function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = BaseRewardEscrowV2.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](3); newAddresses[0] = CONTRACT_PERIFINANCE_BRIDGE_OPTIMISM; newAddresses[1] = CONTRACT_REWARD_ESCROW; newAddresses[2] = CONTRACT_SYSTEMSTATUS; return combineArrays(existingAddresses, newAddresses); } function periFinanceBridgeToOptimism() internal view returns (address) { return requireAndGetAddress(CONTRACT_PERIFINANCE_BRIDGE_OPTIMISM); } function oldRewardEscrow() internal view returns (IRewardEscrow) { return IRewardEscrow(requireAndGetAddress(CONTRACT_REWARD_ESCROW)); } function systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } uint internal constant TIME_INDEX = 0; uint internal constant QUANTITY_INDEX = 1; function setMigrateEntriesThresholdAmount(uint amount) external onlyOwner { migrateEntriesThresholdAmount = amount; emit MigrateEntriesThresholdAmountUpdated(amount); } function migrateVestingSchedule(address addressToMigrate) external systemActive { require(totalBalancePendingMigration[addressToMigrate] > 0, "No escrow migration pending"); require(totalEscrowedAccountBalance[addressToMigrate] > 0, "Address escrow balance is 0"); if (totalBalancePendingMigration[addressToMigrate] <= migrateEntriesThresholdAmount) { _importVestingEntry( addressToMigrate, VestingEntries.VestingEntry({ endTime: uint64(block.timestamp), escrowAmount: totalBalancePendingMigration[addressToMigrate] }) ); uint numEntries = oldRewardEscrow().numVestingEntries(addressToMigrate); for (uint i = 1; i <= numEntries; i++) { uint[2] memory vestingSchedule = oldRewardEscrow().getVestingScheduleEntry(addressToMigrate, numEntries - i); uint time = vestingSchedule[TIME_INDEX]; uint amount = vestingSchedule[QUANTITY_INDEX]; if (time < block.timestamp) { break; } addressToMigrate, ); } } } function migrateVestingSchedule(address addressToMigrate) external systemActive { require(totalBalancePendingMigration[addressToMigrate] > 0, "No escrow migration pending"); require(totalEscrowedAccountBalance[addressToMigrate] > 0, "Address escrow balance is 0"); if (totalBalancePendingMigration[addressToMigrate] <= migrateEntriesThresholdAmount) { _importVestingEntry( addressToMigrate, VestingEntries.VestingEntry({ endTime: uint64(block.timestamp), escrowAmount: totalBalancePendingMigration[addressToMigrate] }) ); uint numEntries = oldRewardEscrow().numVestingEntries(addressToMigrate); for (uint i = 1; i <= numEntries; i++) { uint[2] memory vestingSchedule = oldRewardEscrow().getVestingScheduleEntry(addressToMigrate, numEntries - i); uint time = vestingSchedule[TIME_INDEX]; uint amount = vestingSchedule[QUANTITY_INDEX]; if (time < block.timestamp) { break; } addressToMigrate, ); } } } function migrateVestingSchedule(address addressToMigrate) external systemActive { require(totalBalancePendingMigration[addressToMigrate] > 0, "No escrow migration pending"); require(totalEscrowedAccountBalance[addressToMigrate] > 0, "Address escrow balance is 0"); if (totalBalancePendingMigration[addressToMigrate] <= migrateEntriesThresholdAmount) { _importVestingEntry( addressToMigrate, VestingEntries.VestingEntry({ endTime: uint64(block.timestamp), escrowAmount: totalBalancePendingMigration[addressToMigrate] }) ); uint numEntries = oldRewardEscrow().numVestingEntries(addressToMigrate); for (uint i = 1; i <= numEntries; i++) { uint[2] memory vestingSchedule = oldRewardEscrow().getVestingScheduleEntry(addressToMigrate, numEntries - i); uint time = vestingSchedule[TIME_INDEX]; uint amount = vestingSchedule[QUANTITY_INDEX]; if (time < block.timestamp) { break; } addressToMigrate, ); } } } delete totalBalancePendingMigration[addressToMigrate]; } else { function migrateVestingSchedule(address addressToMigrate) external systemActive { require(totalBalancePendingMigration[addressToMigrate] > 0, "No escrow migration pending"); require(totalEscrowedAccountBalance[addressToMigrate] > 0, "Address escrow balance is 0"); if (totalBalancePendingMigration[addressToMigrate] <= migrateEntriesThresholdAmount) { _importVestingEntry( addressToMigrate, VestingEntries.VestingEntry({ endTime: uint64(block.timestamp), escrowAmount: totalBalancePendingMigration[addressToMigrate] }) ); uint numEntries = oldRewardEscrow().numVestingEntries(addressToMigrate); for (uint i = 1; i <= numEntries; i++) { uint[2] memory vestingSchedule = oldRewardEscrow().getVestingScheduleEntry(addressToMigrate, numEntries - i); uint time = vestingSchedule[TIME_INDEX]; uint amount = vestingSchedule[QUANTITY_INDEX]; if (time < block.timestamp) { break; } addressToMigrate, ); } } } function migrateVestingSchedule(address addressToMigrate) external systemActive { require(totalBalancePendingMigration[addressToMigrate] > 0, "No escrow migration pending"); require(totalEscrowedAccountBalance[addressToMigrate] > 0, "Address escrow balance is 0"); if (totalBalancePendingMigration[addressToMigrate] <= migrateEntriesThresholdAmount) { _importVestingEntry( addressToMigrate, VestingEntries.VestingEntry({ endTime: uint64(block.timestamp), escrowAmount: totalBalancePendingMigration[addressToMigrate] }) ); uint numEntries = oldRewardEscrow().numVestingEntries(addressToMigrate); for (uint i = 1; i <= numEntries; i++) { uint[2] memory vestingSchedule = oldRewardEscrow().getVestingScheduleEntry(addressToMigrate, numEntries - i); uint time = vestingSchedule[TIME_INDEX]; uint amount = vestingSchedule[QUANTITY_INDEX]; if (time < block.timestamp) { break; } addressToMigrate, ); } } } _importVestingEntry( VestingEntries.VestingEntry({endTime: uint64(time), escrowAmount: amount}) totalBalancePendingMigration[addressToMigrate] = totalBalancePendingMigration[addressToMigrate].sub(amount); function importVestingSchedule(address[] calldata accounts, uint256[] calldata escrowAmounts) external onlyDuringSetup onlyOwner { require(accounts.length == escrowAmounts.length, "Account and escrowAmounts Length mismatch"); for (uint i = 0; i < accounts.length; i++) { address addressToMigrate = accounts[i]; uint256 escrowAmount = escrowAmounts[i]; require(totalEscrowedAccountBalance[addressToMigrate] > 0, "Address escrow balance is 0"); require(totalBalancePendingMigration[addressToMigrate] > 0, "No escrow migration pending"); _importVestingEntry( addressToMigrate, ); totalBalancePendingMigration[addressToMigrate] = totalBalancePendingMigration[addressToMigrate].sub( escrowAmount ); emit ImportedVestingSchedule(addressToMigrate, block.timestamp, escrowAmount); } function importVestingSchedule(address[] calldata accounts, uint256[] calldata escrowAmounts) external onlyDuringSetup onlyOwner { require(accounts.length == escrowAmounts.length, "Account and escrowAmounts Length mismatch"); for (uint i = 0; i < accounts.length; i++) { address addressToMigrate = accounts[i]; uint256 escrowAmount = escrowAmounts[i]; require(totalEscrowedAccountBalance[addressToMigrate] > 0, "Address escrow balance is 0"); require(totalBalancePendingMigration[addressToMigrate] > 0, "No escrow migration pending"); _importVestingEntry( addressToMigrate, ); totalBalancePendingMigration[addressToMigrate] = totalBalancePendingMigration[addressToMigrate].sub( escrowAmount ); emit ImportedVestingSchedule(addressToMigrate, block.timestamp, escrowAmount); } VestingEntries.VestingEntry({endTime: uint64(block.timestamp), escrowAmount: escrowAmount}) } function migrateAccountEscrowBalances( address[] calldata accounts, uint256[] calldata escrowBalances, uint256[] calldata vestedBalances ) external onlyDuringSetup onlyOwner { require(accounts.length == escrowBalances.length, "Number of accounts and balances don't match"); require(accounts.length == vestedBalances.length, "Number of accounts and vestedBalances don't match"); for (uint i = 0; i < accounts.length; i++) { address account = accounts[i]; uint escrowedAmount = escrowBalances[i]; uint vestedAmount = vestedBalances[i]; require(totalBalancePendingMigration[account] == 0, "Account migration is pending already"); totalEscrowedBalance = totalEscrowedBalance.add(escrowedAmount); totalEscrowedAccountBalance[account] = totalEscrowedAccountBalance[account].add(escrowedAmount); totalVestedAccountBalance[account] = totalVestedAccountBalance[account].add(vestedAmount); totalBalancePendingMigration[account] = escrowedAmount; emit MigratedAccountEscrow(account, escrowedAmount, vestedAmount, now); } function migrateAccountEscrowBalances( address[] calldata accounts, uint256[] calldata escrowBalances, uint256[] calldata vestedBalances ) external onlyDuringSetup onlyOwner { require(accounts.length == escrowBalances.length, "Number of accounts and balances don't match"); require(accounts.length == vestedBalances.length, "Number of accounts and vestedBalances don't match"); for (uint i = 0; i < accounts.length; i++) { address account = accounts[i]; uint escrowedAmount = escrowBalances[i]; uint vestedAmount = vestedBalances[i]; require(totalBalancePendingMigration[account] == 0, "Account migration is pending already"); totalEscrowedBalance = totalEscrowedBalance.add(escrowedAmount); totalEscrowedAccountBalance[account] = totalEscrowedAccountBalance[account].add(escrowedAmount); totalVestedAccountBalance[account] = totalVestedAccountBalance[account].add(vestedAmount); totalBalancePendingMigration[account] = escrowedAmount; emit MigratedAccountEscrow(account, escrowedAmount, vestedAmount, now); } } function _importVestingEntry(address account, VestingEntries.VestingEntry memory entry) internal { uint entryID = BaseRewardEscrowV2._addVestingEntry(account, entry); emit ImportedVestingEntry(account, entryID, entry.escrowAmount, entry.endTime); } function burnForMigration(address account, uint[] calldata entryIDs) external onlyPeriFinanceBridge returns (uint256 escrowedAccountBalance, VestingEntries.VestingEntry[] memory vestingEntries) { require(entryIDs.length > 0, "Entry IDs required"); vestingEntries = new VestingEntries.VestingEntry[](entryIDs.length); for (uint i = 0; i < entryIDs.length; i++) { VestingEntries.VestingEntry storage entry = vestingSchedules[account][entryIDs[i]]; if (entry.escrowAmount > 0) { vestingEntries[i] = entry; escrowedAccountBalance = escrowedAccountBalance.add(entry.escrowAmount); delete vestingSchedules[account][entryIDs[i]]; } if (escrowedAccountBalance > 0) { _reduceAccountEscrowBalances(account, escrowedAccountBalance); IERC20(address(periFinance())).transfer(periFinanceBridgeToOptimism(), escrowedAccountBalance); } emit BurnedForMigrationToL2(account, entryIDs, escrowedAccountBalance, block.timestamp); return (escrowedAccountBalance, vestingEntries); } function burnForMigration(address account, uint[] calldata entryIDs) external onlyPeriFinanceBridge returns (uint256 escrowedAccountBalance, VestingEntries.VestingEntry[] memory vestingEntries) { require(entryIDs.length > 0, "Entry IDs required"); vestingEntries = new VestingEntries.VestingEntry[](entryIDs.length); for (uint i = 0; i < entryIDs.length; i++) { VestingEntries.VestingEntry storage entry = vestingSchedules[account][entryIDs[i]]; if (entry.escrowAmount > 0) { vestingEntries[i] = entry; escrowedAccountBalance = escrowedAccountBalance.add(entry.escrowAmount); delete vestingSchedules[account][entryIDs[i]]; } if (escrowedAccountBalance > 0) { _reduceAccountEscrowBalances(account, escrowedAccountBalance); IERC20(address(periFinance())).transfer(periFinanceBridgeToOptimism(), escrowedAccountBalance); } emit BurnedForMigrationToL2(account, entryIDs, escrowedAccountBalance, block.timestamp); return (escrowedAccountBalance, vestingEntries); } function burnForMigration(address account, uint[] calldata entryIDs) external onlyPeriFinanceBridge returns (uint256 escrowedAccountBalance, VestingEntries.VestingEntry[] memory vestingEntries) { require(entryIDs.length > 0, "Entry IDs required"); vestingEntries = new VestingEntries.VestingEntry[](entryIDs.length); for (uint i = 0; i < entryIDs.length; i++) { VestingEntries.VestingEntry storage entry = vestingSchedules[account][entryIDs[i]]; if (entry.escrowAmount > 0) { vestingEntries[i] = entry; escrowedAccountBalance = escrowedAccountBalance.add(entry.escrowAmount); delete vestingSchedules[account][entryIDs[i]]; } if (escrowedAccountBalance > 0) { _reduceAccountEscrowBalances(account, escrowedAccountBalance); IERC20(address(periFinance())).transfer(periFinanceBridgeToOptimism(), escrowedAccountBalance); } emit BurnedForMigrationToL2(account, entryIDs, escrowedAccountBalance, block.timestamp); return (escrowedAccountBalance, vestingEntries); } } function burnForMigration(address account, uint[] calldata entryIDs) external onlyPeriFinanceBridge returns (uint256 escrowedAccountBalance, VestingEntries.VestingEntry[] memory vestingEntries) { require(entryIDs.length > 0, "Entry IDs required"); vestingEntries = new VestingEntries.VestingEntry[](entryIDs.length); for (uint i = 0; i < entryIDs.length; i++) { VestingEntries.VestingEntry storage entry = vestingSchedules[account][entryIDs[i]]; if (entry.escrowAmount > 0) { vestingEntries[i] = entry; escrowedAccountBalance = escrowedAccountBalance.add(entry.escrowAmount); delete vestingSchedules[account][entryIDs[i]]; } if (escrowedAccountBalance > 0) { _reduceAccountEscrowBalances(account, escrowedAccountBalance); IERC20(address(periFinance())).transfer(periFinanceBridgeToOptimism(), escrowedAccountBalance); } emit BurnedForMigrationToL2(account, entryIDs, escrowedAccountBalance, block.timestamp); return (escrowedAccountBalance, vestingEntries); } modifier onlyPeriFinanceBridge() { require(msg.sender == periFinanceBridgeToOptimism(), "Can only be invoked by PeriFinanceBridgeToOptimism contract"); _; } modifier systemActive() { systemStatus().requireSystemActive(); _; } event ImportedVestingSchedule(address indexed account, uint time, uint escrowAmount); event BurnedForMigrationToL2(address indexed account, uint[] entryIDs, uint escrowedAmountMigrated, uint time); event ImportedVestingEntry(address indexed account, uint entryID, uint escrowAmount, uint endTime); event MigrateEntriesThresholdAmountUpdated(uint newAmount); event MigratedAccountEscrow(address indexed account, uint escrowedAmount, uint vestedAmount, uint time); }
16,510,740
[ 1, 9959, 29814, 4186, 25953, 1359, 3186, 5351, 2333, 30, 8532, 18, 457, 77, 18, 926, 1359, 19, 16351, 87, 19, 17631, 1060, 6412, 492, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 534, 359, 1060, 6412, 492, 58, 22, 353, 3360, 17631, 1060, 6412, 492, 58, 22, 288, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 2078, 13937, 8579, 10224, 31, 203, 203, 203, 203, 565, 1731, 1578, 3238, 5381, 8020, 2849, 1268, 67, 3194, 5501, 706, 4722, 67, 7192, 734, 7113, 67, 15620, 3445, 5127, 49, 273, 315, 2173, 77, 6187, 1359, 13691, 774, 13930, 6228, 14432, 203, 565, 1731, 1578, 3238, 5381, 8020, 2849, 1268, 67, 862, 21343, 67, 41, 2312, 11226, 273, 315, 17631, 1060, 6412, 492, 14432, 203, 565, 1731, 1578, 3238, 5381, 8020, 2849, 1268, 67, 14318, 8608, 273, 315, 3163, 1482, 14432, 203, 203, 203, 203, 203, 565, 3885, 12, 2867, 389, 8443, 16, 1758, 389, 14122, 13, 1071, 3360, 17631, 1060, 6412, 492, 58, 22, 24899, 8443, 16, 389, 14122, 13, 2618, 203, 565, 445, 2006, 3367, 12, 3890, 1578, 2442, 16, 1758, 2236, 13, 3903, 1476, 1135, 261, 6430, 848, 55, 18815, 16, 1426, 848, 20911, 1769, 203, 203, 565, 445, 2583, 3163, 3896, 1435, 3903, 1476, 31, 203, 203, 565, 445, 2583, 7568, 89, 1359, 3896, 1435, 3903, 1476, 31, 203, 203, 565, 445, 2583, 11688, 3896, 1435, 3903, 1476, 31, 203, 203, 565, 445, 2583, 11688, 11831, 52, 878, 451, 87, 5042, 12, 3890, 1578, 1084, 7623, 653, 16, 1731, 1578, 2929, 7623, 653, 13, 3903, 1476, 31, 203, 203, 565, 445, 2583, 52, 878, 451, 3896, 12, 3890, 1578, 5462, 653, 13, 3903, 1476, 31, 203, 203, 565, 445, 2583, 52, 878, 2 ]
./full_match/44787/0xFc4feC9521556b3ee5CB696CEB9A16C40297194d/sources/src/vaults/SpiralsCeloImpactVault.sol
* @dev Returns StableToken contract (cUSD)./
function getStableToken() internal view returns (IERC20Upgradeable) { address stableTokenAddr = IRegistry(c_celoRegistry) .getAddressForStringOrDie("StableToken"); return IERC20Upgradeable(stableTokenAddr); }
13,280,225
[ 1, 1356, 934, 429, 1345, 6835, 261, 71, 3378, 40, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 21491, 429, 1345, 1435, 2713, 1476, 1135, 261, 45, 654, 39, 3462, 10784, 429, 13, 288, 203, 3639, 1758, 14114, 1345, 3178, 273, 467, 4243, 12, 71, 67, 2183, 83, 4243, 13, 203, 5411, 263, 588, 1887, 1290, 780, 28850, 2932, 30915, 1345, 8863, 203, 3639, 327, 467, 654, 39, 3462, 10784, 429, 12, 15021, 1345, 3178, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.6; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol pragma solidity ^0.8.6; /* * @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.8.6; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/IERC20Metadata.sol pragma solidity ^0.8.6; /** * @dev Interface for the optional metadata functions from the ERC20 standard. */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol pragma solidity ^0.8.6; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } pragma solidity ^0.8.6; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } // Token Contract pragma solidity 0.8.6; // Pass the token name ,token symbol and token supply as parameters contract MyToken is ERC20, ERC20Burnable, Ownable{ constructor( string memory name_, string memory symbol_, uint256 totalSupply_ ) ERC20(name_, symbol_){ totalSupply_ = totalSupply_ * (10**uint256(18)); if (totalSupply_ > 0) { _mint(owner(), totalSupply_); } } //function to mint function mint(address to, uint256 amount) public onlyOwner { _mint(to, 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}./
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; } 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 18; } 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); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _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"); _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"); _balances[sender] = senderBalance - amount; _balances[recipient] += 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 += amount; _balances[account] += 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); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
6,836
[ 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, 16, 467, 654, 39, 3462, 2277, 288, 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, 203, 97, 203, 203, 565, 3885, 261, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 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, 6549, 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, 63, 4631, 15533, 203, 565, 289, 203, 203, 565, 445, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import './IERC777Token.sol'; import './IMintableToken.sol'; import './Ownable.sol'; import './SafeMath.sol'; /** * @dev Implementation of the IERC777 Token Interface. */ contract DaoToken is IERC777Token, IMintableToken, Ownable { // Token name string internal tokenName; // Token symbol string internal tokenSymbol; // Token total supply uint256 internal tokenTotalSupply; // Token granularity uint256 internal tokenGranularity; // Token holders address[] internal tokenHoldersList; // Balances of each token holder mapping(address => uint256) internal tokenHoldersBalances; // Default token operators address[] internal defaultTokenOperators; // Flag token as mintable or not at the moment bool internal tokenMintable; /** * @dev Initialize token on contract deployment. */ constructor() Ownable() { // set basic token attributes tokenName = 'EESTEC LC Zagreb'; tokenSymbol = 'EZG'; tokenGranularity = 1; // set token holder and initial supply tokenMintable = false; tokenTotalSupply = 1; tokenHoldersBalances[msg.sender] = 1; tokenHoldersList.push(msg.sender); } /** * @notice Gets the token name. * @return the token name */ function name() external view override returns (string memory) { return tokenName; } /** * @notice Gets the token symbol. * @return the token symbol */ function symbol() external view override returns (string memory) { return tokenSymbol; } /** * @notice Gets the total number of minted tokens. * @return the total supply of tokens */ function totalSupply() external view override returns (uint256) { return tokenTotalSupply; } /** * @notice Gets the balance of the account with address holder. * @param holder the address of token holder for which the balance is returned * @return the balance of token holder */ function balanceOf(address holder) external view override returns (uint256) { return tokenHoldersBalances[holder]; } /** * @notice Return all token holders who hold token. * @return addresses of holders */ function tokenHolders() external view returns (address[] memory) { return tokenHoldersList; } /** * @notice Gets the smallest part of the token that is not divisible. * @return the token granularity */ function granularity() external view override returns (uint256) { return tokenGranularity; } /** * @notice Gets the list of addresses which are allowed to operate with tokens on behalf of some holder. * @return the token operators */ function defaultOperators() external view override returns (address[] memory) { return defaultTokenOperators; } /** * @notice Check if operator of holder. * @dev Check whether the operator is allowed to manage tokens held by the holder address. * @param operator the address of the operator * @param holder the address of the token holder * @return true if the operator is allowed to manage tokens of holder */ function isOperatorFor(address operator, address holder) external view override returns (bool) { return false; } /** * @dev Authorize an operator to manage tokens of the sender (caller's address). * @param operator the operator's address that will be authorized */ function authorizeOperator(address operator) external override {} /** * @dev Revoke an operator's rights to manage tokens of the sender (caller's address). * @param operator the operator's address that will be revoked */ function revokeOperator(address operator) external override {} /** * @dev Move amount of tokens from the sender's (caller's) address to recipient's address. * @param to the address of recipient * @param amount number of tokens to move * @param data data generated by the holder */ function send( address to, uint256 amount, bytes calldata data ) external override {} /** * @dev Move amount of tokens on behalf of the address from to address to. * @param from the address holding tokens * @param to the address of the recipient * @param amount number of tokens to send * @param data data generated by the holder * @param operatorData data generated by the operator */ function operatorSend( address from, address to, uint256 amount, bytes calldata data, bytes calldata operatorData ) external override {} /** * @dev Destroys amount of tokens from the sender’s account (caller's address), reducing the total supply. * @param amount number of tokens to burn * @param data data generated by the holder */ function burn(uint256 amount, bytes calldata data) external override {} /** * @dev Burn amount of tokens on behalf of the address from. * @param from the address holding tokens * @param amount number of tokens to burn * @param data data generated by the holder * @param operatorData data generated by the operator */ function operatorBurn( address from, uint256 amount, bytes calldata data, bytes calldata operatorData ) external override {} /** * @dev Verify that token is mintable before minting. */ modifier mintEnabled { require(tokenMintable, 'Token is not mintable at the moment'); _; } /** * @notice Mint yourself a token. * @dev Mint exactly one token for caller's address if one hasn't minted already. */ function mint() external override mintEnabled { if (tokenHoldersBalances[msg.sender] == 0) { tokenTotalSupply = SafeMath.add(tokenTotalSupply, 1); tokenHoldersBalances[msg.sender] = 1; tokenHoldersList.push(msg.sender); } else { revert('You already have a token'); } } /** * @notice Check whether the token is mintable or not. * @return true if token is mintable */ function isMintable() external view override returns (bool) { return tokenMintable; } /** * @notice Enable token minting for public. */ function enableMinting() external override onlyOwner { if (!tokenMintable) { tokenMintable = true; } else { revert('Token minting is already enabled'); } } /** * @notice Disable token minting for public. */ function disableMinting() external override onlyOwner { if (tokenMintable) { tokenMintable = false; } else { revert('Token minting is already disabled'); } } }
* @dev Destroys amount of tokens from the sender’s account (caller's address), reducing the total supply. @param amount number of tokens to burn @param data data generated by the holder/
function burn(uint256 amount, bytes calldata data) external override {}
2,522,103
[ 1, 9378, 28599, 3844, 434, 2430, 628, 326, 5793, 163, 227, 252, 87, 2236, 261, 16140, 1807, 1758, 3631, 9299, 2822, 326, 2078, 14467, 18, 225, 3844, 1300, 434, 2430, 358, 18305, 225, 501, 501, 4374, 635, 326, 10438, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18305, 12, 11890, 5034, 3844, 16, 1731, 745, 892, 501, 13, 3903, 3849, 2618, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * Copyright 2016 Everex https://everex.io * * 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. */ /* String utility library */ library strUtils { string constant CHAINY_JSON_ID = '"id":"CHAINY"'; uint8 constant CHAINY_JSON_MIN_LEN = 32; /* Converts given number to base58, limited by _maxLength symbols */ function toBase58(uint256 _value, uint8 _maxLength) internal returns (string) { string memory letters = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"; bytes memory alphabet = bytes(letters); uint8 base = 58; uint8 len = 0; uint256 remainder = 0; bool needBreak = false; bytes memory bytesReversed = bytes(new string(_maxLength)); for (uint8 i = 0; i < _maxLength; i++) { if(_value < base){ needBreak = true; } remainder = _value % base; _value = uint256(_value / base); bytesReversed[i] = alphabet[remainder]; len++; if(needBreak){ break; } } // Reverse bytes memory result = bytes(new string(len)); for (i = 0; i < len; i++) { result[i] = bytesReversed[len - i - 1]; } return string(result); } /* Concatenates two strings */ function concat(string _s1, string _s2) internal returns (string) { bytes memory bs1 = bytes(_s1); bytes memory bs2 = bytes(_s2); string memory s3 = new string(bs1.length + bs2.length); bytes memory bs3 = bytes(s3); uint256 j = 0; for (uint256 i = 0; i < bs1.length; i++) { bs3[j++] = bs1[i]; } for (i = 0; i < bs2.length; i++) { bs3[j++] = bs2[i]; } return string(bs3); } /* Checks if provided JSON string has valid Chainy format */ function isValidChainyJson(string _json) internal returns (bool) { bytes memory json = bytes(_json); bytes memory id = bytes(CHAINY_JSON_ID); if (json.length < CHAINY_JSON_MIN_LEN) { return false; } else { uint len = 0; if (json[1] == id[0]) { len = 1; while (len < id.length && (1 + len) < json.length && json[1 + len] == id[len]) { len++; } if (len == id.length) { return true; } } } return false; } } // Ownership contract owned { address public owner; function owned() { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) throw; _ } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } } contract Chainy is owned { // Chainy viewer url string CHAINY_URL; // Configuration mapping(string => uint256) private chainyConfig; // Service accounts mapping (address => bool) private srvAccount; // Fee receiver address private receiverAddress; struct data {uint256 timestamp; string json; address sender;} mapping (string => data) private chainy; event chainyShortLink(uint256 timestamp, string code); // Constructor function Chainy(){ setConfig("fee", 0); // change the block offset to 1000000 to use contract in testnet setConfig("blockoffset", 2000000); setChainyURL("https://txn.me/"); } // Sets new Chainy viewer URL function setChainyURL(string _url) onlyOwner { CHAINY_URL = _url; } // Returns current Chainy viewer URL function getChainyURL() constant returns(string){ return CHAINY_URL; } // Sets configuration option function setConfig(string _key, uint256 _value) onlyOwner { chainyConfig[_key] = _value; } // Returns configuration option function getConfig(string _key) constant returns (uint256 _value) { return chainyConfig[_key]; } // Add/Remove service account function setServiceAccount(address _address, bool _value) onlyOwner { srvAccount[_address] = _value; } // Set receiver address function setReceiverAddress(address _address) onlyOwner { receiverAddress = _address; } // Send all ether back to owner function releaseFunds() onlyOwner { if(!owner.send(this.balance)) throw; } // Add record function addChainyData(string json) { checkFormat(json); var code = generateShortLink(); // Checks if the record exist if (getChainyTimestamp(code) > 0) throw; processFee(); chainy[code] = data({ timestamp: block.timestamp, json: json, sender: tx.origin }); // Fire event var link = strUtils.concat(CHAINY_URL, code); chainyShortLink(block.timestamp, link); } // Get record timestamp function getChainyTimestamp(string code) constant returns (uint256) { return chainy[code].timestamp; } // Get record JSON function getChainyData(string code) constant returns (string) { return chainy[code].json; } // Get record sender function getChainySender(string code) constant returns (address) { return chainy[code].sender; } // Checks if enough fee provided function processFee() internal { var fee = getConfig("fee"); if (srvAccount[msg.sender] || (fee == 0)) return; if (msg.value < fee) throw; else if (!receiverAddress.send(fee)) throw; } // Checks if provided string has valid format function checkFormat(string json) internal { if (!strUtils.isValidChainyJson(json)) throw; } // Generates a shortlink code for this transaction function generateShortLink() internal returns (string) { var s1 = strUtils.toBase58(block.number - getConfig("blockoffset"), 11); var s2 = strUtils.toBase58(uint256(tx.origin), 2); var s = strUtils.concat(s1, s2); return s; } }
Sets configuration option
function setConfig(string _key, uint256 _value) onlyOwner { chainyConfig[_key] = _value; }
12,723,723
[ 1, 2785, 1664, 1456, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 15517, 12, 1080, 389, 856, 16, 2254, 5034, 389, 1132, 13, 1338, 5541, 288, 203, 3639, 2687, 93, 809, 63, 67, 856, 65, 273, 389, 1132, 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 ]
./full_match/11155111/0x260C2D98c4c14845d3B9283A0D2B21C150b2e766/sources/contracts/ERC1410Standard.sol
Declare the RedeemedByPartition event Declare the IssuedByPartition event
contract ERC1410Standard is ERC1410Operator { using SafeMath for uint256; event RedeemedByPartition( bytes32 indexed partition, address indexed operator, address indexed from, uint256 value ); event IssuedByPartition( bytes32 indexed partition, address indexed to, uint256 value ); function isOwner(address _account) external view returns (bool) { if (owner() == _account) { return true; return false; } } function isOwner(address _account) external view returns (bool) { if (owner() == _account) { return true; return false; } } } else { function isManager(address _manager) external view returns (bool) { return _isManager(_manager); } function _issueByPartition( bytes32 _partition, address _tokenHolder, uint256 _value ) internal whitelisted(_tokenHolder) { _validateParams(_partition, _value); require(_tokenHolder != address(0), "Invalid token receiver"); uint256 index = partitionToIndex[_tokenHolder][_partition]; if (index == 0) { partitions[_tokenHolder].push(Partition(_value, _partition)); partitionToIndex[_tokenHolder][_partition] = partitions[ _tokenHolder ].length; partitions[_tokenHolder][index - 1].amount = partitions[ _tokenHolder ][index - 1].amount.add(_value); } _totalSupply = _totalSupply.add(_value); balances[_tokenHolder] = balances[_tokenHolder].add(_value); emit IssuedByPartition(_partition, _tokenHolder, _value); } function _issueByPartition( bytes32 _partition, address _tokenHolder, uint256 _value ) internal whitelisted(_tokenHolder) { _validateParams(_partition, _value); require(_tokenHolder != address(0), "Invalid token receiver"); uint256 index = partitionToIndex[_tokenHolder][_partition]; if (index == 0) { partitions[_tokenHolder].push(Partition(_value, _partition)); partitionToIndex[_tokenHolder][_partition] = partitions[ _tokenHolder ].length; partitions[_tokenHolder][index - 1].amount = partitions[ _tokenHolder ][index - 1].amount.add(_value); } _totalSupply = _totalSupply.add(_value); balances[_tokenHolder] = balances[_tokenHolder].add(_value); emit IssuedByPartition(_partition, _tokenHolder, _value); } } else { function issueByPartition( bytes32 _partition, address _tokenHolder, uint256 _value ) external onlyOwnerOrManager { _issueByPartition(_partition, _tokenHolder, _value); } function operatorIssueByPartition( bytes32 _partition, address _tokenHolder, uint256 _value ) external onlyOperatorForPartition(_partition, msg.sender) { _issueByPartition(_partition, _tokenHolder, _value); } function redeemByPartition( bytes32 _partition, uint256 _value ) external onlyWhitelisted { _redeemByPartition(_partition, msg.sender, address(0), _value); } function operatorRedeemByPartition( bytes32 _partition, address _tokenHolder, uint256 _value ) external whitelisted(_tokenHolder) { require(_tokenHolder != address(0), "Invalid from address"); require( isOperator(msg.sender, _tokenHolder) || isOperatorForPartition(_partition, msg.sender, _tokenHolder), "Not authorized" ); _redeemByPartition(_partition, _tokenHolder, msg.sender, _value); } function _redeemByPartition( bytes32 _partition, address _from, address _operator, uint256 _value ) internal { _validateParams(_partition, _value); require(_validPartition(_partition, _from), "Invalid partition"); uint256 index = partitionToIndex[_from][_partition] - 1; require( partitions[_from][index].amount >= _value, "Insufficient value" ); if (partitions[_from][index].amount == _value) { _deletePartitionForHolder(_from, _partition, index); partitions[_from][index].amount = partitions[_from][index] .amount .sub(_value); } balances[_from] = balances[_from].sub(_value); _totalSupply = _totalSupply.sub(_value); _takeSnapshot( _getHolderSnapshots(_partition, _from), _partition, _balanceOfByPartition(_partition, _from), true ); _takeSnapshot( _getTotalSupplySnapshots(_partition), _partition, _totalSupplyByPartition(_partition), false ); emit RedeemedByPartition(_partition, _operator, _from, _value); } function _redeemByPartition( bytes32 _partition, address _from, address _operator, uint256 _value ) internal { _validateParams(_partition, _value); require(_validPartition(_partition, _from), "Invalid partition"); uint256 index = partitionToIndex[_from][_partition] - 1; require( partitions[_from][index].amount >= _value, "Insufficient value" ); if (partitions[_from][index].amount == _value) { _deletePartitionForHolder(_from, _partition, index); partitions[_from][index].amount = partitions[_from][index] .amount .sub(_value); } balances[_from] = balances[_from].sub(_value); _totalSupply = _totalSupply.sub(_value); _takeSnapshot( _getHolderSnapshots(_partition, _from), _partition, _balanceOfByPartition(_partition, _from), true ); _takeSnapshot( _getTotalSupplySnapshots(_partition), _partition, _totalSupplyByPartition(_partition), false ); emit RedeemedByPartition(_partition, _operator, _from, _value); } } else { function _deletePartitionForHolder( address _holder, bytes32 _partition, uint256 index ) internal { uint256 lastIndex = partitions[_holder].length - 1; if (index != lastIndex) { partitions[_holder][index] = partitions[_holder][lastIndex]; partitionToIndex[_holder][partitions[_holder][index].partition] = index + 1; } delete partitionToIndex[_holder][_partition]; partitions[_holder].pop(); _getHolderSnapshots(_partition, _holder), _partition, _balanceOfByPartition(_partition, _holder), true ); _getTotalSupplySnapshots(_partition), _partition, _totalSupplyByPartition(_partition), false ); } function _deletePartitionForHolder( address _holder, bytes32 _partition, uint256 index ) internal { uint256 lastIndex = partitions[_holder].length - 1; if (index != lastIndex) { partitions[_holder][index] = partitions[_holder][lastIndex]; partitionToIndex[_holder][partitions[_holder][index].partition] = index + 1; } delete partitionToIndex[_holder][_partition]; partitions[_holder].pop(); _getHolderSnapshots(_partition, _holder), _partition, _balanceOfByPartition(_partition, _holder), true ); _getTotalSupplySnapshots(_partition), _partition, _totalSupplyByPartition(_partition), false ); } _takeSnapshot( _takeSnapshot( function operatorTransferByPartition( bytes32 _partition, address _from, address _to, uint256 _value ) external onlyOperatorForPartition(_partition, msg.sender) whitelisted(_from) whitelisted(_to) returns (bytes32) { _transferByPartition(_from, _to, _value, _partition); return _partition; } function addManager(address _manager) public onlyOwner { _addManager(_manager); if (!_isWhitelisted(_manager)) { _addToWhitelist(_manager); } } function addManager(address _manager) public onlyOwner { _addManager(_manager); if (!_isWhitelisted(_manager)) { _addToWhitelist(_manager); } } function removeManager(address _manager) public onlyOwner { _removeManager(_manager); if (_isWhitelisted(_manager)) { _removeFromWhitelist(_manager); } } function removeManager(address _manager) public onlyOwner { _removeManager(_manager); if (_isWhitelisted(_manager)) { _removeFromWhitelist(_manager); } } function removeFromWhitelist( address account ) public virtual onlyOwnerOrManager { require(_balanceOf(account) == 0, "Balance not zero"); _removeFromWhitelist(account); } function isWhitelisted(address _address) external view returns (bool) { return _isWhitelisted(_address); } function totalSupplyByPartition( bytes32 _partition ) external view returns (uint256) { return _totalSupplyByPartition(_partition); } function _validateParams(bytes32 _partition, uint256 _value) internal pure { require(_value != uint256(0), "Zero value not allowed"); require(_partition != bytes32(0), "Invalid partition"); } }
3,791,819
[ 1, 3456, 834, 326, 868, 24903, 18696, 7003, 871, 16110, 834, 326, 9310, 5957, 858, 7003, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 4232, 39, 3461, 2163, 8336, 353, 4232, 39, 3461, 2163, 5592, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 871, 868, 24903, 18696, 7003, 12, 203, 3639, 1731, 1578, 8808, 3590, 16, 203, 3639, 1758, 8808, 3726, 16, 203, 3639, 1758, 8808, 628, 16, 203, 3639, 2254, 5034, 460, 203, 565, 11272, 203, 203, 565, 871, 9310, 5957, 858, 7003, 12, 203, 3639, 1731, 1578, 8808, 3590, 16, 203, 3639, 1758, 8808, 358, 16, 203, 3639, 2254, 5034, 460, 203, 565, 11272, 203, 203, 203, 565, 445, 353, 5541, 12, 2867, 389, 4631, 13, 3903, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 309, 261, 8443, 1435, 422, 389, 4631, 13, 288, 203, 5411, 327, 638, 31, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 353, 5541, 12, 2867, 389, 4631, 13, 3903, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 309, 261, 8443, 1435, 422, 389, 4631, 13, 288, 203, 5411, 327, 638, 31, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 3639, 289, 469, 288, 203, 565, 445, 353, 1318, 12, 2867, 389, 4181, 13, 3903, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 291, 1318, 24899, 4181, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 13882, 858, 7003, 12, 203, 3639, 1731, 1578, 389, 10534, 16, 203, 3639, 1758, 389, 2316, 6064, 16, 203, 3639, 2254, 5034, 389, 1132, 203, 565, 262, 2713, 26944, 24899, 2316, 6064, 13, 288, 203, 2 ]
pragma solidity ^0.4.15; import './SafeMath.sol'; import './ERC20.sol'; import './EnjinReceivingContract.sol'; /** * @title Enjin Coin Custom Tokens (Mint) Contract * @dev Handles minting of custom game tokens * todo DRAFT / Work in progress, monolithic design version * todo Economy of scale curve needs re-do because of solidity math limitations * todo Unit Tests */ contract CustomTokens { using SafeMath for uint256; // this multiplier is needed for the minimum exchange rate of 1 and used for all division uint256 multiplier = 10000; ERC20 enjinCoin; uint256 index = 0; struct Tokens { address creator; uint256 totalSupply; uint256 exchangeRate; uint8 decimals; string name; string icon; string data; mapping (address => uint256) balances; } // customTokenId => Tokens mapping (uint256 => Tokens) types; /** * Default fallback function */ function() { revert(); } /** * @dev Constructor * @param _enjinCoinToken Address of the deployed Enjin Coin ERC20 token contract */ function CustomTokens(address _enjinCoinToken) { enjinCoin = ERC20(_enjinCoinToken); } /** * @dev Require that only the token creator can execute this function * @param _customTokenId The ID number of the Custom Token */ function checkTokenCreator(uint256 _customTokenId) { require(msg.sender == types[_customTokenId].creator); } /** * @dev Get the balance of anyone's token * @param _customTokenId The ID number of the Custom Token * @return The _owner's token balance of the type requested */ function balanceOf(uint256 _customTokenId, address _owner) constant returns (uint256) { return types[_customTokenId].balances[_owner]; } /** * @dev Transfer Custom Tokens from a sender to an address * @param _customTokenId The ID number of the Custom Token * @param _to Address to send to * @param _value Number of tokens to send (omitting decimals) * @param _data Include data which will be passed to tokenFallback function */ function transfer(uint256 _customTokenId, address _to, uint256 _value, bytes _data) { uint256 codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } types[_customTokenId].balances[msg.sender] = types[_customTokenId].balances[msg.sender].sub(_value); types[_customTokenId].balances[_to] = types[_customTokenId].balances[_to].add(_value); if(codeLength>0) { EnjinReceivingContract receiver = EnjinReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } Transfer(_customTokenId, msg.sender, _to, _value, _data); } /** * @dev Standard function transfer similar to ERC20 transfer with no _data, added for backward-compatibility and simple transfers * @param _customTokenId The ID number of the Custom Token * @param _to Address to send to * @param _value Number of tokens to send (omitting decimals) */ function transfer(uint256 _customTokenId, address _to, uint256 _value) { uint256 codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } types[_customTokenId].balances[msg.sender] = types[_customTokenId].balances[msg.sender].sub(_value); types[_customTokenId].balances[_to] = types[_customTokenId].balances[_to].add(_value); bytes memory empty; // todo: see if we can just pass "" instead of this variable if(codeLength>0) { EnjinReceivingContract receiver = EnjinReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, empty); } Transfer(_customTokenId, msg.sender, _to, _value, empty); } /** * @dev Private function that transfers Custom Tokens between two addresses * @param _customTokenId The ID number of the Custom Token * @param _from Address to send from * @param _to Address to send to * @param _value Number of tokens to send (omitting decimals) */ function transferInternal(uint256 _customTokenId, address _from, address _to, uint256 _value) private { require(_to != address(0)); types[_customTokenId].balances[_from] = types[_customTokenId].balances[_from].sub(_value); types[_customTokenId].balances[_to] = types[_customTokenId].balances[_to].add(_value); } /** * @dev Create and mint a new Custom Token type, committing ENJ to the reserve and receiving the newly minted tokens * @param _totalSupply The total supply of Custom Tokens that will be created * @param _exchangeRate How many ENJ each unit is worth (using multiplier 10000) * @param _decimals Number of Decimal places (0 for indivisible items) * @param _name Human name of the item, ex. Sword of Satoshi * @param _icon URL to the 500x500px icon representing the item * @param _customData Optional data string to store custom game attributes in an item * @return index */ function createToken(uint256 _totalSupply, uint256 _exchangeRate, uint8 _decimals, string _name, string _icon, string _customData) returns (uint256) { require(_totalSupply > 0); // Economy-of-scale calculation forcing the minimum exchange rate to start at 1 ENJ : 1 Custom Token and then decrease w/ exponential decay // Check for <1 because of possible 0 with integer math - this results in the lowest exchange rate of 1 (w/multiplier) after 100,000,000 units // todo: Rewrite this with 100M/x for solidity int math and match the curve //require(_exchangeRate >= (_totalSupply ** (-5 / 10)) * multiplier && _exchangeRate > 0); // Check ENJ allowance that Mint may take from creator uint256 totalCost = _exchangeRate / multiplier * _totalSupply; require(enjinCoin.allowance(msg.sender, this) >= totalCost); // Take ENJ from creator enjinCoin.transferFrom(msg.sender, this, totalCost); // Register the new token index++; types[index] = Tokens( msg.sender, _totalSupply, _exchangeRate, _decimals, _name, _icon, _customData ); // Grant tokens to creator types[index].balances[msg.sender] = _totalSupply; // Event Create(index, msg.sender); return index; } /** * @dev Liquidate a custom token into ENJ. The Mint contract gains ownership of the liquidated custom tokens until re-minting by the creator * @param _customTokenId The ID number of the Custom Token * @param _value How many tokens to liquidate */ function liquidateToken(uint256 _customTokenId, uint256 _value) { // todo: We may want another function signature that liquidates and transfers to a specific address instead of original sender require(types[_customTokenId].balances[msg.sender] >= _value); transferInternal(_customTokenId, msg.sender, this, _value); enjinCoin.transferFrom(this, msg.sender, types[_customTokenId].exchangeRate / multiplier * _value); // todo: check this calculation carefully Liquidate(_customTokenId, msg.sender, _value); } /** * @dev Re-mint any custom tokens that have been taken out of circulation * @param _customTokenId The ID number of the Custom Token * @param _value How many tokens to mint */ function mintToken(uint256 _customTokenId, uint256 _value) { checkTokenCreator(_customTokenId); // Ensure enough tokens have been liquidated and are held for re-minting require(types[_customTokenId].balances[this] <= _value); // Check ENJ allowance that Mint may take from creator uint256 totalCost = types[_customTokenId].exchangeRate / multiplier * _value; require(enjinCoin.allowance(msg.sender, this) >= totalCost); // Take ENJ from creator enjinCoin.transferFrom(msg.sender, this, totalCost); // Grant tokens to creator transferInternal(_customTokenId, this, msg.sender, _value); // Event Mint(_customTokenId, _value); } /** * @dev Delete a custom token type. There must be 0 in circulation and this must be run by the token creator. * @param _customTokenId The ID number of the Custom Token */ function deleteToken(uint256 _customTokenId) { checkTokenCreator(_customTokenId); // A Custom Token may only be deleted if its total supply is fully liquidated require(types[_customTokenId].balances[this] == types[_customTokenId].totalSupply); delete types[_customTokenId]; Delete(_customTokenId, msg.sender); } /** * @dev Delete a custom token type. There must be 0 in circulation and this must be run by the token creator. * @param _customTokenId The ID number of the Custom Token * @param _name Human name of the item, ex. Sword of Satoshi * @param _icon URL to the 500x500px icon representing the item * @param _customData Optional data string to store custom game attributes in an item */ function updateParams(uint256 _customTokenId, string _name, string _icon, string _customData) { checkTokenCreator(_customTokenId); types[_customTokenId].name = _name; types[_customTokenId].icon = _icon; types[_customTokenId].data = _customData; Update(_customTokenId, _name, _icon, _customData); } /** * @dev Get the name of a Custom Token * @param _customTokenId The ID number of the Custom Token */ function getParams(uint256 _customTokenId) constant returns (address creator, uint256 totalSupply, uint256 exchangeRate, uint8 decimals, string name, string icon, string data) { creator = types[_customTokenId].creator; totalSupply = types[_customTokenId].totalSupply; exchangeRate = types[_customTokenId].exchangeRate; decimals = types[_customTokenId].decimals; name = types[_customTokenId].name; icon = types[_customTokenId].icon; data = types[_customTokenId ].data; } /** * @dev Allows the current token creator to transfer control of the custom token to a new creator. * @param _customTokenId The ID number of the Custom Token * @param _creator The address to transfer ownership to. */ function assign(uint256 _customTokenId, address _creator) { checkTokenCreator(_customTokenId); if (_creator != address(0)) { types[_customTokenId].creator = _creator; } Assign(_customTokenId, msg.sender, _creator); } /** * @dev Events */ event Create(uint256 indexed _customTokenId, address indexed _creator); event Liquidate(uint256 indexed _customTokenId, address indexed _owner, uint256 _value); event Mint(uint256 indexed _customTokenId, uint256 _value); event Delete(uint256 indexed _customTokenId, address indexed _creator); event Update(uint256 indexed _customTokenId, string _name, string _icon, string _customData); event Transfer(uint256 indexed _customTokenId, address indexed _from, address indexed _to, uint256 _value, bytes _data); event Assign(uint256 indexed _customTokenId, address indexed _from, address indexed _to); }
* @dev Liquidate a custom token into ENJ. The Mint contract gains ownership of the liquidated custom tokens until re-minting by the creator @param _customTokenId The ID number of the Custom Token @param _value How many tokens to liquidate/ todo: We may want another function signature that liquidates and transfers to a specific address instead of original sender
function liquidateToken(uint256 _customTokenId, uint256 _value) { require(types[_customTokenId].balances[msg.sender] >= _value); transferInternal(_customTokenId, msg.sender, this, _value); Liquidate(_customTokenId, msg.sender, _value); }
15,824,848
[ 1, 48, 18988, 350, 340, 279, 1679, 1147, 1368, 6693, 46, 18, 1021, 490, 474, 6835, 314, 4167, 23178, 434, 326, 4501, 26595, 690, 1679, 2430, 3180, 283, 17, 81, 474, 310, 635, 326, 11784, 225, 389, 3662, 1345, 548, 1021, 1599, 1300, 434, 326, 6082, 3155, 225, 389, 1132, 9017, 4906, 2430, 358, 4501, 26595, 340, 19, 10621, 30, 1660, 2026, 2545, 4042, 445, 3372, 716, 4501, 26595, 815, 471, 29375, 358, 279, 2923, 1758, 3560, 434, 2282, 5793, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4501, 26595, 340, 1345, 12, 11890, 5034, 389, 3662, 1345, 548, 16, 2254, 5034, 389, 1132, 13, 288, 203, 3639, 2583, 12, 2352, 63, 67, 3662, 1345, 548, 8009, 70, 26488, 63, 3576, 18, 15330, 65, 1545, 389, 1132, 1769, 203, 203, 3639, 7412, 3061, 24899, 3662, 1345, 548, 16, 1234, 18, 15330, 16, 333, 16, 389, 1132, 1769, 203, 3639, 511, 18988, 350, 340, 24899, 3662, 1345, 548, 16, 1234, 18, 15330, 16, 389, 1132, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view 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); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * 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 Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @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. */ 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); _; } } /* * @title ENC ECO System, build in Heco Network * @dev A financial system built on smart contract technology. Open to all, transparent to all. * The worlds first decentralized, community support fund */ contract EncEcosystem is Ownable { IERC20 public invest1ccToken; IERC20 public investEncToken; using SafeMath for uint256; struct PlayerDeposit { uint256 id; uint256 amount; uint256 total_withdraw; uint256 time; uint256 period; uint256 month; uint256 expire; uint8 status; uint8 is_crowd; } struct Player { address referral; uint8 is_supernode; uint256 level_id; uint256 dividends; uint256 referral_bonus; uint256 match_bonus; uint256 supernode_bonus; uint256 total_invested; uint256 total_redeem; uint256 total_withdrawn; uint256 last_payout; PlayerDeposit[] deposits; address[] referrals; } struct PlayerTotal { uint256 total_match_invested; uint256 total_dividends; uint256 total_referral_bonus; uint256 total_match_bonus; uint256 total_supernode_bonus; uint256 total_period1_invested; uint256 total_period2_invested; uint256 total_period3_invested; uint256 total_period4_invested; uint256 total_period1_devidends; uint256 total_period2_devidends; uint256 total_period3_devidends; uint256 total_period4_devidends; } /* Deposit smart contract address */ address public invest_1cc_token_address = 0xFAd7161C74c809C213D88DAc021600D74F6c961c; uint256 public invest_1cc_token_decimal = 4; address public invest_enc_token_address = 0x73724d56fE952bf2eD130A6fb31C1f58dDEdac68; uint256 public invest_enc_token_decimal = 8; /* Platform bonus address */ address public platform_bonus_address = 0x6Fc447828B90d7D7f6C84d5fa688FF3E4ED3763C; /* Platform bonus rate percent(%) */ uint256 constant public platform_bonus_rate = 3; uint256 public total_investors; uint256 public total_invested; uint256 public total_withdrawn; uint256 public total_redeem; uint256 public total_dividends; uint256 public total_referral_bonus; uint256 public total_match_bonus; uint256 public total_supernode_bonus; uint256 public total_platform_bonus; /* Current joined supernode count */ uint256 public total_supernode_num; /* Total supernode join limit number */ uint256 constant public SUPERNODE_LIMIT_NUM = 100; uint256[] public supernode_period_ids = [1, 2, 3]; //period months uint256[] public supernode_period_amounts = [5000,6000,7000]; //period amount uint256[] public supernode_period_limits = [20, 30, 50]; //period limit //supernode total numer in which period uint256[] public total_supernode_num_periods = [0,0,0]; /* Super Node bonus rate */ uint256 constant public supernode_bonus_rate = 30; /* Referral bonuses data define*/ uint8[] public referral_bonuses = [6,4,2,1,1,1,1,1,1,1]; /* Invest period and profit parameter definition */ uint256 constant public invest_early_redeem_feerate = 15; //invest early redeem fee rate(%) uint256[] public invest_period_ids = [1, 2, 3, 4]; //period ids uint256[] public invest_period_months = [3, 6, 12, 24]; //period months uint256[] public invest_period_rates = [600, 700, 800, 900]; //Ten thousand of month' rate uint256[] public invest_period_totals = [0, 0, 0, 0]; //period total invested uint256[] public invest_period_devidends = [0, 0, 0, 0]; //period total devidends /* withdraw fee amount (0.8 1CC)) */ uint256 constant public withdraw_fee_amount = 8000; /* yield reduce project section config, item1: total yield, item2: reduce rate */ uint256[] public yield_reduce_section1 = [30000, 30]; uint256[] public yield_reduce_section2 = [60000, 30]; uint256[] public yield_reduce_section3 = [90000, 30]; uint256[] public yield_reduce_section4 = [290000, 30]; uint256[] public yield_reduce_section5 = [800000, 30]; /* Team level data definition */ uint256[] public team_level_ids = [1,2,3,4,5,6]; uint256[] public team_level_amounts = [1000,3000,5000,10000,20000,50000]; uint256[] public team_level_bonuses = [2,4,6,8,10,12]; /* Crowd period data definition */ uint256[] public crowd_period_ids = [1,2,3]; uint256[] public crowd_period_rates = [4,5,6]; uint256[] public crowd_period_limits = [50000,30000,20000]; /* Total (period) crowd number*/ uint256[] public total_crowd_num_periods = [0,0,0]; /* user invest min amount */ uint256 constant public INVEST_MIN_AMOUNT = 10000000; /* user invest max amount */ uint256 constant public INVEST_MAX_AMOUNT = 100000000000000; /* user crowd limit amount */ uint256 constant public SUPERNODE_LIMIT_AMOUNT = 5000; /* user crowd period(month) */ uint256 constant public crowd_period_month = 24; uint256 constant public crowd_period_start = 1634313600; /* Mapping data list define */ mapping(address => Player) public players; mapping(address => PlayerTotal) public playerTotals; mapping(uint256 => address) public addrmap; address[] public supernodes; event Deposit(address indexed addr, uint256 amount, uint256 month); event Withdraw(address indexed addr, uint256 amount); event Crowd(address indexed addr, uint256 period,uint256 amount); event SuperNode(address indexed addr, uint256 _period, uint256 amount); event DepositRedeem(uint256 invest_id); event ReferralPayout(address indexed addr, uint256 amount, uint8 level); event SetReferral(address indexed addr,address refferal); constructor() public { /* Create invest token instace */ invest1ccToken = IERC20(invest_1cc_token_address); investEncToken = IERC20(invest_enc_token_address); } /* Function to receive Ether. msg.data must be empty */ receive() external payable {} /* Fallback function is called when msg.data is not empty */ fallback() external payable {} function getBalance() public view returns (uint) { return address(this).balance; } /* * @dev user do set refferal action */ function setReferral(address _referral) payable external { Player storage player = players[msg.sender]; require(player.referral == address(0), "Referral has been set"); require(_referral != address(0), "Invalid Referral address"); Player storage ref_player = players[_referral]; require(ref_player.referral != address(0) || _referral == platform_bonus_address, "Referral address not activated yet"); _setReferral(msg.sender,_referral); emit SetReferral(msg.sender,_referral); } /* * @dev user do join shareholder action, to join SUPERNODE */ function superNode(address _referral, uint256 _period, uint256 _amount) payable external { Player storage player = players[msg.sender]; require(player.is_supernode == 0, "Already a supernode"); require(_period >= 1 && _period <= 3 , "Invalid Period Id"); if(_period > 1){ uint256 _lastPeriodLimit = supernode_period_limits[_period-2]; require(total_supernode_num_periods[_period-2] >= _lastPeriodLimit, "Current round not started yet "); } uint256 _periodAmount = supernode_period_amounts[_period-1]; require(_amount == _periodAmount, "Not match the current round limit"); //valid period remain uint256 _periodRemain = supernode_period_limits[_period-1] - total_supernode_num_periods[_period-1]; require(_periodRemain > 0, "Out of current period limit"); /* format token amount */ uint256 token_amount = _getTokenAmount(_amount,invest_1cc_token_decimal); /* Transfer user address token to contract address*/ require(invest1ccToken.transferFrom(msg.sender, address(this), token_amount), "transferFrom failed"); _setReferral(msg.sender, _referral); /* set the player of supernodes roles */ player.is_supernode = 1; total_supernode_num += 1; total_supernode_num_periods[_period-1] += 1; /* push user to shareholder list*/ supernodes.push(msg.sender); emit SuperNode(msg.sender, _period, _amount); } /* * @dev user do crowd action, to get enc */ function crowd(address _referral, uint256 _period, uint256 _amount) payable external { require(_period >= 1 && _period <= 3 , "Invalid Period Id"); if(_period > 1){ uint256 _lastPeriodLimit = crowd_period_limits[_period-2]; require(total_crowd_num_periods[_period-2] >= _lastPeriodLimit, "Current round not started yet "); } //valid period remain uint256 _periodRemain = crowd_period_limits[_period-1] - total_crowd_num_periods[_period-1]; require(_periodRemain > 0, "Out of current period limit"); uint256 _periodRate = crowd_period_rates[_period-1]; uint256 token_enc_amount = _getTokenAmount(_amount,invest_enc_token_decimal); uint256 token_1cc_amount = _getTokenAmount(_amount.mul(_periodRate),invest_1cc_token_decimal); /* Transfer user address token to contract address*/ require(invest1ccToken.transferFrom(msg.sender, address(this), token_1cc_amount), "transferFrom failed"); _setReferral(msg.sender, _referral); /* get the period total time (total secones) */ uint256 _period_ = 4; uint256 _month = crowd_period_month; uint256 period_time = _month.mul(30).mul(86400); //updater period total number total_crowd_num_periods[_period-1] += _amount; Player storage player = players[msg.sender]; /* update total investor count */ if(player.deposits.length == 0){ total_investors += 1; addrmap[total_investors] = msg.sender; } uint256 _id = player.deposits.length + 1; player.deposits.push(PlayerDeposit({ id: _id, amount: token_enc_amount, total_withdraw: 0, time: uint256(block.timestamp), period: _period_, month: _month, expire: uint256(block.timestamp).add(period_time), status: 0, is_crowd: 1 })); //update total invested player.total_invested += token_enc_amount; total_invested += token_enc_amount; invest_period_totals[_period_-1] += token_enc_amount; //update player period total invest data _updatePlayerPeriodTotalInvestedData(msg.sender, _period_, token_enc_amount, 1); /* update user referral and match invested amount*/ _updateReferralMatchInvestedAmount(msg.sender, token_enc_amount, 1); emit Crowd(msg.sender, _period, _amount); } /* * @dev user do deposit action,grant the referrs bonus,grant the shareholder bonus,grant the match bonus */ function deposit(address _referral, uint256 _amount, uint256 _period) external payable { require(_period >= 1 && _period <= 4 , "Invalid Period Id"); uint256 _month = invest_period_months[_period-1]; /* format token amount */ uint256 _decimal = invest_enc_token_decimal - invest_1cc_token_decimal; uint256 token_enc_amount = _amount; uint256 token_1cc_amount = _amount.div(10**_decimal); require(token_enc_amount >= INVEST_MIN_AMOUNT, "Minimal deposit: 0.1 enc"); require(token_enc_amount <= INVEST_MAX_AMOUNT, "Maxinum deposit: 1000000 enc"); Player storage player = players[msg.sender]; require(player.deposits.length < 2000, "Max 2000 deposits per address"); /* Transfer user address token to contract address*/ require(investEncToken.transferFrom(msg.sender, address(this), token_enc_amount), "transferFrom failed"); require(invest1ccToken.transferFrom(msg.sender, address(this), token_1cc_amount), "transferFrom failed"); _setReferral(msg.sender, _referral); /* update total investor count */ if(player.deposits.length == 0){ total_investors += 1; addrmap[total_investors] = msg.sender; } /* get the period total time (total secones) */ uint256 period_time = _month.mul(30).mul(86400); uint256 _id = player.deposits.length + 1; player.deposits.push(PlayerDeposit({ id: _id, amount: token_enc_amount, total_withdraw: 0, time: uint256(block.timestamp), period: _period, month: _month, expire:uint256(block.timestamp).add(period_time), status: 0, is_crowd: 0 })); player.total_invested += token_enc_amount; total_invested += token_enc_amount; invest_period_totals[_period-1] += token_enc_amount; //update player period total invest data _updatePlayerPeriodTotalInvestedData(msg.sender, _period, token_enc_amount, 1); /* update user referral and match invested amount*/ _updateReferralMatchInvestedAmount(msg.sender, token_enc_amount, 1); emit Deposit(msg.sender, _amount, _month); } /* * @dev user do withdraw action, tranfer the total profit to user account, grant rereferral bonus, grant match bonus, grant shareholder bonus */ function withdraw() payable external { /* update user dividend data */ _payout(msg.sender); Player storage player = players[msg.sender]; uint256 _amount = player.dividends + player.referral_bonus + player.match_bonus + player.supernode_bonus; require(_amount >= 10000000, "Minimal payout: 0.1 ENC"); /* format deposit token amount */ uint256 token_enc_amount = _amount; /* process token transfer action */ require(investEncToken.approve(address(this), token_enc_amount), "approve failed"); require(investEncToken.transferFrom(address(this), msg.sender, token_enc_amount), "transferFrom failed"); /*transfer service fee to contract*/ uint256 token_1cc_fee_amount = withdraw_fee_amount; require(invest1ccToken.transferFrom(msg.sender, address(this), token_1cc_fee_amount), "transferFrom failed"); uint256 _dividends = player.dividends; /* Update user total payout data */ _updatePlayerTotalPayout(msg.sender, token_enc_amount); /* Grant referral bonus */ _referralPayout(msg.sender, _dividends); /* Grant super node bonus */ _superNodesPayout(_dividends); /* Grant team match bonus*/ _matchPayout(msg.sender, _dividends); emit Withdraw(msg.sender, token_enc_amount); } /* * @dev user do deposit redeem action,transfer the expire deposit's amount to user account */ function depositRedeem(uint256 _invest_id) payable external { Player storage player = players[msg.sender]; require(player.deposits.length >= _invest_id && _invest_id > 0, "Valid deposit id"); uint256 _index = _invest_id - 1; require(player.deposits[_index].status == 0, "Invest is redeemed"); //crowded deposit can't do early redeem action //if(player.deposits[_index].is_crowd == 1) { require(player.deposits[_index].expire < block.timestamp, "Invest not expired"); //} /* formt deposit token amount */ uint256 token_enc_amount = player.deposits[_index].amount; //deposit is not expired, deduct the fee (10%) if(player.deposits[_index].expire > block.timestamp){ //token_enc_amount = token_enc_amount * (100 - invest_early_redeem_feerate) / 100; } /* process token transfer action*/ require(investEncToken.approve(address(this), token_enc_amount), "approve failed"); require(investEncToken.transferFrom(address(this), msg.sender, token_enc_amount), "transferFrom failed"); /* update deposit status in redeem */ player.deposits[_index].status = 1; uint256 _amount = player.deposits[_index].amount; /* update user token balance*/ player.total_invested -= _amount; /* update total invested/redeem amount */ total_invested -= _amount; total_redeem += _amount; /* update invest period total invested amount*/ uint256 _period = player.deposits[_index].period; invest_period_totals[_period-1] -= _amount; //update player period total invest data _updatePlayerPeriodTotalInvestedData(msg.sender, _period, _amount, -1); /* update user referral and match invested amount*/ _updateReferralMatchInvestedAmount(msg.sender, _amount, -1); emit DepositRedeem(_invest_id); } /* * @dev Update Referral Match invest amount, total investor number, map investor address index */ function _updateReferralMatchInvestedAmount(address _addr,uint256 _amount,int8 _opType) private { if(_opType > 0) { playerTotals[_addr].total_match_invested += _amount; address ref = players[_addr].referral; while(true){ if(ref == address(0)) break; playerTotals[ref].total_match_invested += _amount; ref = players[ref].referral; } }else{ playerTotals[_addr].total_match_invested -= _amount; address ref = players[_addr].referral; while(true){ if(ref == address(0)) break; playerTotals[ref].total_match_invested -= _amount; ref = players[ref].referral; } } } /* * @dev Update user total payout data */ function _updatePlayerTotalPayout(address _addr,uint256 token_amount) private { Player storage player = players[_addr]; PlayerTotal storage playerTotal = playerTotals[_addr]; /* update user Withdraw total amount*/ player.total_withdrawn += token_amount; playerTotal.total_dividends += player.dividends; playerTotal.total_referral_bonus += player.referral_bonus; playerTotal.total_match_bonus += player.match_bonus; playerTotal.total_supernode_bonus += player.supernode_bonus; /* update platform total data*/ total_withdrawn += token_amount; total_dividends += player.dividends; total_referral_bonus += player.referral_bonus; total_match_bonus += player.match_bonus; total_supernode_bonus += player.supernode_bonus; uint256 _platform_bonus = (token_amount * platform_bonus_rate / 100); total_platform_bonus += _platform_bonus; /* update platform address bonus*/ players[platform_bonus_address].match_bonus += _platform_bonus; /* reset user bonus data */ player.dividends = 0; player.referral_bonus = 0; player.match_bonus = 0; player.supernode_bonus = 0; } /* * @dev get user deposit expire status */ function _getExpireStatus(address _addr) view private returns(uint256 value) { Player storage player = players[_addr]; uint256 _status = 1; for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(from < to && dep.status == 0) { _status = 0; break; } } return _status; } /* * @dev update user referral data */ function _setReferral(address _addr, address _referral) private { /* if user referral is not set */ if(players[_addr].referral == address(0) && _referral != _addr && _referral != address(0)) { Player storage ref_player = players[_referral]; if(ref_player.referral != address(0) || _referral == platform_bonus_address){ players[_addr].referral = _referral; /* update user referral address list*/ players[_referral].referrals.push(_addr); } } } /* * @dev Grant user referral bonus in user withdraw */ function _referralPayout(address _addr, uint256 _amount) private { address ref = players[_addr].referral; uint256 _day_payout = _payoutOfDay(_addr); if(_day_payout == 0) return; for(uint8 i = 0; i < referral_bonuses.length; i++) { if(ref == address(0)) break; uint256 _ref_day_payout = _payoutOfDay(ref); uint256 _token_amount = _amount; /* user bonus double burn */ if(_ref_day_payout * 2 < _day_payout){ _token_amount = _token_amount * (_ref_day_payout * 2) / _day_payout; } //validate account deposit is all expired or not uint256 _is_expire = _getExpireStatus(ref); if(_is_expire == 0) { uint256 bonus = _token_amount * referral_bonuses[i] / 100; players[ref].referral_bonus += bonus; } ref = players[ref].referral; } } /* * @dev Grant shareholder full node bonus in user withdraw */ function _superNodesPayout(uint256 _amount) private { uint256 _supernode_num = supernodes.length; if(_supernode_num == 0) return; uint256 bonus = _amount * supernode_bonus_rate / 100 / _supernode_num; for(uint256 i = 0; i < _supernode_num; i++) { address _addr = supernodes[i]; players[_addr].supernode_bonus += bonus; } } /* * @dev Grant Match bonus in user withdraw */ function _matchPayout(address _addr,uint256 _amount) private { /* update player team level */ _upgradePlayerTeamLevel(_addr); uint256 last_level_id = players[_addr].level_id; /* player is max team level, quit */ if(last_level_id == team_level_ids[team_level_ids.length-1]) return; address ref = players[_addr].referral; while(true){ if(ref == address(0)) break; //validate account deposit is all expired or not uint256 _is_expire = _getExpireStatus(ref); /* upgrade player team level id*/ _upgradePlayerTeamLevel(ref); if(players[ref].level_id > last_level_id){ uint256 last_level_bonus = 0; if(last_level_id > 0){ last_level_bonus = team_level_bonuses[last_level_id-1]; } uint256 cur_level_bonus = team_level_bonuses[players[ref].level_id-1]; uint256 bonus_amount = _amount * (cur_level_bonus - last_level_bonus) / 100; if(_is_expire==0){ players[ref].match_bonus += bonus_amount; } last_level_id = players[ref].level_id; /* referral is max team level, quit */ if(last_level_id == team_level_ids[team_level_ids.length-1]) break; } ref = players[ref].referral; } } /* * @dev upgrade player team level id */ function _upgradePlayerTeamLevel(address _addr) private { /* get community total invested*/ uint256 community_total_invested = _getCommunityTotalInvested(_addr); uint256 level_id = 0; for(uint8 i=0; i < team_level_ids.length; i++){ uint256 _team_level_amount = _getTokenAmount(team_level_amounts[i], invest_enc_token_decimal); if(community_total_invested >= _team_level_amount){ level_id = team_level_ids[i]; } } players[_addr].level_id = level_id; } /* * @dev Get community total invested */ function _getCommunityTotalInvested(address _addr) view private returns(uint256 value) { address[] memory referrals = players[_addr].referrals; uint256 nodes_max_invested = 0; uint256 nodes_total_invested = 0; for(uint256 i=0;i<referrals.length;i++){ address ref = referrals[i]; nodes_total_invested += playerTotals[ref].total_match_invested; if(playerTotals[ref].total_match_invested > nodes_max_invested){ nodes_max_invested = playerTotals[ref].total_match_invested; } } return (nodes_total_invested - nodes_max_invested); } /* * @dev user withdraw, user devidends data update */ function _payout(address _addr) private { uint256 payout = this.payoutOf(_addr); if(payout > 0) { _updateTotalPayout(_addr); players[_addr].last_payout = uint256(block.timestamp); players[_addr].dividends += payout; } } /* * @dev format token amount with token decimal */ function _getTokenAmount(uint256 _amount,uint256 _token_decimal) pure private returns(uint256 token_amount) { uint256 token_decimals = 10 ** _token_decimal; token_amount = _amount * token_decimals; return token_amount; } /* * @dev update user total withdraw data */ function _updateTotalPayout(address _addr) private { Player storage player = players[_addr]; for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(from < to && dep.status == 0) { uint256 _day_payout = _getInvestDayPayoutOf(dep.amount,dep.period); uint256 _dep_payout = _day_payout * (to - from) / 86400; uint256 _period = player.deposits[i].period; player.deposits[i].total_withdraw += _dep_payout; invest_period_devidends[_period-1]+= _dep_payout; //update player period total devidend data _updatePlayerPeriodTotalDevidendsData(msg.sender,_period,_dep_payout); } } } /* * @dev update player period total invest data */ function _updatePlayerPeriodTotalInvestedData(address _addr,uint256 _period,uint256 _token_amount,int8 _opType) private { if(_opType==-1){ if(_period==1){ playerTotals[_addr].total_period1_invested -= _token_amount; return; } if(_period==2){ playerTotals[_addr].total_period2_invested -= _token_amount; return; } if(_period==3){ playerTotals[_addr].total_period3_invested -= _token_amount; return; } if(_period==4){ playerTotals[_addr].total_period4_invested -= _token_amount; return; } }else{ if(_period==1){ playerTotals[_addr].total_period1_invested += _token_amount; return; } if(_period==2){ playerTotals[_addr].total_period2_invested += _token_amount; return; } if(_period==3){ playerTotals[_addr].total_period3_invested += _token_amount; return; } if(_period==4){ playerTotals[_addr].total_period4_invested += _token_amount; return; } } } /* * @dev update player period total devidend data */ function _updatePlayerPeriodTotalDevidendsData(address _addr,uint256 _period,uint256 _dep_payout) private { if(_period==1){ playerTotals[_addr].total_period1_devidends += _dep_payout; return; } if(_period==2){ playerTotals[_addr].total_period2_devidends += _dep_payout; return; } if(_period==3){ playerTotals[_addr].total_period3_devidends += _dep_payout; return; } if(_period==4){ playerTotals[_addr].total_period4_devidends += _dep_payout; return; } } /* * @dev get the invest period rate, if total yield reached reduce limit, invest day rate will be reduce */ function _getInvestDayPayoutOf(uint256 _amount, uint256 _period) view private returns(uint256 value) { /* get invest period base rate*/ uint256 period_month_rate = invest_period_rates[_period-1]; /* format amount with token decimal */ uint256 token_amount = _amount; value = token_amount * period_month_rate / 30 / 10000; if(value > 0){ /* total yield reached 30,000,start first reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section1[0], invest_enc_token_decimal)){ value = value * (100 - yield_reduce_section1[1]) / 100; } /* total yield reached 60,000,start second reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section2[0], invest_enc_token_decimal)){ value = value * (100 - yield_reduce_section2[1]) / 100; } /* total yield reached 90,000,start third reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section3[0], invest_enc_token_decimal)){ value = value * (100 - yield_reduce_section3[1]) / 100; } /* total yield reached 290,000,start fourth reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section4[0], invest_enc_token_decimal)){ value = value * (100 - yield_reduce_section4[1]) / 100; } /* total yield reached 890,000,start fifth reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section5[0], invest_enc_token_decimal)){ value = value * (100 - yield_reduce_section5[1]) / 100; } } return value; } /* * @dev get user deposit day total pending profit * @return user pending payout amount */ function payoutOf(address _addr) view external returns(uint256 value) { Player storage player = players[_addr]; for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(from < to && dep.status == 0) { uint256 _day_payout = _getInvestDayPayoutOf(dep.amount,dep.period); value += _day_payout * (to - from) / 86400; } } return value; } /* * @dev get user deposit day total pending profit * @return user pending payout amount */ function _payoutOfDay(address _addr) view private returns(uint256 value) { Player storage player = players[_addr]; for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; //uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; //uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(dep.status == 0) { uint256 _day_payout = _getInvestDayPayoutOf(dep.amount, dep.period); value += _day_payout; } } return value; } /* * @dev Remove supernodes of the special address */ function _removeSuperNodes(address _addr) private { for (uint index = 0; index < supernodes.length; index++) { if(supernodes[index] == _addr){ for (uint i = index; i < supernodes.length-1; i++) { supernodes[i] = supernodes[i+1]; } delete supernodes[supernodes.length-1]; break; } } } /* * @dev get contract data info * @return total invested,total investor number,total withdraw,total referral bonus */ function contractInfo() view external returns( uint256 _total_invested, uint256 _total_investors, uint256 _total_withdrawn, uint256 _total_dividends, uint256 _total_referral_bonus, uint256 _total_platform_bonus, uint256 _total_supernode_num, uint256 _crowd_period_month, uint256 _crowd_period_start, uint256 _total_holder_bonus, uint256 _total_match_bonus) { return ( total_invested, total_investors, total_withdrawn, total_dividends, total_referral_bonus, total_platform_bonus, total_supernode_num, crowd_period_month, crowd_period_start, total_supernode_bonus, total_match_bonus ); } /* * @dev get user info * @return pending withdraw amount,referral,rreferral num etc. */ function userInfo(address _addr) view external returns ( address _referral, uint256 _referral_num, uint256 _is_supernode, uint256 _dividends, uint256 _referral_bonus, uint256 _match_bonus, uint256 _supernode_bonus,uint256 _last_payout ) { Player storage player = players[_addr]; return ( player.referral, player.referrals.length, player.is_supernode, player.dividends, player.referral_bonus, player.match_bonus, player.supernode_bonus, player.last_payout ); } /* * @dev get user info * @return pending withdraw amount,referral bonus, total deposited, total withdrawn etc. */ function userInfoTotals(address _addr) view external returns( uint256 _total_invested, uint256 _total_withdrawn, uint256 _total_community_invested, uint256 _total_match_invested, uint256 _total_dividends, uint256 _total_referral_bonus, uint256 _total_match_bonus, uint256 _total_supernode_bonus ) { Player storage player = players[_addr]; PlayerTotal storage playerTotal = playerTotals[_addr]; /* get community total invested*/ uint256 total_community_invested = _getCommunityTotalInvested(_addr); return ( player.total_invested, player.total_withdrawn, total_community_invested, playerTotal.total_match_invested, playerTotal.total_dividends, playerTotal.total_referral_bonus, playerTotal.total_match_bonus, playerTotal.total_supernode_bonus ); } /* * @dev get user investment list */ function getInvestList(address _addr) view external returns( uint256[] memory ids,uint256[] memory times, uint256[] memory months, uint256[] memory amounts,uint256[] memory withdraws, uint256[] memory statuses,uint256[] memory payouts) { Player storage player = players[_addr]; PlayerDeposit[] memory deposits = _getValidInvestList(_addr); uint256[] memory _ids = new uint256[](deposits.length); uint256[] memory _times = new uint256[](deposits.length); uint256[] memory _months = new uint256[](deposits.length); uint256[] memory _amounts = new uint256[](deposits.length); uint256[] memory _withdraws = new uint256[](deposits.length); uint256[] memory _statuses = new uint256[](deposits.length); uint256[] memory _payouts = new uint256[](deposits.length); for(uint256 i = 0; i < deposits.length; i++) { PlayerDeposit memory dep = deposits[i]; _ids[i] = dep.id; _amounts[i] = dep.amount; _withdraws[i] = dep.total_withdraw; _times[i] = dep.time; _months[i] = dep.month; _statuses[i] = dep.is_crowd; _months[i] = dep.month; //get deposit current payout uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(from < to && dep.status == 0) { uint256 _day_payout = _getInvestDayPayoutOf(dep.amount,dep.period); uint256 _value = _day_payout * (to - from) / 86400; _payouts[i] = _value; } } return ( _ids, _times, _months, _amounts, _withdraws, _statuses, _payouts ); } /* * @dev get deposit valid count */ function _getValidInvestList(address _addr) view private returns(PlayerDeposit[] memory) { Player storage player = players[_addr]; uint256 resultCount; for (uint i = 0; i < player.deposits.length; i++) { if ( player.deposits[i].status == 0) { resultCount++; } } PlayerDeposit[] memory deposits = new PlayerDeposit[](resultCount); uint256 j; for(uint256 i = 0; i < player.deposits.length; i++){ if(player.deposits[i].status==0){ deposits[j] = player.deposits[i]; j++; } } return deposits; } /* * @dev get crowd period list */ function getCrowdPeriodList() view external returns(uint256[] memory ids,uint256[] memory rates, uint256[] memory limits, uint256[] memory totals) { return ( crowd_period_ids, crowd_period_rates, crowd_period_limits, total_crowd_num_periods ); } /* * @dev get invest period list */ function getInvestPeriodList(address _addr) view external returns( uint256[] memory ids,uint256[] memory months, uint256[] memory rates,uint256[] memory totals, uint256[] memory devidends,uint256[] memory user_investeds, uint256[] memory user_devidends) { PlayerTotal storage playerTotal = playerTotals[_addr]; uint256[] memory _user_period_investeds = new uint256[](4); uint256[] memory _user_period_devidends = new uint256[](4); _user_period_investeds[0] = playerTotal.total_period1_invested; _user_period_investeds[1] = playerTotal.total_period2_invested; _user_period_investeds[2] = playerTotal.total_period3_invested; _user_period_investeds[3] = playerTotal.total_period4_invested; _user_period_devidends[0] = playerTotal.total_period1_devidends; _user_period_devidends[1] = playerTotal.total_period2_devidends; _user_period_devidends[2] = playerTotal.total_period3_devidends; _user_period_devidends[3] = playerTotal.total_period4_devidends; return ( invest_period_ids, invest_period_months, invest_period_rates, invest_period_totals, invest_period_devidends, _user_period_investeds, _user_period_devidends ); } /* * @dev get supernode period list */ function getSuperNodePeriodList() view external returns(uint256[] memory ids,uint256[] memory amounts, uint256[] memory limits,uint256[] memory totals) { return ( supernode_period_ids, supernode_period_amounts, supernode_period_limits, total_supernode_num_periods ); } }
* @dev Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view 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); pragma solidity ^0.6.12; }
12,749,264
[ 1, 1358, 434, 326, 4232, 39, 3462, 4529, 487, 2553, 316, 326, 512, 2579, 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, 5831, 467, 654, 39, 3462, 288, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 460, 1769, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 460, 1769, 203, 203, 565, 445, 508, 1435, 3903, 1476, 1135, 261, 1080, 3778, 1769, 203, 565, 445, 3273, 1435, 3903, 1476, 1135, 261, 1080, 3778, 1769, 203, 565, 445, 15105, 1435, 3903, 1476, 1135, 261, 11890, 28, 1769, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 1769, 203, 565, 445, 11013, 951, 12, 2867, 3410, 13, 3903, 1476, 1135, 261, 11890, 1769, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 1769, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 460, 13, 3903, 1135, 261, 6430, 1769, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 460, 13, 3903, 1135, 261, 6430, 1769, 203, 565, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 460, 13, 3903, 1135, 261, 6430, 1769, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 2138, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-03-11 */ // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint a, uint b) internal pure returns (bool, uint) { uint 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(uint a, uint b) internal pure returns (bool, uint) { 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(uint a, uint b) internal pure returns (bool, uint) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint 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(uint a, uint b) internal pure returns (bool, uint) { 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(uint a, uint b) internal pure returns (bool, uint) { 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(uint a, uint b) internal pure returns (uint) { uint 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(uint a, uint b) internal pure returns (uint) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) return 0; uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint a, uint b) internal pure returns (uint) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint a, uint b) internal pure returns (uint) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { 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( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint private constant _NOT_ENTERED = 1; uint private constant _ENTERED = 2; uint private _status; constructor() internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @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 (uint); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint); /** * @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, uint 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 (uint); /** * @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, uint 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, uint 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, uint 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, uint value); } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint 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, uint 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, uint 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, uint value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer( IERC20 token, address to, uint value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint 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, uint 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, uint value ) internal { uint newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint value ) internal { uint newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File: @openzeppelin/contracts/utils/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint) { 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, uint 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 (uint) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint 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, uint 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, uint 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, uint 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, uint 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, uint 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, uint 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, uint amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint amount ) internal virtual {} } // File: contracts/protocol/IStrategy.sol /* version 1.2.0 Changes Changes listed here do not affect interaction with other contracts (Vault and Controller) - removed function assets(address _token) external view returns (bool); - remove function deposit(uint), declared in IStrategyERC20 - add function setSlippage(uint _slippage); - add function setDelta(uint _delta); */ interface IStrategy { function admin() external view returns (address); function controller() external view returns (address); function vault() external view returns (address); /* @notice Returns address of underlying asset (ETH or ERC20) @dev Must return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for ETH strategy */ function underlying() external view returns (address); /* @notice Returns total amount of underlying transferred from vault */ function totalDebt() external view returns (uint); function performanceFee() external view returns (uint); function slippage() external view returns (uint); /* @notice Multiplier used to check total underlying <= total debt * delta / DELTA_MIN */ function delta() external view returns (uint); /* @dev Flag to force exit in case normal exit fails */ function forceExit() external view returns (bool); function setAdmin(address _admin) external; function setController(address _controller) external; function setPerformanceFee(uint _fee) external; function setSlippage(uint _slippage) external; function setDelta(uint _delta) external; function setForceExit(bool _forceExit) external; /* @notice Returns amount of underlying asset locked in this contract @dev Output may vary depending on price of liquidity provider token where the underlying asset is invested */ function totalAssets() external view returns (uint); /* @notice Withdraw `_amount` underlying asset @param amount Amount of underlying asset to withdraw */ function withdraw(uint _amount) external; /* @notice Withdraw all underlying asset from strategy */ function withdrawAll() external; /* @notice Sell any staking rewards for underlying and then deposit undelying */ function harvest() external; /* @notice Increase total debt if profit > 0 and total assets <= max, otherwise transfers profit to vault. @dev Guard against manipulation of external price feed by checking that total assets is below factor of total debt */ function skim() external; /* @notice Exit from strategy @dev Must transfer all underlying tokens back to vault */ function exit() external; /* @notice Transfer token accidentally sent here to admin @param _token Address of token to transfer @dev _token must not be equal to underlying token */ function sweep(address _token) external; } // File: contracts/protocol/IStrategyETH.sol interface IStrategyETH is IStrategy { /* @notice Deposit ETH */ function deposit() external payable; } // File: contracts/protocol/IVault.sol /* version 1.2.0 Changes - function deposit(uint) declared in IERC20Vault */ interface IVault { function admin() external view returns (address); function controller() external view returns (address); function timeLock() external view returns (address); /* @notice For EthVault, must return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE */ function token() external view returns (address); function strategy() external view returns (address); function strategies(address _strategy) external view returns (bool); function reserveMin() external view returns (uint); function withdrawFee() external view returns (uint); function paused() external view returns (bool); function whitelist(address _addr) external view returns (bool); function setWhitelist(address _addr, bool _approve) external; function setAdmin(address _admin) external; function setController(address _controller) external; function setTimeLock(address _timeLock) external; function setPause(bool _paused) external; function setReserveMin(uint _reserveMin) external; function setWithdrawFee(uint _fee) external; /* @notice Returns the amount of asset (ETH or ERC20) in the vault */ function balanceInVault() external view returns (uint); /* @notice Returns the estimate amount of asset in strategy @dev Output may vary depending on price of liquidity provider token where the underlying asset is invested */ function balanceInStrategy() external view returns (uint); /* @notice Returns amount of tokens invested strategy */ function totalDebtInStrategy() external view returns (uint); /* @notice Returns the total amount of asset in vault + total debt */ function totalAssets() external view returns (uint); /* @notice Returns minimum amount of tokens that should be kept in vault for cheap withdraw @return Reserve amount */ function minReserve() external view returns (uint); /* @notice Returns the amount of tokens available to be invested */ function availableToInvest() external view returns (uint); /* @notice Approve strategy @param _strategy Address of strategy */ function approveStrategy(address _strategy) external; /* @notice Revoke strategy @param _strategy Address of strategy */ function revokeStrategy(address _strategy) external; /* @notice Set strategy @param _min Minimum undelying asset current strategy must return. Prevents slippage */ function setStrategy(address _strategy, uint _min) external; /* @notice Transfers asset in vault to strategy */ function invest() external; /* @notice Calculate amount of asset that can be withdrawn @param _shares Amount of shares @return Amount of asset that can be withdrawn */ function getExpectedReturn(uint _shares) external view returns (uint); /* @notice Withdraw asset @param _shares Amount of shares to burn @param _min Minimum amount of asset expected to return */ function withdraw(uint _shares, uint _min) external; /* @notice Transfer asset in vault to admin @param _token Address of asset to transfer @dev _token must not be equal to vault asset */ function sweep(address _token) external; } // File: contracts/protocol/IETHVault.sol interface IETHVault is IVault { /* @notice Deposit ETH into this vault */ function deposit() external payable; } // File: contracts/protocol/IController.sol interface IController { function ADMIN_ROLE() external view returns (bytes32); function HARVESTER_ROLE() external view returns (bytes32); function admin() external view returns (address); function treasury() external view returns (address); function setAdmin(address _admin) external; function setTreasury(address _treasury) external; function grantRole(bytes32 _role, address _addr) external; function revokeRole(bytes32 _role, address _addr) external; /* @notice Set strategy for vault @param _vault Address of vault @param _strategy Address of strategy @param _min Minimum undelying token current strategy must return. Prevents slippage */ function setStrategy( address _vault, address _strategy, uint _min ) external; // calls to strategy /* @notice Invest token in vault into strategy @param _vault Address of vault */ function invest(address _vault) external; function harvest(address _strategy) external; function skim(address _strategy) external; /* @notice Withdraw from strategy to vault @param _strategy Address of strategy @param _amount Amount of underlying token to withdraw @param _min Minimum amount of underlying token to withdraw */ function withdraw( address _strategy, uint _amount, uint _min ) external; /* @notice Withdraw all from strategy to vault @param _strategy Address of strategy @param _min Minimum amount of underlying token to withdraw */ function withdrawAll(address _strategy, uint _min) external; /* @notice Exit from strategy @param _strategy Address of strategy @param _min Minimum amount of underlying token to withdraw */ function exit(address _strategy, uint _min) external; } // File: contracts/ETHVault.sol /* version 1.2.0 */ contract ETHVault is IETHVault, ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint; event SetStrategy(address strategy); event ApproveStrategy(address strategy); event RevokeStrategy(address strategy); event SetWhitelist(address addr, bool approved); // WARNING: not address of ETH, used as placeholder address private constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public override admin; address public override controller; address public override timeLock; address public constant override token = ETH; address public override strategy; // mapping of approved strategies mapping(address => bool) public override strategies; // percentange of ETH reserved in vault for cheap withdraw uint public override reserveMin = 500; uint private constant RESERVE_MAX = 10000; // Denominator used to calculate fees uint private constant FEE_MAX = 10000; uint public override withdrawFee; uint private constant WITHDRAW_FEE_CAP = 500; // upper limit to withdrawFee bool public override paused; // whitelisted addresses // used to prevent flash loah attacks mapping(address => bool) public override whitelist; constructor(address _controller, address _timeLock) public ERC20("unagii_ETH", "uETH") { require(_controller != address(0), "controller = zero address"); require(_timeLock != address(0), "time lock = zero address"); // ETH decimals = 18 and ERC20 defaults to 18 decimals admin = msg.sender; controller = _controller; timeLock = _timeLock; } /* @dev Only allow ETH from current strategy @dev EOA cannot accidentally send ETH into this vault */ receive() external payable { require(msg.sender == strategy, "msg.sender != strategy"); } modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } modifier onlyTimeLock() { require(msg.sender == timeLock, "!time lock"); _; } modifier onlyAdminOrController() { require(msg.sender == admin || msg.sender == controller, "!authorized"); _; } modifier whenStrategyDefined() { require(strategy != address(0), "strategy = zero address"); _; } modifier whenNotPaused() { require(!paused, "paused"); _; } /* @dev modifier to prevent flash loan @dev caller is restricted to EOA or whitelisted contract @dev Warning: Users can have their funds stuck if shares is transferred to a contract */ modifier guard() { require((msg.sender == tx.origin) || whitelist[msg.sender], "!whitelist"); _; } function setAdmin(address _admin) external override onlyAdmin { require(_admin != address(0), "admin = zero address"); admin = _admin; } function setController(address _controller) external override onlyAdmin { require(_controller != address(0), "controller = zero address"); controller = _controller; } function setTimeLock(address _timeLock) external override onlyTimeLock { require(_timeLock != address(0), "time lock = zero address"); timeLock = _timeLock; } function setPause(bool _paused) external override onlyAdmin { paused = _paused; } function setWhitelist(address _addr, bool _approve) external override onlyAdmin { whitelist[_addr] = _approve; emit SetWhitelist(_addr, _approve); } function setReserveMin(uint _reserveMin) external override onlyAdmin { require(_reserveMin <= RESERVE_MAX, "reserve min > max"); reserveMin = _reserveMin; } function setWithdrawFee(uint _fee) external override onlyAdmin { require(_fee <= WITHDRAW_FEE_CAP, "withdraw fee > cap"); withdrawFee = _fee; } function _balanceInVault() private view returns (uint) { return address(this).balance; } /* @notice Returns balance of ETH in vault @return Amount of ETH in vault */ function balanceInVault() external view override returns (uint) { return _balanceInVault(); } function _balanceInStrategy() private view returns (uint) { if (strategy == address(0)) { return 0; } return IStrategyETH(strategy).totalAssets(); } /* @notice Returns the estimate amount of ETH in strategy @dev Output may vary depending on price of liquidity provider token where ETH is invested */ function balanceInStrategy() external view override returns (uint) { return _balanceInStrategy(); } function _totalDebtInStrategy() private view returns (uint) { if (strategy == address(0)) { return 0; } return IStrategyETH(strategy).totalDebt(); } /* @notice Returns amount of ETH invested strategy */ function totalDebtInStrategy() external view override returns (uint) { return _totalDebtInStrategy(); } function _totalAssets() private view returns (uint) { return _balanceInVault().add(_totalDebtInStrategy()); } /* @notice Returns the total amount of ETH in vault + total debt @return Total amount of ETH in vault + total debt */ function totalAssets() external view override returns (uint) { return _totalAssets(); } function _minReserve() private view returns (uint) { return _totalAssets().mul(reserveMin) / RESERVE_MAX; } /* @notice Returns minimum amount of ETH that should be kept in vault for cheap withdraw @return Reserve amount */ function minReserve() external view override returns (uint) { return _minReserve(); } function _availableToInvest() private view returns (uint) { if (strategy == address(0)) { return 0; } uint balInVault = _balanceInVault(); uint reserve = _minReserve(); if (balInVault <= reserve) { return 0; } return balInVault - reserve; } /* @notice Returns amount of ETH available to be invested into strategy @return Amount of ETH available to be invested into strategy */ function availableToInvest() external view override returns (uint) { return _availableToInvest(); } /* @notice Approve strategy @param _strategy Address of strategy to revoke */ function approveStrategy(address _strategy) external override onlyTimeLock { require(_strategy != address(0), "strategy = zero address"); strategies[_strategy] = true; emit ApproveStrategy(_strategy); } /* @notice Revoke strategy @param _strategy Address of strategy to revoke */ function revokeStrategy(address _strategy) external override onlyAdmin { require(_strategy != address(0), "strategy = zero address"); strategies[_strategy] = false; emit RevokeStrategy(_strategy); } /* @notice Set strategy to approved strategy @param _strategy Address of strategy used @param _min Minimum ETH current strategy must return. Prevents slippage */ function setStrategy(address _strategy, uint _min) external override onlyAdminOrController { require(strategies[_strategy], "!approved"); require(_strategy != strategy, "new strategy = current strategy"); require( IStrategyETH(_strategy).underlying() == ETH, "strategy.underlying != ETH" ); require( IStrategyETH(_strategy).vault() == address(this), "strategy.vault != vault" ); // withdraw from current strategy if (strategy != address(0)) { uint balBefore = _balanceInVault(); IStrategyETH(strategy).exit(); uint balAfter = _balanceInVault(); require(balAfter.sub(balBefore) >= _min, "withdraw < min"); } strategy = _strategy; emit SetStrategy(strategy); } /* @notice Invest ETH from vault into strategy. Some ETH are kept in vault for cheap withdraw. */ function invest() external override whenStrategyDefined whenNotPaused onlyAdminOrController { uint amount = _availableToInvest(); require(amount > 0, "available = 0"); IStrategyETH(strategy).deposit{value: amount}(); } /* @notice Deposit ETH into vault */ function deposit() external payable override whenNotPaused nonReentrant guard { require(msg.value > 0, "deposit = 0"); /* need to subtract msg.value to get total ETH before deposit totalAssets >= msg.value, since address(this).balance >= msg.value */ uint totalEth = _totalAssets() - msg.value; uint totalShares = totalSupply(); /* s = shares to mint T = total shares before mint d = deposit amount A = total ETH in vault + strategy before deposit s / (T + s) = d / (A + d) s = d / A * T */ uint shares; if (totalShares == 0) { shares = msg.value; } else { shares = msg.value.mul(totalShares).div(totalEth); } _mint(msg.sender, shares); } function _getExpectedReturn( uint _shares, uint _balInVault, uint _balInStrat ) private view returns (uint) { /* s = shares T = total supply of shares w = amount of ETH to withdraw E = total amount of redeemable ETH in vault + strategy s / T = w / E w = s / T * E */ /* total ETH = ETH in vault + min(total debt, ETH in strat) if ETH in strat > total debt, redeemable = total debt else redeemable = ETH in strat */ uint totalDebt = _totalDebtInStrategy(); uint totalEth; if (_balInStrat > totalDebt) { totalEth = _balInVault.add(totalDebt); } else { totalEth = _balInVault.add(_balInStrat); } uint totalShares = totalSupply(); if (totalShares > 0) { return _shares.mul(totalEth) / totalShares; } return 0; } /* @notice Calculate amount of ETH that can be withdrawn @param _shares Amount of shares @return Amount of ETH that can be withdrawn */ function getExpectedReturn(uint _shares) external view override returns (uint) { uint balInVault = _balanceInVault(); uint balInStrat = _balanceInStrategy(); return _getExpectedReturn(_shares, balInVault, balInStrat); } /* @dev WARNING check `_to` is not zero address before calling this function */ function _sendEth(address payable _to, uint _amount) private { (bool sent, ) = _to.call{value: _amount}(""); require(sent, "Send ETH failed"); } /* @notice Withdraw ETH @param _shares Amount of shares to burn @param _min Minimum amount of ETH to return @dev Keep `guard` modifier, else attacker can deposit and then use smart contract to attack from withdraw */ function withdraw(uint _shares, uint _min) external override nonReentrant guard { require(_shares > 0, "shares = 0"); uint balInVault = _balanceInVault(); uint balInStrat = _balanceInStrategy(); uint withdrawAmount = _getExpectedReturn(_shares, balInVault, balInStrat); // Must burn after calculating withdraw amount _burn(msg.sender, _shares); if (balInVault < withdrawAmount) { // maximize withdraw amount from strategy uint amountFromStrat = withdrawAmount; if (balInStrat < withdrawAmount) { amountFromStrat = balInStrat; } IStrategyETH(strategy).withdraw(amountFromStrat); uint balAfter = _balanceInVault(); uint diff = balAfter.sub(balInVault); if (diff < amountFromStrat) { // withdraw amount - withdraw amount from strat = amount to withdraw from vault // diff = actual amount returned from strategy // NOTE: withdrawAmount >= amountFromStrat withdrawAmount = (withdrawAmount - amountFromStrat).add(diff); } // transfer to treasury uint fee = withdrawAmount.mul(withdrawFee) / FEE_MAX; if (fee > 0) { // treasury must be able to receive ETH address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); withdrawAmount = withdrawAmount - fee; _sendEth(payable(treasury), fee); } } require(withdrawAmount >= _min, "withdraw < min"); _sendEth(msg.sender, withdrawAmount); } /* @notice Transfer token in vault to admin @param _token Address of token to transfer @dev Used to transfer token that was accidentally sent to this vault */ function sweep(address _token) external override onlyAdmin { IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this))); } }
* @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 { pragma solidity 0.6.11; function tryAdd(uint a, uint b) internal pure returns (bool, uint) { uint c = a + b; if (c < a) return (false, 0); return (true, c); } function trySub(uint a, uint b) internal pure returns (bool, uint) { if (b > a) return (false, 0); return (true, a - b); } function tryMul(uint a, uint b) internal pure returns (bool, uint) { if (a == 0) return (true, 0); uint c = a * b; if (c / a != b) return (false, 0); return (true, c); } function tryDiv(uint a, uint b) internal pure returns (bool, uint) { if (b == 0) return (false, 0); return (true, a / b); } function tryMod(uint a, uint b) internal pure returns (bool, uint) { if (b == 0) return (false, 0); return (true, a % b); } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns (uint) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) return 0; uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns (uint) { require(b > 0, "SafeMath: division by zero"); return a / b; } function mod(uint a, uint b) internal pure returns (uint) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } function sub( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b <= a, errorMessage); return a - b; } function div( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b > 0, errorMessage); return a / b; } function mod( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b > 0, errorMessage); return a % b; } }
6,656,191
[ 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, 203, 683, 9454, 18035, 560, 374, 18, 26, 18, 2499, 31, 203, 203, 565, 445, 775, 986, 12, 11890, 279, 16, 2254, 324, 13, 2713, 16618, 1135, 261, 6430, 16, 2254, 13, 288, 203, 3639, 2254, 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, 203, 565, 445, 775, 1676, 12, 11890, 279, 16, 2254, 324, 13, 2713, 16618, 1135, 261, 6430, 16, 2254, 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, 203, 565, 445, 775, 27860, 12, 11890, 279, 16, 2254, 324, 13, 2713, 16618, 1135, 261, 6430, 16, 2254, 13, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 327, 261, 3767, 16, 374, 1769, 203, 3639, 2254, 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, 203, 565, 445, 775, 7244, 12, 11890, 279, 16, 2254, 324, 13, 2713, 16618, 1135, 261, 6430, 16, 2254, 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, 203, 565, 445, 775, 1739, 12, 11890, 279, 16, 2254, 324, 2 ]
pragma solidity ^0.4.26; // INTERFACE interface ERC20 { function transferFrom(address _from, address _to, uint256 _value) external returns (bool); function transfer(address _to, uint256 _value) external returns (bool); function balanceOf(address _owner) external constant returns (uint256); function allowance(address _owner, address _spender) external returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); event Approval(address indexed _owner, address indexed _spender, uint256 _val); event Transfer(address indexed _from, address indexed _to, uint256 _val); } // CONTRACT contract ODS_Coin is ERC20 { uint256 public totalSupply; uint public decimals; string public symbol; string public name; mapping (address => mapping (address => uint256)) approach; mapping (address => uint256) holders; // CONSTRUCTOR CONTRACT constructor() public { name = "Operational Data Store"; symbol = "ODS"; decimals = 18; totalSupply = 1000000000 * 10**uint(decimals); holders[msg.sender] = totalSupply; } // REVERT IF ETHEREUM SEND function () public { revert(); } // CHECK BALANCE function balanceOf(address _own) public view returns (uint256) { return holders[_own]; } // TRANSFER TOKENS FROM YOUR ACCOUNT function transfer(address _to, uint256 _val) public returns (bool) { require(holders[msg.sender] >= _val); require(msg.sender != _to); assert(_val <= holders[msg.sender]); holders[msg.sender] = holders[msg.sender] - _val; holders[_to] = holders[_to] + _val; assert(holders[_to] >= _val); emit Transfer(msg.sender, _to, _val); return true; } // TRANSFER TOKENS FROM ANOTHER ACCOUNT function transferFrom(address _from, address _to, uint256 _val) public returns (bool) { require(holders[_from] >= _val); require(approach[_from][msg.sender] >= _val); assert(_val <= holders[_from]); holders[_from] = holders[_from] - _val; assert(_val <= approach[_from][msg.sender]); approach[_from][msg.sender] = approach[_from][msg.sender] - _val; holders[_to] = holders[_to] + _val; assert(holders[_to] >= _val); emit Transfer(_from, _to, _val); return true; } // APPROVE TOKENS TO SEND function approve(address _spender, uint256 _val) public returns (bool) { require(holders[msg.sender] >= _val); approach[msg.sender][_spender] = _val; emit Approval(msg.sender, _spender, _val); return true; } // CHECK APPROVE function allowance(address _owner, address _spender) public view returns (uint256) { return approach[_owner][_spender]; } }
CONSTRUCTOR CONTRACT
contract ODS_Coin is ERC20 { uint256 public totalSupply; uint public decimals; string public symbol; string public name; mapping (address => mapping (address => uint256)) approach; mapping (address => uint256) holders; constructor() public { name = "Operational Data Store"; symbol = "ODS"; decimals = 18; totalSupply = 1000000000 * 10**uint(decimals); holders[msg.sender] = totalSupply; } function () public { revert(); } function balanceOf(address _own) public view returns (uint256) { return holders[_own]; } function transfer(address _to, uint256 _val) public returns (bool) { require(holders[msg.sender] >= _val); require(msg.sender != _to); assert(_val <= holders[msg.sender]); holders[msg.sender] = holders[msg.sender] - _val; holders[_to] = holders[_to] + _val; assert(holders[_to] >= _val); emit Transfer(msg.sender, _to, _val); return true; } function transferFrom(address _from, address _to, uint256 _val) public returns (bool) { require(holders[_from] >= _val); require(approach[_from][msg.sender] >= _val); assert(_val <= holders[_from]); holders[_from] = holders[_from] - _val; assert(_val <= approach[_from][msg.sender]); approach[_from][msg.sender] = approach[_from][msg.sender] - _val; holders[_to] = holders[_to] + _val; assert(holders[_to] >= _val); emit Transfer(_from, _to, _val); return true; } function approve(address _spender, uint256 _val) public returns (bool) { require(holders[msg.sender] >= _val); approach[msg.sender][_spender] = _val; emit Approval(msg.sender, _spender, _val); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return approach[_owner][_spender]; } }
12,558,485
[ 1, 26935, 916, 8020, 2849, 1268, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 531, 3948, 67, 27055, 353, 4232, 39, 3462, 288, 203, 11890, 5034, 1071, 2078, 3088, 1283, 31, 203, 11890, 1071, 15105, 31, 203, 1080, 1071, 3273, 31, 203, 1080, 1071, 508, 31, 203, 6770, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 17504, 31, 203, 6770, 261, 2867, 516, 2254, 5034, 13, 366, 4665, 31, 203, 203, 203, 203, 12316, 1435, 1071, 288, 203, 1377, 508, 273, 315, 2988, 287, 1910, 4994, 14432, 203, 1377, 3273, 273, 315, 1212, 55, 14432, 203, 1377, 15105, 273, 6549, 31, 203, 1377, 2078, 3088, 1283, 273, 225, 15088, 3784, 380, 1728, 636, 11890, 12, 31734, 1769, 203, 1377, 366, 4665, 63, 3576, 18, 15330, 65, 273, 2078, 3088, 1283, 31, 203, 97, 203, 203, 203, 915, 1832, 1071, 288, 203, 266, 1097, 5621, 203, 97, 203, 203, 203, 915, 11013, 951, 12, 2867, 389, 995, 13, 203, 482, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 2463, 366, 4665, 63, 67, 995, 15533, 203, 97, 203, 203, 203, 915, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1125, 13, 203, 482, 1135, 261, 6430, 13, 288, 203, 6528, 12, 9000, 63, 3576, 18, 15330, 65, 1545, 389, 1125, 1769, 203, 6528, 12, 3576, 18, 15330, 480, 389, 869, 1769, 203, 11231, 24899, 1125, 1648, 366, 4665, 63, 3576, 18, 15330, 19226, 203, 9000, 63, 3576, 18, 15330, 65, 273, 366, 4665, 63, 3576, 18, 15330, 65, 300, 389, 1125, 31, 203, 9000, 63, 67, 869, 65, 273, 366, 4665, 63, 67, 869, 65, 2 ]
./partial_match/1/0x4f33B1FE407b4C0F57059a9Fd01f2739d313007C/sources/basarMarketPlace.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 onlyInitializing { } function __ERC721Enumerable_init_unchained() internal onlyInitializing { } mapping(address => mapping(uint256 => uint256)) private _ownedTokens; mapping(uint256 => uint256) private _ownedTokensIndex; uint256[] private _allTokens; mapping(uint256 => uint256) private _allTokensIndex; function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } 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]; } function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } } else if (from != to) { function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } } else if (to != from) { function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721Upgradeable.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; } delete _ownedTokens[from][lastTokenIndex]; } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; } delete _ownedTokens[from][lastTokenIndex]; } delete _ownedTokensIndex[tokenId]; function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenId = _allTokens[lastTokenIndex]; delete _allTokensIndex[tokenId]; _allTokens.pop(); } uint256[46] private __gap; }
2,882,062
[ 1, 2503, 4792, 392, 3129, 2710, 434, 288, 654, 39, 27, 5340, 97, 2553, 316, 326, 512, 2579, 716, 4831, 3557, 2967, 434, 777, 326, 1147, 3258, 316, 326, 6835, 487, 5492, 487, 777, 1147, 3258, 16199, 635, 1517, 2236, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 4232, 39, 27, 5340, 3572, 25121, 10784, 429, 353, 10188, 6934, 16, 4232, 39, 27, 5340, 10784, 429, 16, 467, 654, 39, 27, 5340, 3572, 25121, 10784, 429, 288, 203, 203, 203, 565, 445, 1001, 654, 39, 27, 5340, 3572, 25121, 67, 2738, 1435, 2713, 1338, 29782, 288, 203, 565, 289, 203, 203, 565, 445, 1001, 654, 39, 27, 5340, 3572, 25121, 67, 2738, 67, 4384, 8707, 1435, 2713, 1338, 29782, 288, 203, 565, 289, 203, 203, 203, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 11890, 5034, 516, 2254, 5034, 3719, 3238, 389, 995, 329, 5157, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 389, 995, 329, 5157, 1016, 31, 203, 565, 2254, 5034, 8526, 3238, 389, 454, 5157, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 389, 454, 5157, 1016, 31, 203, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 1071, 1476, 5024, 3849, 12, 45, 654, 39, 28275, 10784, 429, 16, 4232, 39, 27, 5340, 10784, 429, 13, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1560, 548, 422, 618, 12, 45, 654, 39, 27, 5340, 3572, 25121, 10784, 429, 2934, 5831, 548, 747, 2240, 18, 28064, 1358, 12, 5831, 548, 1769, 203, 565, 289, 203, 203, 565, 445, 1147, 951, 5541, 21268, 12, 2867, 3410, 16, 2254, 5034, 770, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 1615, 411, 4232, 39, 27, 5340, 10784, 429, 18, 12296, 951, 12, 8443, 2 ]
./full_match/43114/0x12ED2771c849C29ff3413099DDEf6dC987624144/sources/contracts/mac.sol
Contract implementation We will set a minimum amount of tokens to be swaped => 5M
contract MicrochainFinance 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 _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'Microchain Finance'; string private _symbol = 'MCF'; uint8 private _decimals = 9; uint256 private _taxFee = 10; uint256 private _teamFee = 10; uint256 private _previousTaxFee = _taxFee; uint256 private _previousTeamFee = _teamFee; address payable public _MCFWalletAddress; address payable public _marketingWalletAddress; IJoeRouter02 public immutable joeV2Router; address public immutable joeV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _maxTxAmount = 100000000000000e9; uint256 private walletLimitDuration; uint256 private _numOfTokensToExchangeForTeam = 5 * 10**3 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable MCFWalletAddress, address payable marketingWalletAddress) { _MCFWalletAddress = MCFWalletAddress; _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; joeV2Pair = IJoeFactory(_joeV2Router.factory()) .createPair(address(this), _joeV2Router.WAVAX()); joeV2Router = _joeV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; walletLimitDuration = block.timestamp + (60 minutes); emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } 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; (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } } else { function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(account != 0x60aE616a2155Ee3d9A68541Ba4544862310933d4, 'We can not exclude TraderJoe router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeAccount(address account) external onlyOwner() { require(account != 0x60aE616a2155Ee3d9A68541Ba4544862310933d4, 'We can not exclude TraderJoe router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _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]; _tOwned[account] = 0; _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]; _tOwned[account] = 0; _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]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { if(_taxFee == 0 && _teamFee == 0) return; _previousTaxFee = _taxFee; _previousTeamFee = _teamFee; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _teamFee = _previousTeamFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(sender == joeV2Pair && recipient != address(joeV2Router) && !_isExcludedFromFee[recipient]) { if (walletLimitDuration > block.timestamp) { uint walletBalance = balanceOf(address(recipient)); require(amount.add(walletBalance) <= _tTotal.mul(5).div(1000)); } } if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != joeV2Pair) { swapTokensForAvax(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendAVAXToTeam(address(this).balance); } } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(sender == joeV2Pair && recipient != address(joeV2Router) && !_isExcludedFromFee[recipient]) { if (walletLimitDuration > block.timestamp) { uint walletBalance = balanceOf(address(recipient)); require(amount.add(walletBalance) <= _tTotal.mul(5).div(1000)); } } if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != joeV2Pair) { swapTokensForAvax(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendAVAXToTeam(address(this).balance); } } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(sender == joeV2Pair && recipient != address(joeV2Router) && !_isExcludedFromFee[recipient]) { if (walletLimitDuration > block.timestamp) { uint walletBalance = balanceOf(address(recipient)); require(amount.add(walletBalance) <= _tTotal.mul(5).div(1000)); } } if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != joeV2Pair) { swapTokensForAvax(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendAVAXToTeam(address(this).balance); } } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(sender == joeV2Pair && recipient != address(joeV2Router) && !_isExcludedFromFee[recipient]) { if (walletLimitDuration > block.timestamp) { uint walletBalance = balanceOf(address(recipient)); require(amount.add(walletBalance) <= _tTotal.mul(5).div(1000)); } } if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != joeV2Pair) { swapTokensForAvax(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendAVAXToTeam(address(this).balance); } } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } } uint256 contractTokenBalance = balanceOf(address(this)); function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(sender == joeV2Pair && recipient != address(joeV2Router) && !_isExcludedFromFee[recipient]) { if (walletLimitDuration > block.timestamp) { uint walletBalance = balanceOf(address(recipient)); require(amount.add(walletBalance) <= _tTotal.mul(5).div(1000)); } } if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != joeV2Pair) { swapTokensForAvax(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendAVAXToTeam(address(this).balance); } } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(sender == joeV2Pair && recipient != address(joeV2Router) && !_isExcludedFromFee[recipient]) { if (walletLimitDuration > block.timestamp) { uint walletBalance = balanceOf(address(recipient)); require(amount.add(walletBalance) <= _tTotal.mul(5).div(1000)); } } if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != joeV2Pair) { swapTokensForAvax(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendAVAXToTeam(address(this).balance); } } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(sender == joeV2Pair && recipient != address(joeV2Router) && !_isExcludedFromFee[recipient]) { if (walletLimitDuration > block.timestamp) { uint walletBalance = balanceOf(address(recipient)); require(amount.add(walletBalance) <= _tTotal.mul(5).div(1000)); } } if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != joeV2Pair) { swapTokensForAvax(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendAVAXToTeam(address(this).balance); } } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } } bool takeFee = true; function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(sender == joeV2Pair && recipient != address(joeV2Router) && !_isExcludedFromFee[recipient]) { if (walletLimitDuration > block.timestamp) { uint walletBalance = balanceOf(address(recipient)); require(amount.add(walletBalance) <= _tTotal.mul(5).div(1000)); } } if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != joeV2Pair) { swapTokensForAvax(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendAVAXToTeam(address(this).balance); } } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } } _tokenTransfer(sender,recipient,amount,takeFee); function swapTokensForAvax(uint256 tokenAmount) private lockTheSwap{ address[] memory path = new address[](2); path[0] = address(this); path[1] = joeV2Router.WAVAX(); _approve(address(this), address(joeV2Router), tokenAmount); joeV2Router.swapExactTokensForAVAXSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function sendAVAXToTeam(uint256 amount) private { _MCFWalletAddress.transfer(amount.div(2)); _marketingWalletAddress.transfer(amount.div(2)); } function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForAvax(contractBalance); } function manualSend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendAVAXToTeam(contractETHBalance); } function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } } else if (!_isExcluded[sender] && _isExcluded[recipient]) { } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { } else if (_isExcluded[sender] && _isExcluded[recipient]) { } else { function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _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 tTeam) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _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 tTeam) = _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); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _teamFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 teamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(teamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getTaxFee() private view returns(uint256) { return _taxFee; } function _getMaxTxAmount() private view returns(uint256) { return _maxTxAmount; } function _getETHBalance() public view returns(uint256 balance) { return address(this).balance; } function _setTaxFee(uint256 taxFee) external onlyOwner() { require(taxFee >= 1 && taxFee <= 25, 'taxFee should be in 1 - 25'); _taxFee = taxFee; } function _setTeamFee(uint256 teamFee) external onlyOwner() { require(teamFee >= 1 && teamFee <= 25, 'teamFee should be in 1 - 25'); _teamFee = teamFee; } function _setMCFWallet(address payable MCFWalletAddress) external onlyOwner() { _MCFWalletAddress = MCFWalletAddress; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { require(maxTxAmount >= 100000000000000e9 , 'maxTxAmount should be greater than 100000000000000e9'); _maxTxAmount = maxTxAmount; } }
4,623,236
[ 1, 8924, 4471, 1660, 903, 444, 279, 5224, 3844, 434, 2430, 358, 506, 1352, 5994, 516, 1381, 49, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 6835, 18284, 5639, 6187, 1359, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 3639, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 3639, 1450, 5267, 364, 1758, 31, 203, 203, 3639, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 3639, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 3639, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 3639, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 203, 3639, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 31, 203, 3639, 1758, 8526, 3238, 389, 24602, 31, 203, 203, 203, 3639, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 3639, 2254, 5034, 3238, 389, 88, 5269, 273, 15088, 9449, 380, 1728, 636, 29, 31, 203, 3639, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 3639, 2254, 5034, 3238, 389, 88, 14667, 5269, 31, 203, 203, 3639, 533, 3238, 389, 529, 273, 296, 13617, 5639, 9458, 1359, 13506, 203, 3639, 533, 3238, 389, 7175, 273, 296, 49, 8955, 13506, 203, 3639, 2254, 28, 3238, 389, 31734, 273, 2468, 31, 203, 203, 3639, 2254, 5034, 3238, 389, 8066, 14667, 273, 1728, 31, 203, 3639, 2254, 5034, 3238, 389, 10035, 14667, 273, 1728, 31, 203, 3639, 2254, 5034, 3238, 389, 11515, 7731, 14667, 273, 389, 8066, 14667, 31, 203, 2 ]
./full_match/1/0x15062659dfDf3709De009a8f5c4ca48b0a888f0F/sources/IERC20.sol
* @dev Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address to, 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 from, address to, uint256 amount) external returns (bool); }
2,970,960
[ 1, 1358, 434, 326, 4232, 39, 3462, 4529, 487, 2553, 316, 326, 512, 2579, 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, 5831, 467, 654, 39, 3462, 288, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 203, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
contract LockMyEther { //Author: General_Illus //Date: 3/6/2016 //Version: LockMyEther v1.0 address owner; mapping (address => uint) fees; struct User { uint balance; // user balance uint expiration_block; // block ether is unlocked bool trickle; // turn trickle on/off uint trickle_block; // last block user attempted trickle witdrawal } mapping (address => User) user; // Constructor function LockMyEther(){ owner = msg.sender; fees[owner] = 0; } // Default function function() { main(); } // Deposit funds. User cannot alter expiration block once set. Can deposit more Ether though function main() { // Pay half of a percent fee to depost funds uint fee = msg.value / 200; fees[owner] += fee; // Deposit Funds uint deposit = msg.value - fee; user[msg.sender].balance += deposit; if (user[msg.sender].expiration_block > 0) return; user[msg.sender].expiration_block = 0; } // Withdraw funds function withdraw() { // Trickle is on, so allow withdraw based on variance between expiration block and last withdraw block if (user[msg.sender].trickle == true && user[msg.sender].expiration_block > block.number) { uint balance_per_block = user[msg.sender].balance / (user[msg.sender].expiration_block - user[msg.sender].trickle_block); uint trickle_balance = balance_per_block * (block.number - user[msg.sender].trickle_block); msg.sender.send(trickle_balance); user[msg.sender].balance = user[msg.sender].balance - trickle_balance; user[msg.sender].trickle_block = block.number; } // Trickle is off, test is current block is greater than expiration block, if true then withdraw else { if (user[msg.sender].expiration_block > block.number) return; msg.sender.send(user[msg.sender].balance); user[msg.sender].balance = 0; user[msg.sender].expiration_block = 0; } } // Withdraw fees function withdrawFees() { if (msg.sender == owner) owner.send(fees[owner]); fees[owner] = 0; } // Check balance of account function getBalance() constant returns (uint Balance) { return user[msg.sender].balance; } // Check balance of fee account function getFeeBalance() constant returns (uint FeeBalance) { if (msg.sender == owner) return fees[owner]; } // Get latest block number function getLatestBlock() constant returns (uint BlockNumber) { return block.number; } // Get expiration block function getExpirationBlock() constant returns (uint ExpirationBlock) { return user[msg.sender].expiration_block; } // Get trickle block function getTrickleBlock() constant returns (uint TrickleBlock) { return user[msg.sender].trickle_block; } // Get trickle status function getTrickle() constant returns (bool Trickle) { return user[msg.sender].trickle; } // Set expiration block function setExpirationBlock(uint _blocknumber) { // Do not allow anyone to set an expiration after one has already been set if (user[msg.sender].expiration_block > 0) return; // Do not allow anyone to set an expiration that is more than 9M blocks into future if (_blocknumber > block.number+9000000) return; user[msg.sender].expiration_block = _blocknumber; } //Turn trickle on function setTrickleOn() { user[msg.sender].trickle = true; user[msg.sender].trickle_block = block.number; } //Turn trickle off function setTrickleOff() { user[msg.sender].trickle = false; } // Suicide the contract //function destroyContract() { // if (msg.sender == owner){ // suicide(owner); // } //} }
Check balance of fee account
function getFeeBalance() constant returns (uint FeeBalance) { if (msg.sender == owner) return fees[owner]; }
6,456,029
[ 1, 1564, 11013, 434, 14036, 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, 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, 202, 915, 2812, 1340, 13937, 1435, 5381, 1135, 261, 11890, 30174, 13937, 13, 288, 203, 202, 202, 430, 261, 3576, 18, 15330, 422, 3410, 13, 203, 4202, 202, 202, 2463, 1656, 281, 63, 8443, 15533, 203, 565, 289, 203, 202, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x18C68B3adacE08C934408c343BC50a7EDe3F4aD7/sources/project_/contracts/EchoooERC721.sol
* @dev Returns true if the two strings are equal./
function equal(string memory a, string memory b) internal pure returns (bool) { return keccak256(bytes(a)) == keccak256(bytes(b)); }
1,859,728
[ 1, 1356, 638, 309, 326, 2795, 2064, 854, 3959, 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, 3959, 12, 1080, 3778, 279, 16, 533, 3778, 324, 13, 2713, 16618, 1135, 261, 6430, 13, 288, 203, 3639, 327, 417, 24410, 581, 5034, 12, 3890, 12, 69, 3719, 422, 417, 24410, 581, 5034, 12, 3890, 12, 70, 10019, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x66d97FD4DefEcD79904B3D3587dC4f8ed66Cf4Ab/sources/src/LSSVMRouter.sol
* @notice Buys NFTs with ETH and sells them for tokens in one transaction @param params All the parameters for the swap (packed in struct to avoid stack too deep), containing: - ethToNFTSwapList The list of NFTs to buy - nftToTokenSwapList The list of NFTs to sell - inputAmount The max amount of tokens to send (if ERC20) - tokenRecipient The address that receives tokens from the NFTs sold - nftRecipient The address that receives NFTs - deadline UNIX timestamp deadline for the swap/ Try doing each swap Calculate actual cost per swap If within our maxCost and no error, proceed We know how much ETH to send because we already did the math above So we just send that much Return remaining value to sender Try doing each swap Locally scoped to avoid stack too deep error If at least equal to our minOutput, proceed Do the swap and update outputAmount with how many tokens we got
function robustSwapETHForSpecificNFTsAndNFTsToToken(RobustPairNFTsFoTokenAndTokenforNFTsTrade calldata params) external payable virtual returns (uint256 remainingValue, uint256 outputAmount) { { remainingValue = msg.value; uint256 pairCost; CurveErrorCodes.Error error; uint256 numSwaps = params.tokenToNFTTrades.length; for (uint256 i; i < numSwaps;) { (error,,, pairCost,,) = params.tokenToNFTTrades[i].swapInfo.pair.getBuyNFTQuote( params.tokenToNFTTrades[i].swapInfo.nftIds[0], params.tokenToNFTTrades[i].swapInfo.nftIds.length ); if (pairCost <= params.tokenToNFTTrades[i].maxCost && error == CurveErrorCodes.Error.OK) { params.tokenToNFTTrades[i].swapInfo.nftIds, pairCost, params.nftRecipient, true, msg.sender ); } unchecked { ++i; } } if (remainingValue > 0) { params.tokenRecipient.safeTransferETH(remainingValue); } } { uint256 numSwaps = params.nftToTokenTrades.length; for (uint256 i; i < numSwaps;) { uint256 pairOutput; { CurveErrorCodes.Error error; uint256 assetId = params.nftToTokenTrades[i].swapInfo.nftIds[0]; (error,,, pairOutput,,) = params.nftToTokenTrades[i].swapInfo.pair.getSellNFTQuote( assetId, params.nftToTokenTrades[i].swapInfo.nftIds.length ); if (error != CurveErrorCodes.Error.OK) { unchecked { ++i; } continue; } } if (pairOutput >= params.nftToTokenTrades[i].minOutput) { outputAmount += params.nftToTokenTrades[i].swapInfo.pair.swapNFTsForToken( params.nftToTokenTrades[i].swapInfo.nftIds, 0, params.tokenRecipient, true, msg.sender ); } unchecked { ++i; } } } }
8,297,851
[ 1, 38, 89, 1900, 423, 4464, 87, 598, 512, 2455, 471, 357, 3251, 2182, 364, 2430, 316, 1245, 2492, 225, 859, 4826, 326, 1472, 364, 326, 7720, 261, 2920, 329, 316, 1958, 358, 4543, 2110, 4885, 4608, 3631, 4191, 30, 300, 13750, 774, 50, 4464, 12521, 682, 1021, 666, 434, 423, 4464, 87, 358, 30143, 300, 290, 1222, 774, 1345, 12521, 682, 1021, 666, 434, 423, 4464, 87, 358, 357, 80, 300, 810, 6275, 1021, 943, 3844, 434, 2430, 358, 1366, 261, 430, 4232, 39, 3462, 13, 300, 1147, 18241, 1021, 1758, 716, 17024, 2430, 628, 326, 423, 4464, 87, 272, 1673, 300, 290, 1222, 18241, 1021, 1758, 716, 17024, 423, 4464, 87, 300, 14096, 23160, 2858, 14096, 364, 326, 7720, 19, 6161, 9957, 1517, 7720, 9029, 3214, 6991, 1534, 7720, 971, 3470, 3134, 943, 8018, 471, 1158, 555, 16, 11247, 1660, 5055, 3661, 9816, 512, 2455, 358, 1366, 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, 27920, 12521, 1584, 44, 1290, 9969, 50, 4464, 87, 1876, 50, 4464, 11634, 1345, 12, 14444, 641, 4154, 50, 4464, 87, 42, 83, 1345, 1876, 1345, 1884, 50, 4464, 87, 22583, 745, 892, 859, 13, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 5024, 203, 3639, 1135, 261, 11890, 5034, 4463, 620, 16, 2254, 5034, 876, 6275, 13, 203, 565, 288, 203, 3639, 288, 203, 5411, 4463, 620, 273, 1234, 18, 1132, 31, 203, 5411, 2254, 5034, 3082, 8018, 31, 203, 5411, 22901, 668, 6295, 18, 668, 555, 31, 203, 203, 5411, 2254, 5034, 818, 6050, 6679, 273, 859, 18, 2316, 774, 26473, 1470, 354, 5489, 18, 2469, 31, 203, 5411, 364, 261, 11890, 5034, 277, 31, 277, 411, 818, 6050, 6679, 30943, 288, 203, 7734, 261, 1636, 16408, 16, 3082, 8018, 16408, 13, 273, 859, 18, 2316, 774, 26473, 1470, 354, 5489, 63, 77, 8009, 22270, 966, 18, 6017, 18, 588, 38, 9835, 50, 4464, 10257, 12, 203, 10792, 859, 18, 2316, 774, 26473, 1470, 354, 5489, 63, 77, 8009, 22270, 966, 18, 82, 1222, 2673, 63, 20, 6487, 859, 18, 2316, 774, 26473, 1470, 354, 5489, 63, 77, 8009, 22270, 966, 18, 82, 1222, 2673, 18, 2469, 203, 7734, 11272, 203, 203, 7734, 309, 261, 6017, 8018, 1648, 859, 18, 2316, 774, 26473, 1470, 354, 5489, 63, 77, 8009, 1896, 8018, 597, 555, 422, 22901, 668, 6295, 18, 668, 18, 3141, 13, 288, 203, 13491, 859, 18, 2316, 774, 26473, 1470, 354, 5489, 63, 77, 8009, 22270, 966, 18, 2 ]
pragma solidity ^0.5.2; import "./Ownable.sol"; import "asn1-decode/contracts/Asn1Decode.sol"; import "@ensdomains/dnssec-oracle/contracts/algorithms/Algorithm.sol"; import "ens-namehash/contracts/ENSNamehash.sol"; import "ethereum-datetime/contracts/DateTime.sol"; /* * @dev Stores validated X.509 certificate chains in parent pointer trees. * @dev The root of each tree is a CA root certificate */ contract X509ForestOfTrust is Ownable { using Asn1Decode for bytes; using ENSNamehash for bytes; bytes10 constant private OID_SUBJECT_ALT_NAME = 0x551d1100000000000000; bytes10 constant private OID_BASIC_CONSTRAINTS = 0x551d1300000000000000; bytes10 constant private OID_NAME_CONSTRAINTS = 0x551d1e00000000000000; bytes10 constant private OID_KEY_USAGE = 0x551d0f00000000000000; bytes10 constant private OID_EXTENDED_KEY_USAGE = 0x551d2500000000000000; bytes10 private OID_CAN_SIGN_HTTP_EXCHANGES = 0x2b06010401d679020116; // Not constant because spec may change constructor(address sha256WithRSAEncryption, address _dateTime) public { bytes32 algOid = 0x2a864886f70d01010b0000000000000000000000000000000000000000000000; algs[algOid] = Algorithm(sha256WithRSAEncryption); dateTime = DateTime(_dateTime); } struct KeyUsage { bool critical; bool present; uint16 bits; // Value of KeyUsage bits. (E.g. 5 is 000000101) } struct ExtKeyUsage { bool critical; bool present; bytes32[] oids; } struct Certificate { address owner; bytes32 parentId; uint40 timestamp; uint160 serialNumber; uint40 validNotBefore; uint40 validNotAfter; bool cA; // Whether the certified public key may be used to verify certificate signatures. uint8 pathLenConstraint; // Maximum number of non-self-issued intermediate certs that may follow this // cert in a valid certification path. KeyUsage keyUsage; ExtKeyUsage extKeyUsage; bool sxg; // canSignHttpExchanges extension is present. bytes32 extId; // keccak256 of extensions field for further validation. // Equal to 0x0 unless a critical extension was found but not parsed. // This should always be checked on leaf certificates } mapping (bytes32 => Certificate) private certs; // certId => cert (certId is keccak256(pubKey)) mapping (bytes32 => Algorithm) private algs; // algorithm oid bytes => signature verification contract mapping (bytes32 => bytes32[]) public toCertIds; // ensNamehash(subjectAltName) => certId mapping (bytes32 => bytes32) public toCertId; // sha256 fingerprint => certId DateTime dateTime; // For dateTime conversion event CertAdded(bytes32); event CertClaimed(bytes32, address); event AlgSet(bytes32, address); /** * @dev Add a X.509 certificate to an existing tree/chain * @param cert A DER-encoded X.509 certificate * @param parentPubKey The parent certificate's DER-encoded public key */ function addCert(bytes memory cert, bytes memory parentPubKey) public { Certificate memory certificate; bytes32 certId; uint node1; uint node2; uint node3; uint node4; certificate.parentId = keccak256(parentPubKey); certificate.timestamp = uint40(block.timestamp); node1 = cert.root(); node1 = cert.firstChildOf(node1); node2 = cert.firstChildOf(node1); if (cert[NodePtr.ixs(node2)] == 0xa0) { node2 = cert.nextSiblingOf(node2); } // Extract serial number certificate.serialNumber = uint160(cert.uintAt(node2)); node2 = cert.nextSiblingOf(node2); node2 = cert.firstChildOf(node2); node3 = cert.nextSiblingOf(node1); node3 = cert.nextSiblingOf(node3); // Verify signature require(algs[cert.bytes32At(node2)].verify(parentPubKey, cert.allBytesAt(node1), cert.bytesAt(node3)), "Signature doesnt match"); node1 = cert.firstChildOf(node1); node1 = cert.nextSiblingOf(node1); node1 = cert.nextSiblingOf(node1); node1 = cert.nextSiblingOf(node1); node1 = cert.nextSiblingOf(node1); node2 = cert.firstChildOf(node1); // Check validNotBefore certificate.validNotBefore = uint40(toTimestamp(cert.bytesAt(node2))); require(certificate.validNotBefore <= now, "Now is before validNotBefore"); node2 = cert.nextSiblingOf(node2); // Check validNotAfter certificate.validNotAfter = uint40(toTimestamp(cert.bytesAt(node2))); require(now <= certificate.validNotAfter, "Now is after validNotAfter"); node1 = cert.nextSiblingOf(node1); node1 = cert.nextSiblingOf(node1); // Get public key and calculate certId from it certId = cert.keccakOfAllBytesAt(node1); // Cert must not already exist // Prevents duplicate references and owner from being overridden require(certs[certId].validNotAfter == 0); // Fire event emit CertAdded(certId); // Add reference from sha256 fingerprint toCertId[sha256(cert)] = certId; node1 = cert.nextSiblingOf(node1); // Skip over v2 fields if (cert[NodePtr.ixs(node1)] == 0xa1) node1 = cert.nextSiblingOf(node1); if (cert[NodePtr.ixs(node1)] == 0xa2) node1 = cert.nextSiblingOf(node1); // Parse extensions if (cert[NodePtr.ixs(node1)] == 0xa3) { node1 = cert.firstChildOf(node1); node2 = cert.firstChildOf(node1); bytes10 oid; bool isCritical; while (Asn1Decode.isChildOf(node2, node1)) { node3 = cert.firstChildOf(node2); oid = bytes10(cert.bytes32At(node3)); // Extension oid node3 = cert.nextSiblingOf(node3); // Check if extension is critical isCritical = false; if (cert[NodePtr.ixs(node3)] == 0x01) { // If type is bool if (cert[NodePtr.ixf(node3)] != 0x00) // If not false isCritical = true; node3 = cert.nextSiblingOf(node3); } if (oid == OID_SUBJECT_ALT_NAME) { // Add references from names node3 = cert.rootOfOctetStringAt(node3); node4 = cert.firstChildOf(node3); while (Asn1Decode.isChildOf(node4, node3)) { if(cert[NodePtr.ixs(node4)] == 0x82) toCertIds[cert.bytesAt(node4).namehash()].push(certId); else toCertIds[cert.keccakOfBytesAt(node4)].push(certId); node4 = cert.nextSiblingOf(node4); } } else if (oid == OID_BASIC_CONSTRAINTS) { if (isCritical) { // Check if cert can sign other certs node3 = cert.rootOfOctetStringAt(node3); node4 = cert.firstChildOf(node3); // If sequence (node3) is not empty if (Asn1Decode.isChildOf(node4, node3)) { // If value == true if (cert[NodePtr.ixf(node4)] != 0x00) { certificate.cA = true; node4 = cert.nextSiblingOf(node4); if (Asn1Decode.isChildOf(node4, node3)) { certificate.pathLenConstraint = uint8(cert.uintAt(node4)); } else { certificate.pathLenConstraint = uint8(-1); } } } } } else if (oid == OID_KEY_USAGE) { certificate.keyUsage.present = true; certificate.keyUsage.critical = isCritical; node3 = cert.rootOfOctetStringAt(node3); bytes3 v = bytes3(cert.bytes32At(node3)); // The encoded bitstring value certificate.keyUsage.bits = ((uint16(uint8(v[1])) << 8) + uint16(uint8(v[2]))) >> 7; } else if (oid == OID_EXTENDED_KEY_USAGE) { certificate.extKeyUsage.present = true; certificate.extKeyUsage.critical = isCritical; node3 = cert.rootOfOctetStringAt(node3); node4 = cert.firstChildOf(node3); uint len; while (Asn1Decode.isChildOf(node4, node3)) { len++; node4 = cert.nextSiblingOf(node4); } bytes32[] memory oids = new bytes32[](len); node4 = cert.firstChildOf(node3); for (uint i; i<len; i++) { oids[i] = cert.bytes32At(node4); node4 = cert.nextSiblingOf(node4); } certificate.extKeyUsage.oids = oids; } else if (oid == OID_CAN_SIGN_HTTP_EXCHANGES) { certificate.sxg = true; } else if (oid == OID_NAME_CONSTRAINTS) { // Name constraints not allowed. require(false, "Name constraints extension not supported"); } else if (isCritical && certificate.extId == bytes32(0)) { // Note: unrecognized critical extensions are allowed. // Further validation of certificate is needed if extId != bytes32(0). // Save hash of extensions certificate.extId = cert.keccakOfAllBytesAt(node1); } node2 = cert.nextSiblingOf(node2); } } certs[certId] = certificate; require(certs[certificate.parentId].cA, "Invalid parent cert"); // If intermediate cert, verify authority's pathLenConstraint if (certificate.cA && certId != certificate.parentId) require(certs[certificate.parentId].pathLenConstraint == uint8(-1) || certs[certificate.parentId].pathLenConstraint > certificate.pathLenConstraint, "Invalid parent cert"); // RFC 5280: If the cA boolean is not asserted, then the keyCertSign // bit in the key usage extension MUST NOT be asserted. if (!certificate.cA) require(certificate.keyUsage.bits & 8 != 8, "cA boolean is not asserted and keyCertSign bit is asserted"); } /** * @dev The return values of this function are used to proveOwnership() of a * certificate that exists in the certs mapping. * @return Some unique bytes to be signed * @return The block number used to create the first return value */ function signThis() external view returns (bytes memory, uint) { return ( abi.encodePacked(msg.sender, blockhash(block.number - 1)), block.number -1 ); } /** * @dev An account calls this method to prove ownership of a certificate. * If successful, certs[certId].owner will be set to caller's address. * @param pubKey The target certificate's public key * @param signature signThis()[0] signed with certificate's private key * @param blockNumber The value of signThis()[1] (must be > block.number - 256) * @param sigAlg The OID of the algorithm used to sign `signature` */ function proveOwnership(bytes calldata pubKey, bytes calldata signature, uint blockNumber, bytes32 sigAlg) external { bytes32 certId = keccak256(pubKey); bytes memory message = abi.encodePacked(msg.sender, blockhash(blockNumber)); emit CertClaimed(certId, msg.sender); // Only accept proof if it's less than 256 blocks old // This is the most time I can give since blockhash() can only return the 256 most recent require(block.number - blockNumber < 256, "Signature too old"); // Verify signature, which proves ownership require(algs[sigAlg].verify(pubKey, message, signature), "Signature doesnt match"); certs[certId].owner = msg.sender; } function rootOf(bytes32 certId) external view returns (bytes32) { bytes32 id = certId; while (id != certs[id].parentId) { id = certs[id].parentId; } return id; } function owner(bytes32 certId) external view returns (address) { return certs[certId].owner; } function parentId(bytes32 certId) external view returns (bytes32) { return certs[certId].parentId; } function timestamp(bytes32 certId) external view returns (uint40) { return certs[certId].timestamp; } function serialNumber(bytes32 certId) external view returns (uint160) { return certs[certId].serialNumber; } function validNotBefore(bytes32 certId) external view returns (uint40) { return certs[certId].validNotBefore; } function validNotAfter(bytes32 certId) external view returns (uint40) { return certs[certId].validNotAfter; } function sxg(bytes32 certId) external view returns (bool) { return certs[certId].sxg; } function basicConstraints(bytes32 certId) external view returns (bool, uint8) { return (certs[certId].cA, certs[certId].pathLenConstraint); } function keyUsage(bytes32 certId) external view returns (bool, bool[9] memory) { KeyUsage memory _keyUsage = certs[certId].keyUsage; uint16 mask = 256; bool[9] memory flags; if (_keyUsage.present) { for (uint i; i<9; i++) { flags[i] = (_keyUsage.bits & mask == mask); mask = mask >> 1; } } return (_keyUsage.present, flags); } function keyUsageCritical(bytes32 certId) external view returns (bool) { return certs[certId].keyUsage.critical; } function extKeyUsage(bytes32 certId) external view returns (bool, bytes32[] memory) { ExtKeyUsage memory _extKeyUsage = certs[certId].extKeyUsage; return (_extKeyUsage.present, _extKeyUsage.oids); } function extKeyUsageCritical(bytes32 certId) external view returns (bool) { return certs[certId].extKeyUsage.critical; } function unparsedCriticalExtensionPresent(bytes32 certId) external view returns (bool) { return (certs[certId].extId != bytes32(0)); } function extId(bytes32 certId) external view returns (bytes32) { return certs[certId].extId; } function toCertIdsLength(bytes32 _hash) external view returns (uint) { return toCertIds[_hash].length; } function toTimestamp(bytes memory x509Time) private view returns (uint) { uint16 yrs; uint8 mnths; uint8 dys; uint8 hrs; uint8 mins; uint8 secs; uint8 offset; if (x509Time.length == 13) { if (uint8(x509Time[0])-48 < 5) yrs += 2000; else yrs += 1900; } else { yrs += (uint8(x509Time[0])-48) * 1000 + (uint8(x509Time[1])-48) * 100; offset = 2; } yrs += (uint8(x509Time[offset+0])-48)*10 + uint8(x509Time[offset+1])-48; mnths = (uint8(x509Time[offset+2])-48)*10 + uint8(x509Time[offset+3])-48; dys += (uint8(x509Time[offset+4])-48)*10 + uint8(x509Time[offset+5])-48; hrs += (uint8(x509Time[offset+6])-48)*10 + uint8(x509Time[offset+7])-48; mins += (uint8(x509Time[offset+8])-48)*10 + uint8(x509Time[offset+9])-48; secs += (uint8(x509Time[offset+10])-48)*10 + uint8(x509Time[offset+11])-48; return dateTime.toTimestamp(yrs, mnths, dys, hrs, mins, secs); } function setAlg(bytes32 oid, address alg) external onlyOwner { algs[oid] = Algorithm(alg); emit AlgSet(oid, alg); } function setSxgOid(bytes32 sxgOid) external onlyOwner { OID_CAN_SIGN_HTTP_EXCHANGES = bytes10(sxgOid); } }
Add reference from sha256 fingerprint
toCertId[sha256(cert)] = certId;
5,374,515
[ 1, 986, 2114, 628, 6056, 5034, 12115, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 358, 5461, 548, 63, 7819, 5034, 12, 7593, 25887, 273, 3320, 548, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IToken is IERC20{ function decimals() external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "./Interfaces/IWETH.sol"; import "./Interfaces/IToken.sol"; import "./Interfaces/IWHAsset.sol"; import "./Interfaces/IWhiteUSDCPool.sol"; import "./Interfaces/IWhiteOptionsPricer.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; interface IKeep3r { function getRequestedPayment() external view returns (uint); } /** * @author jmonteer * @title Whiteheart's Hedge Contract * @notice WHAsset implementation. Hedge contract: Wraps an amount of the underlying asset with an ATM put option (or other protection instrument) */ abstract contract WHAssetv2 is ERC721, IWHAssetv2, Ownable { using Counters for Counters.Counter; using SafeMath for uint; using SafeMath for uint48; uint256 internal constant PRICE_DECIMALS = 1e8; uint256 public optionCollateralizationRatio = 100; address[] public underlyingToStableSwapPath; Counters.Counter private _tokenIds; IWhiteUSDCPool public immutable pool; IWhiteOptionsPricer public whiteOptionsPricer; IUniswapV2Router02 public immutable swapRouter; AggregatorV3Interface public immutable priceProvider; address public keep3r; address public router; uint internal immutable DECIMALS; IERC20 public immutable stablecoin; mapping(uint => Underlying) public underlying; mapping(address => bool) public autoUnwrapDisabled; constructor( IUniswapV2Router02 _swapRouter, IToken _stablecoin, IToken _token, AggregatorV3Interface _priceProvider, IWhiteUSDCPool _pool, IWhiteOptionsPricer _whiteOptionsPricer, string memory _name, string memory _symbol) public ERC721(_name, _symbol) { uint _DECIMALS = 10 ** (uint(IToken(_token).decimals()).sub(uint(IToken(_stablecoin).decimals()))) * PRICE_DECIMALS; DECIMALS = _DECIMALS; address[] memory _underlyingToStableSwapPath = new address[](2); _underlyingToStableSwapPath[0] = address(_token); _underlyingToStableSwapPath[1] = address(_stablecoin); underlyingToStableSwapPath = _underlyingToStableSwapPath; swapRouter = _swapRouter; whiteOptionsPricer = _whiteOptionsPricer; priceProvider = _priceProvider; stablecoin = _stablecoin; pool = _pool; } modifier onlyKeep3r { require(msg.sender == address(this) || msg.sender == keep3r, "!not allowed"); _; } modifier onlyTokenOwner(uint tokenId) { require(underlying[tokenId].owner == msg.sender, "msg.sender != owner"); _; } modifier onlyRouter { require(msg.sender == router, "!not allowed"); _; } /** * @notice Sets swap router to swap underlying into USDC to pay for the protection * @param newRouter address of swapRouter contract */ function setRouter(address newRouter) external onlyOwner { router = newRouter; } /** * @notice Sets the Keep3r contract address. Keep3r is in charge of auto unwrapping a HedgeContract when it is in owner's best interest * @param newKeep3r address of Keep3r contract */ function setKeep3r(address newKeep3r) external onlyOwner { keep3r = newKeep3r; } /** * @notice Returns cost of certain protection * @param amount amount to be protected * @param period duration of quoted protection * @return cost of protection */ function wrapCost(uint amount, uint period) view external returns (uint cost){ uint strike = _currentPrice(); return whiteOptionsPricer.getOptionPrice(period, amount, strike); } /** * @notice Wraps an amount of principal into a HedgeContract * @param amount amount to be protected (principal) * @param period duration of protection * @param to recipient of WHAsset (onBehalfOf) * @param _mintToken boolean telling the function to mint a new ERC721 token representing this Hedge Contract or not * @param minPremiumUSDC param to protect against DEX slippage and front-running txs * @return newTokenId ID of new HedgeContract and its token if minted */ function wrap(uint128 amount, uint period, address to, bool _mintToken, uint minPremiumUSDC) payable public override virtual returns (uint newTokenId) { newTokenId = _wrap(uint(amount), period, to, true, _mintToken, minPremiumUSDC); } /** * @notice Mints a token of an existing hedge contract * @param tokenId hedge contract id to mint a token for */ function mintToken(uint tokenId) external { require(underlying[tokenId].active && underlying[tokenId].owner == msg.sender, "!not-tokenizable"); _mint(msg.sender, tokenId); } /** * @notice Unwraps an active or inactive Hedge Contract, receiving back the principal amount * @param tokenId hedge contract id to be unwrapped */ function unwrap(uint tokenId) external override onlyTokenOwner(tokenId) { _unwrap(tokenId); } /** * @notice Returns a list of autounwrappable hedge contracts. To be called off-chain * @return list of autounwrappable hedge contracts */ function listAutoUnwrapable() external view returns (uint[] memory list) { uint counter = 0; for(uint i = 0; i <= _tokenIds.current() ; i++) { if(isAutoUnwrapable(i)) counter++; } list = new uint[](counter); uint index = 0; for(uint i = 0; i <= _tokenIds.current() ; i++) { if(isAutoUnwrapable(i)){ list[index] = i; index++; } if(index>=counter) return list; } } /** * @notice Unwraps a list of autoUnwrappable hedge contracts in exchange for a fee (if called by Keep3r) * @param list list of hedge contracts to be unwrapped * @param rewardRecipient address of the recipient of the fees in exchange of autoExercise * @return reward that keep3r will receive */ function autoUnwrapAll(uint[] calldata list, address rewardRecipient) external override returns (uint reward) { for(uint i = 0; i < list.length; i++){ if(isAutoUnwrapable(list[i])) { _unwrap(list[i]); } } if(address(msg.sender).isContract() && msg.sender == keep3r) reward = pool.payKeep3r(rewardRecipient); } /** * @notice Unwraps a autoUnwrappable hedge contracts in exchange for a fee (if called by Keep3r) * @param tokenId HedgeContract to be unwrapped * @param rewardRecipient address of the recipient of the fees in exchange of autoExercise * @return reward that keep3r will receive */ function autoUnwrap(uint tokenId, address rewardRecipient) public override returns (uint reward) { require(isAutoUnwrapable(tokenId), "!not-unwrapable"); _unwrap(tokenId); if(address(msg.sender).isContract() && msg.sender == keep3r) reward = pool.payKeep3r(rewardRecipient); } /** * @notice Disables (or enables) autounwrapping for caller. If set to true, keep3rs wont be able to unwrap this user's WHAssets * @param disabled true to disable autounwrapping, false to re-enable autounwrapping */ function setAutoUnwrapDisabled(bool disabled) external { autoUnwrapDisabled[msg.sender] = disabled; } /** * @notice Answers the question: is this hedge contract Auto unwrappable? * @param tokenId HedgeContract to be unwrapped * @return answer to the question: is this hedge contract Auto unwrappable */ function isAutoUnwrapable(uint tokenId) public view returns (bool) { Underlying memory _underlying = underlying[tokenId]; if(autoUnwrapDisabled[_underlying.owner]) return false; if(!_underlying.active) return false; bool ITM = false; uint currentPrice = _currentPrice(); ITM = currentPrice < _underlying.strike; // if option is In The Money and the option is going to expire in the next minutes if (ITM && ((_underlying.expiration.sub(30 minutes) <= block.timestamp) && (_underlying.expiration >= block.timestamp))) { return true; } return false; } /** * @notice Internal function that wraps a hedge contract * @param amount amount * @param period period * @param to address that will receive the hedgecontract * @param receiveAsset whether or not require asset from sender * @param _mintToken whether or not to mint a token representing the hedge contract * @return newTokenId new token id */ function _wrap(uint amount, uint period, address to, bool receiveAsset, bool _mintToken, uint minPremiumUSDC) internal returns (uint newTokenId){ // new tokenId _tokenIds.increment(); newTokenId = _tokenIds.current(); // get cost of option uint strike = _currentPrice(); uint total = whiteOptionsPricer.getOptionPrice(period, amount, strike); // receive asset + cost of hedge if(receiveAsset) _receiveAsset(msg.sender, amount, total); // buy option _createHedge(newTokenId, total, period, amount, strike, to, minPremiumUSDC); // mint ERC721 token if(_mintToken) _mint(to, newTokenId); emit Wrap(to, uint32(newTokenId), uint88(total), uint88(amount), uint48(strike), uint32(block.timestamp+period)); } /** * @notice Internal function that creates the option protecting it * @param tokenId hedge contract id * @param totalFee total fee to be paid for the option * @param period seconds of duration of protection * @param amount amount to be protected * @param strike price at which the asset is protected * @param owner address of the owner of the hedge contract */ function _createHedge(uint tokenId, uint totalFee, uint period, uint amount, uint strike, address owner, uint minPremiumUSDC) internal { uint collateral = amount.mul(strike).mul(optionCollateralizationRatio).div(100).div(DECIMALS); underlying[tokenId] = Underlying( bool(true), address(owner), uint88(amount), uint48(block.timestamp + period), uint48(strike) ); uint[] memory amounts = swapRouter.swapExactTokensForTokens( totalFee, minPremiumUSDC, underlyingToStableSwapPath, address(pool), block.timestamp ); uint totalStablecoin = amounts[amounts.length - 1]; pool.lock(tokenId, collateral, totalStablecoin); } /** * @notice Exercises an option. only callable when unwrapping a hedge contract * @param tokenId id of hedge contract * @param owner owner of contract * @return optionProfit profit of exercised option * @return amount principal amount that was protected by it */ function _exercise(uint tokenId, address owner) internal returns (uint optionProfit, uint amount, uint underlyingCurrentPrice) { Underlying storage _underlying = underlying[tokenId]; amount = _underlying.amount; underlyingCurrentPrice = _currentPrice(); if(_underlying.expiration < block.timestamp){ pool.unlock(tokenId); optionProfit = 0; } else { (optionProfit) = _payProfit(owner, tokenId, _underlying.strike, _underlying.amount, underlyingCurrentPrice); } } /** * @notice Pays profit (if any) of underlying option * @param owner address of owner * @param tokenId tokenId * @param strike price at which the asset was protected * @param amount principal amount that was protected * @return profit profit of exercised option */ function _payProfit(address owner, uint tokenId, uint strike, uint amount, uint underlyingCurrentPrice) internal returns (uint profit) { if(strike <= underlyingCurrentPrice){ profit = 0; } else { profit = strike.sub(underlyingCurrentPrice).mul(amount).div(DECIMALS); } address _keep3r = address(msg.sender).isContract() ? keep3r : address(0); uint payKeep3r = _keep3r != address(0) ? IKeep3r(_keep3r).getRequestedPayment() : 0; require(payKeep3r <= profit, "!keep3r-requested-too-much"); pool.send(tokenId, payable(owner), profit, payKeep3r); } /** * @notice Unwraps hedge contract * @param tokenId tokenId * @return owner address of hedge contract address * @return optionProfit profit of exercised option */ function _unwrap(uint tokenId) internal returns (address owner, uint optionProfit) { Underlying storage _underlying = underlying[tokenId]; owner = _underlying.owner; require(owner != address(0), "!tokenId-does-not-exist"); require(_underlying.active, "!tokenId-does-not-exist"); // exercise option (uint profit, uint amount, uint underlyingCurrentPrice) = _exercise(tokenId, owner); // burn token if(_exists(tokenId)) _burn(tokenId); _underlying.active = false; _sendTotal(payable(owner), amount); optionProfit = profit; emit Unwrap(owner, uint32(tokenId), uint128(underlyingCurrentPrice), uint128(profit)); } /** * @notice changes hedge contract owner using HedgeContract underlying * @param from sender * @param to recipient * @param tokenId tokenId */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override { if(from != address(0) && to != address(0)){ require(underlying[tokenId].owner == from, "!sth-went-wrong"); underlying[tokenId].owner = to; } } function _receiveAsset(address from, uint amount, uint hedgeCost) internal virtual; function _sendTotal(address payable from, uint amount) internal virtual; function _currentPrice() internal view returns (uint) { ( , int price, , , ) = priceProvider.latestRoundData(); return uint(price); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH is IERC20 { function deposit() payable external; function withdraw(uint wad) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; interface IWHAssetv2 { event Wrap(address indexed account, uint32 indexed tokenId, uint88 cost, uint88 amount, uint48 strike, uint32 expiration); event Unwrap(address indexed account, uint32 indexed tokenId, uint128 closePrice, uint128 optionProfit); struct Underlying { bool active; address owner; uint88 amount; uint48 expiration; uint48 strike; } function wrap(uint128 amount, uint period, address to, bool mintToken, uint minUSDCPremium) payable external returns (uint newTokenId); function unwrap(uint tokenId) external; function autoUnwrap(uint tokenId, address rewardRecipient) external returns (uint); function autoUnwrapAll(uint[] calldata tokenIds, address rewardRecipient) external returns (uint); function wrapAfterSwap(uint total, uint protectionPeriod, address to, bool mintToken, uint minUSDCPremium) external returns (uint newTokenId); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; interface ILiquidityPool { struct LockedLiquidity { uint120 amount; uint120 premium; bool locked; } event Profit(uint indexed id, uint amount); event Loss(uint indexed id, uint amount); event Provide(address indexed account, uint256 amount, uint256 writeAmount); event Withdraw(address indexed account, uint256 amount, uint256 writeAmount); function unlock(uint256 id) external; function setLockupPeriod(uint value) external; function deleteLockedLiquidity(uint id) external; function totalBalance() external view returns (uint256 amount); function setAllowedWHAsset(address _whAsset, bool approved) external; function send(uint256 id, address payable account, uint256 amount, uint payKeep3r) external; } interface IWhiteUSDCPool is ILiquidityPool { function lock(uint id, uint256 amountToLock, uint256 premium) external; function token() external view returns (IERC20); function payKeep3r(address keep3r) external returns (uint amount); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; interface IWhiteOptionsPricer { function getOptionPrice( uint256 period, uint256 amount, uint256 strike ) external view returns (uint256 total); function getAmountToWrapFromTotal(uint total, uint period) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } 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; } pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } 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); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "../WHAssetv2.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @author jmonteer * @title Whiteheart's Hedge Contract (WHETH) * @notice WHAsset implementation. Hedge contract: Wraps an amount of the underlying asset with an ATM put option (or other protection instrument) */ contract WHETHv2 is WHAssetv2 { using SafeERC20 for IERC20; using SafeMath for uint; address public immutable WETH; constructor( IUniswapV2Router02 _swapRouter, IToken _stablecoin, AggregatorV3Interface _priceProvider, IWhiteUSDCPool _pool, IWhiteOptionsPricer _whiteOptionsPricer ) public WHAssetv2(_swapRouter, _stablecoin, IToken(_swapRouter.WETH()), _priceProvider, _pool, _whiteOptionsPricer, "Whiteheart Hedged ETH", "WHETH") { WETH = _swapRouter.WETH(); IERC20(_stablecoin).safeApprove(address(_pool), type(uint256).max); IERC20(_swapRouter.WETH()).safeApprove(address(_swapRouter), type(uint256).max); } receive() payable external {} /** * @notice function to be called by the router after a swap has been completed * @param total principal + hedge cost added amount * @param protectionPeriod seconds of protection * @param to recipient of Hedge Contract (onBehalfOf) * @param mintToken whether to mintToken or not * @return newTokenId new hedge contract id */ function wrapAfterSwap(uint total, uint protectionPeriod, address to, bool mintToken, uint minUSDCPremium) external onlyRouter override returns (uint newTokenId) { uint amountToWrap = whiteOptionsPricer.getAmountToWrapFromTotal(total, protectionPeriod); newTokenId = _wrap(amountToWrap, protectionPeriod, to, false, mintToken, minUSDCPremium); } /** * @notice internal function that supports the receival of principal+hedge cost to be sent * @param from address sender * @param amount principal to receive * @param toUsdc hedgeCost */ function _receiveAsset(address from, uint amount, uint toUsdc) internal override { uint received = msg.value; require(received >= amount.add(toUsdc), "!wrong value"); if(received > amount.add(toUsdc)) payable(from).transfer(received.sub(amount.add(toUsdc))); IWETH(WETH).deposit{value:amount.add(toUsdc)}(); } /** * @notice internal function of support that sends the principal that was protected * @param to receiver of principal * @param amount principal that has been protected */ function _sendTotal(address payable to, uint amount) internal override { IWETH(WETH).withdraw(amount); to.transfer(amount); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "../WHAssetv2.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @author jmonteer * @title Whiteheart's Hedge Contract (Any ERC20) * @notice WHAsset implementation. Hedge contract: Wraps an amount of the underlying asset with an ATM put option (or other protection instrument) */ contract WHERC20v2 is WHAssetv2 { using SafeERC20 for IERC20; using SafeMath for uint; IERC20 public immutable token; constructor( IUniswapV2Router02 _swapRouter, IToken _stablecoin, IToken _token, AggregatorV3Interface _priceProvider, IWhiteUSDCPool _pool, IWhiteOptionsPricer _whiteOptionsPricer, string memory _name, string memory _symbol ) public WHAssetv2(_swapRouter, _stablecoin, _token, _priceProvider, _pool, _whiteOptionsPricer, _name, _symbol) { token = _token; IERC20(_stablecoin).safeApprove(address(_pool), type(uint256).max); IERC20(_token).safeApprove(address(_swapRouter), type(uint256).max); } function wrap(uint128 amount, uint period, address to, bool _mintToken, uint minPremiumUSDC) payable public override returns (uint newTokenId) { require(msg.value == 0, "!eth not accepted"); super.wrap(amount, period, to, _mintToken, minPremiumUSDC); } /** * @notice function to be called by the router after a swap has been completed * @param total principal + hedge cost added amount * @param protectionPeriod seconds of protection * @param to recipient of Hedge Contract (onBehalfOf) * @param mintToken whether to mintToken or not * @return newTokenId new hedge contract id */ function wrapAfterSwap(uint total, uint protectionPeriod, address to, bool mintToken, uint minUSDCPremium) external onlyRouter override returns (uint newTokenId) { uint amountToWrap = whiteOptionsPricer.getAmountToWrapFromTotal(total, protectionPeriod); newTokenId = _wrap(amountToWrap, protectionPeriod, to, false, mintToken, minUSDCPremium); } /** * @notice internal function that supports the receival of principal+hedge cost to be sent * @param from address sender * @param amount principal to receive * @param toUsdc hedgeCost */ function _receiveAsset(address from, uint amount, uint toUsdc) internal override { token.safeTransferFrom(from, address(this), amount.add(toUsdc)); } /** * @notice internal function of support that sends the principal that was protected * @param to receiver of principal * @param amount principal that has been protected */ function _sendTotal(address payable to, uint amount) internal override { token.safeTransfer(to, amount); } } /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2020 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import "../Interfaces/IWhiteStakingERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; pragma solidity 0.6.12; abstract contract WhiteStaking is ERC20, IWhiteStaking { using SafeERC20 for IERC20; using SafeMath for uint; IERC20 public immutable WHITE; uint internal constant ACCURACY = 1e30; address payable public immutable FALLBACK_RECIPIENT; uint public totalProfit = 0; mapping(address => uint) internal lastProfit; mapping(address => uint) internal savedProfit; uint256 public lockupPeriod = 1 days; mapping(address => uint256) public lastStakeTimestamp; mapping(address => bool) public _revertTransfersInLockUpPeriod; constructor(ERC20 _token, string memory name, string memory short) public ERC20(name, short) { WHITE = _token; FALLBACK_RECIPIENT = msg.sender; } function claimProfit() external override returns (uint profit) { profit = saveProfit(msg.sender); require(profit > 0, "Zero profit"); savedProfit[msg.sender] = 0; _transferProfit(profit); emit Claim(msg.sender, profit); } function deposit(uint amount) external override { lastStakeTimestamp[msg.sender] = block.timestamp; require(amount > 0, "!amount"); WHITE.safeTransferFrom(msg.sender, address(this), amount); _mint(msg.sender, amount); } function withdraw(uint amount) external lockupFree override { _burn(msg.sender, amount); WHITE.safeTransfer(msg.sender, amount); } /** * @notice Used for ... */ function revertTransfersInLockUpPeriod(bool value) external { _revertTransfersInLockUpPeriod[msg.sender] = value; } function profitOf(address account) external view override returns (uint) { return savedProfit[account].add(getUnsaved(account)); } function getUnsaved(address account) internal view returns (uint profit) { return totalProfit.sub(lastProfit[account]).mul(balanceOf(account)).div(ACCURACY); } function saveProfit(address account) internal returns (uint profit) { uint unsaved = getUnsaved(account); lastProfit[account] = totalProfit; profit = savedProfit[account].add(unsaved); savedProfit[account] = profit; } function _beforeTokenTransfer(address from, address to, uint256) internal override { if (from != address(0)) saveProfit(from); if (to != address(0)) saveProfit(to); if ( lastStakeTimestamp[from].add(lockupPeriod) > block.timestamp && lastStakeTimestamp[from] > lastStakeTimestamp[to] ) { require( !_revertTransfersInLockUpPeriod[to], "the recipient does not accept blocked funds" ); lastStakeTimestamp[to] = lastStakeTimestamp[from]; } } function _transferProfit(uint amount) internal virtual; modifier lockupFree { require( lastStakeTimestamp[msg.sender].add(lockupPeriod) <= block.timestamp, "Action suspended due to lockup" ); _; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; interface IWhiteStaking { event Claim(address indexed acount, uint amount); event Profit(uint amount); function claimProfit() external returns (uint profit); function deposit(uint amount) external; function withdraw(uint amount) external; function profitOf(address account) external view returns (uint); } interface IWhiteStakingERC20 { function sendProfit(uint amount) external; } /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2020 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import "./WhiteStaking.sol"; pragma solidity 0.6.12; contract WhiteStakingUSDC is WhiteStaking, IWhiteStakingERC20 { using SafeERC20 for IERC20; using SafeMath for uint; IERC20 public immutable USDC; constructor(ERC20 _token, ERC20 usdc) public WhiteStaking(_token, "Staked WHITE", "sWHITE") { USDC = usdc; } function sendProfit(uint amount) external override { uint _totalSupply = totalSupply(); if (_totalSupply > 0) { totalProfit += amount.mul(ACCURACY) / _totalSupply; USDC.safeTransferFrom(msg.sender, address(this), amount); emit Profit(amount); } else { USDC.safeTransferFrom(msg.sender, FALLBACK_RECIPIENT, amount); } } function _transferProfit(uint amount) internal override { USDC.safeTransfer(msg.sender, amount); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract FakeWBTC is ERC20("FakeWBTC", "FAKE") { constructor() public { _setupDecimals(8); } function mintTo(address account, uint256 amount) public { _mint(account, amount); } function mint(uint256 amount) public { _mint(msg.sender, amount); } } contract FakeWHITE is ERC20("FakeWHITE", "FAKEWHITE") { function mintTo(address account, uint256 amount) public { _mint(account, amount); } function mint(uint256 amount) public { _mint(msg.sender, amount); } } contract FakeWETH is ERC20("FakeWETH", "FAKETH") { receive() external payable {} function mintTo(address account, uint256 amount) public { _mint(account, amount); } function mint(uint256 amount) public { _mint(msg.sender, amount); } function deposit() external payable { _mint(msg.sender, msg.value); } function withdraw(uint wad) external { payable(msg.sender).transfer(wad); _burn(msg.sender, wad); } } contract FakeUSDC is ERC20("FakeUSDC", "FAKEU") { using SafeERC20 for ERC20; constructor() public { _setupDecimals(6); } function mintTo(address account, uint256 amount) public { _mint(account, amount); } function mint(uint256 amount) public { _mint(msg.sender, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../Interfaces/Keep3r/ICollectableDust.sol"; abstract contract CollectableDust is ICollectableDust { using EnumerableSet for EnumerableSet.AddressSet; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; EnumerableSet.AddressSet internal protocolTokens; constructor() public {} function _addProtocolToken(address _token) internal { require(!protocolTokens.contains(_token), "collectable-dust::token-is-part-of-the-protocol"); protocolTokens.add(_token); } function _removeProtocolToken(address _token) internal { require(protocolTokens.contains(_token), "collectable-dust::token-not-part-of-the-protocol"); protocolTokens.remove(_token); } function _sendDust( address _to, address _token, uint256 _amount ) internal { require(_to != address(0), "collectable-dust::cant-send-dust-to-zero-address"); require(!protocolTokens.contains(_token), "collectable-dust::token-is-part-of-the-protocol"); if (_token == ETH_ADDRESS) { payable(_to).transfer(_amount); } else { IERC20(_token).transfer(_to, _amount); } emit DustSent(_to, _token, _amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; interface ICollectableDust { event DustSent(address _to, address token, uint256 amount); function sendDust( address _to, address _token, uint256 _amount ) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./Governable.sol"; import "./CollectableDust.sol"; import "../Interfaces/IWHAsset.sol"; import "../Interfaces/Keep3r/IKeep3rV1.sol"; import "../Interfaces/Keep3r/IChainLinkFeed.sol"; import "../Interfaces/Keep3r/IKeep3rV1Helper.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract WhiteKeep3r is Governable, CollectableDust { using Address for address; using SafeMath for uint256; using SafeERC20 for IERC20; IKeep3rV1 public keep3r = IKeep3rV1(0x1cEB5cB57C4D4E2b2433641b95Dd330A33185A44); IChainLinkFeed public immutable ETHUSD = IChainLinkFeed(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); IChainLinkFeed public constant FASTGAS = IChainLinkFeed(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C); uint public constant gasUsed = 100_000; address public job; IERC20 public token; constructor(IERC20 _token) public Governable(msg.sender) CollectableDust() { token = _token; } function unwrapAll(address whAsset, uint[] calldata tokenIds) external paysKeeper(tokenIds) { IWHAssetv2(whAsset).autoUnwrapAll(tokenIds, address(this)); } function refillCredit() external onlyGovernor { uint balance = token.balanceOf(address(this)); keep3r.addCredit(address(token), job, balance); } function _isKeeper() internal { require(tx.origin == msg.sender, "keep3r::isKeeper:keeper-is-a-smart-contract"); require(keep3r.isKeeper(msg.sender), "keep3r::isKeeper:keeper-is-not-registered"); } function getRequestedPayment() public view returns(uint){ uint256 gasPrice = Math.min(tx.gasprice, uint256(FASTGAS.latestAnswer())); return gasPrice.mul(gasUsed).mul(uint(ETHUSD.latestAnswer())).div(1e20); } function getRequestedPaymentETH() public view returns(uint){ uint256 gasPrice = Math.min(tx.gasprice, uint256(FASTGAS.latestAnswer())); return gasPrice.mul(gasUsed); } function setJob(address newJob) external onlyGovernor { job = newJob; } modifier paysKeeper(uint[] calldata tokenIds) { _isKeeper(); _; // function executed by keep3r uint paidReward = tokenIds.length.mul(getRequestedPayment()); keep3r.receipt(address(token), msg.sender, paidReward); } function setKeep3r(address _keep3r) external onlyGovernor { token.safeApprove(address(keep3r), 0); keep3r = IKeep3rV1(_keep3r); token.safeApprove(address(_keep3r), type(uint256).max); } // Governable function setPendingGovernor(address _pendingGovernor) external override onlyGovernor { _setPendingGovernor(_pendingGovernor); } function acceptGovernor() external override onlyPendingGovernor { _acceptGovernor(); } // Collectable Dust function sendDust( address _to, address _token, uint256 _amount ) external override onlyGovernor { _sendDust(_to, _token, _amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../Interfaces/Keep3r/IGovernable.sol"; abstract contract Governable is IGovernable { address public governor; address public pendingGovernor; constructor(address _governor) public { require(_governor != address(0), "governable::governor-should-not-be-zero-address"); governor = _governor; } function _setPendingGovernor(address _pendingGovernor) internal { require(_pendingGovernor != address(0), "governable::pending-governor-should-not-be-zero-address"); pendingGovernor = _pendingGovernor; emit PendingGovernorSet(_pendingGovernor); } function _acceptGovernor() internal { governor = pendingGovernor; pendingGovernor = address(0); emit GovernorAccepted(); } modifier onlyGovernor { require(msg.sender == governor, "governable::only-governor"); _; } modifier onlyPendingGovernor { require(msg.sender == pendingGovernor, "governable::only-pending-governor"); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; interface IKeep3rV1 { function KPRH() external returns (address); function name() external returns (string memory); function isKeeper(address) external returns (bool); function worked(address keeper) external; function workReceipt(address keeper, uint amount) external; function receiptETH(address keeper, uint256 amount) external; function receipt(address credit, address keeper, uint256 amount) external; function addKPRCredit(address job, uint256 amount) external; function addCredit(address asset, address job, uint256 amount) external; function addJob(address job) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; interface IChainLinkFeed { function latestAnswer() external view returns (int256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; interface IKeep3rV1Helper { function quote(uint256) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; interface IGovernable { event PendingGovernorSet(address pendingGovernor); event GovernorAccepted(); function setPendingGovernor(address _pendingGovernor) external; function acceptGovernor() external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "./Interfaces/IWETH.sol"; import "./Interfaces/IWHAsset.sol"; import "./Interfaces/IWHSwapRouter.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@sushiswap/core/contracts/uniswapv2/libraries/TransferHelper.sol"; import "@sushiswap/core/contracts/uniswapv2/libraries/UniswapV2Library.sol"; /** * @author jmonteer * @title Whiteheart's Swap+Wrap router using Uniswap-like DEX * @notice Contract performing a swap and sending the output to the corresponding WHAsset contract for it to be wrapped into a Hedge Contract */ contract WHSwapRouter is IWHSwapRouter, Ownable { address public immutable factory; address public immutable WETH; // Maps the underlying asset to the corresponding Hedge Contracts mapping(address => address) public whAssets; /** * @notice Constructor * @param _factory DEX factory contract * @param _WETH Ether ERC20's token address */ constructor(address _factory, address _WETH) public { factory = _factory; WETH = _WETH; } /** * @notice Adds an entry to the underlyingAsset => WHAsset contract. It can be used to set the underlying asset to 0x0 address * @param token Asset address * @param whAsset WHAsset contract for the underlying asset */ function setWHAsset(address token, address whAsset) external onlyOwner { whAssets[token] = whAsset; } /** * @notice Function used by WHAsset contracts to swap underlying assets into USDC, to buy options. Same function than "original" router's function * @param amountIn amount of the token being swap * @param amountOutMin minimum amount of the asset to be received from the swap * @param path ordered list of assets to be swap from, to * @param to recipient address of the output of the swap * @param deadline maximum timestamp to process the transaction */ function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'insufficient_output_amount'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } /** * @notice Custom function for swapExactTokensForTokens that wraps the output asset into a Hedge Contract (underlying asset + ATM put option) * @param amountIn amount of the token being swap * @param amountOutMin minimum amount of the asset to be received from the swap * @param path ordered list of assets to be swap from, to * @param to recipient address of the output of the swap * @param deadline maximum timestamp to process the transaction * @param protectionPeriod amount of seconds during which the underlying amount is going to be protected * @param mintToken boolean that tells the WHAsset contract whether or not to mint an ERC721 token representing new Hedge Contract */ function swapExactTokensForTokensAndWrap( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint protectionPeriod, bool mintToken, uint minUSDCPremium ) external virtual override ensure(deadline) returns (uint[] memory amounts, uint newTokenId){ amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'insufficient_output_amount'); { address[] calldata _path = path; TransferHelper.safeTransferFrom( _path[0], msg.sender, UniswapV2Library.pairFor(factory, _path[0], _path[1]), amounts[0] ); } newTokenId = _swapAndWrap(path, amounts, protectionPeriod, to, mintToken, minUSDCPremium); } /** * @notice Custom function for swapTokensForExactTokens that wraps the output asset into a Hedge Contract (underlying asset + ATM put option) * @param amountOut exact amount of output asset expected * @param amountInMax maximum amount of tokens to be sent to the DEX * @param path ordered list of assets to be swap from, to * @param to recipient address of the output of the swap * @param deadline maximum timestamp to process the transaction * @param protectionPeriod amount of seconds during which the underlying amount is going to be protected * @param mintToken boolean that tells the WHAsset contract whether or not to mint an ERC721 token representing new Hedge Contract */ function swapTokensForExactTokensAndWrap( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline, uint protectionPeriod, bool mintToken, uint minUSDCPremium ) external virtual override ensure(deadline) returns (uint[] memory amounts, uint newTokenId) { amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'excessive_input_amount'); { address[] calldata _path = path; TransferHelper.safeTransferFrom( _path[0], msg.sender, UniswapV2Library.pairFor(factory, _path[0], _path[1]), amounts[0] ); } newTokenId = _swapAndWrap(path, amounts, protectionPeriod, to, mintToken, minUSDCPremium); } /** * @notice Custom function for swapExactETHForTokens that wraps the output asset into a Hedge Contract (underlying asset + ATM put option) * @param amountOutMin minimum amount of the asset to be received from the swap * @param path ordered list of assets to be swap from, to * @param to recipient address of the output of the swap * @param deadline maximum timestamp to process the transaction * @param protectionPeriod amount of seconds during which the underlying amount is going to be protected * @param mintToken boolean that tells the WHAsset contract whether or not to mint an ERC721 token representing new Hedge Contract */ function swapExactETHForTokensAndWrap(uint amountOutMin, address[] calldata path, address to, uint deadline, uint protectionPeriod, bool mintToken, uint minUSDCPremium) external virtual payable override ensure(deadline) returns (uint[] memory amounts, uint newTokenId) { address[] memory _path = path; // to avoid stack too deep amounts = UniswapV2Library.getAmountsOut(factory, msg.value, _path); require(amounts[amounts.length - 1] >= amountOutMin, 'insufficient_input_amount'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, _path[0], _path[1]), amounts[0])); newTokenId = _swapAndWrap(path, amounts, protectionPeriod, to, mintToken, minUSDCPremium); } /** * @notice Custom function for swapETHForExactTokens that wraps the output asset into a Hedge Contract (underlying asset + ATM put option) * @param amountOut amount of the token being swap * @param path ordered list of assets to be swap from, to * @param to recipient address of the output of the swap * @param deadline maximum timestamp to process the transaction * @param protectionPeriod amount of seconds during which the underlying amount is going to be protected * @param mintToken boolean that tells the WHAsset contract whether or not to mint an ERC721 token representing new Hedge Contract */ function swapETHForExactTokensAndWrap(uint amountOut, address[] calldata path, address to, uint deadline, uint protectionPeriod, bool mintToken, uint minUSDCPremium ) external virtual payable override ensure(deadline) returns (uint[] memory amounts, uint newTokenId) { address[] memory _path = path; // to avoid stack too deep require(_path[0] == WETH, 'invalid_path'); amounts = UniswapV2Library.getAmountsIn(factory, amountOut, _path); require(amounts[0] <= msg.value, 'excessive_input_amount'); IWETH(WETH).deposit{value: amounts[0]}(); { assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, _path[0], _path[1]), amounts[0])); } if(msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); newTokenId = _swapAndWrap(path, amounts, protectionPeriod, to, mintToken, minUSDCPremium); } /** * @notice Custom function for swapExactTokensForETH that wraps the output asset into a Hedge Contract (underlying asset + ATM put option) * @param amountIn amount of the token being swapped * @param amountOutMin minimum amount of the output asset to be received * @param path ordered list of assets to be swap from, to * @param to recipient address of the output of the swap * @param deadline maximum timestamp to process the transaction * @param protectionPeriod amount of seconds during which the underlying amount is going to be protected * @param mintToken boolean that tells the WHAsset contract whether or not to mint an ERC721 token representing new Hedge Contract */ function swapExactTokensForETHAndWrap(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint protectionPeriod, bool mintToken, uint minUSDCPremium) external override ensure(deadline) returns(uint[] memory amounts, uint newTokenId) { require(path[path.length - 1] == WETH, 'invalid_path'); amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, "insufficient_output_amount"); { address[] calldata _path = path; TransferHelper.safeTransferFrom( _path[0], msg.sender, UniswapV2Library.pairFor(factory, _path[0], _path[1]), amounts[0] ); } newTokenId = _swapAndWrap(path, amounts, protectionPeriod, to, mintToken, minUSDCPremium); } /** * @notice Custom function for swapTokensForExactETH that wraps the output asset into a Hedge Contract (underlying asset + ATM put option) * @param amountOut amount of the output asset to be received * @param amountInMax maximum amount of input that user is willing to send to the contract to reach amountOut * @param path ordered list of assets to be swap from, to * @param to recipient address of the output of the swap * @param deadline maximum timestamp to process the transaction * @param protectionPeriod amount of seconds during which the underlying amount is going to be protected * @param mintToken boolean that tells the WHAsset contract whether or not to mint an ERC721 token representing new Hedge Contract */ function swapTokensForExactETHAndWrap(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline, uint protectionPeriod, bool mintToken, uint minUSDCPremium) external override ensure(deadline) returns (uint[] memory amounts, uint newTokenId) { require(path[path.length - 1] == WETH, 'invalid_path'); amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'excessive_input_amount'); { address[] calldata _path = path; TransferHelper.safeTransferFrom( _path[0], msg.sender, UniswapV2Library.pairFor(factory, _path[0], _path[1]), amounts[0] ); } newTokenId = _swapAndWrap(path, amounts, protectionPeriod, to, mintToken, minUSDCPremium); } /** * @notice Internal function to be called after all swap params have been calc'd. it performs a swap and sends output to corresponding WHAsset contract * @param path ordered list of assets to be swap from, to * @param amounts list of amounts to send/receive of each of path's asset * @param protectionPeriod amount of seconds during which the underlying amount is going to be protected * @param mintToken boolean that tells the WHAsset contract whether or not to mint an ERC721 token representing new Hedge Contract */ function _swapAndWrap(address[] calldata path, uint[] memory amounts, uint protectionPeriod, address to, bool mintToken, uint minUSDCPremium) internal returns (uint newTokenId) { address whAsset = whAssets[path[path.length - 1]]; require(whAsset != address(0), 'whAsset_does_not_exist'); _swap(amounts, path, whAsset); newTokenId = IWHAssetv2(whAsset).wrapAfterSwap(amounts[amounts.length - 1], protectionPeriod, to, mintToken, minUSDCPremium); } /** * @notice Internal function to be called for actually swapping the involved assets. requires the initial amount to have already been sent to the first pair * @param amounts list of amounts to send/receive of each of path's asset * @param path ordered list of assets to be swap from, to * @param _to recipient of swap's output */ function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for(uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = UniswapV2Library.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } // **** LIBRARY FUNCTIONS **** // from original Uniswap router function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return UniswapV2Library.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { return UniswapV2Library.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { return UniswapV2Library.getAmountsIn(factory, amountOut, path); } modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'EXPIRED'); _; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; interface IWHSwapRouter { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactTokensForTokensAndWrap( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint protectionPeriod, bool mintToken, uint minUSDCPremium ) external returns (uint[] memory amounts, uint newTokenId); function swapTokensForExactTokensAndWrap( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline, uint protectionPeriod, bool mintToken, uint minUSDCPremium ) external returns (uint[] memory amounts, uint newTokenId); function swapExactETHForTokensAndWrap(uint amountOutMin, address[] calldata path, address to, uint deadline, uint protectionPeriod, bool mintToken, uint minUSDCPremium) external payable returns (uint[] memory amounts, uint newTokenId); function swapETHForExactTokensAndWrap(uint amountOut, address[] calldata path, address to, uint deadline, uint protectionPeriod, bool mintToken, uint minUSDCPremium) external payable returns (uint[] memory amounts, uint newTokenId); function swapExactTokensForETHAndWrap(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint protectionPeriod, bool mintToken, uint minUSDCPremium) external returns(uint[] memory amounts, uint newTokenId); function swapTokensForExactETHAndWrap(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline, uint protectionPeriod, bool mintToken, uint minUSDCPremium) external returns (uint[] memory amounts, uint newTokenId); // **** LIBRARY FUNCTIONS **** 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[] memory path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] memory path) external view returns (uint[] memory amounts); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; import '../interfaces/IUniswapV2Pair.sol'; import "./SafeMath.sol"; library UniswapV2Library { using SafeMathUniswap for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'fa418eb2c6e15c39605695377d0e364aca1c3c56b333eefe9c0d4b707662f785' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: GPL-3.0 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; } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMathUniswap { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; import './libraries/SafeMath.sol'; contract UniswapV2ERC20 { using SafeMathUniswap for uint; string public constant name = 'SushiSwap LP Token'; string public constant symbol = 'SLP'; uint8 public constant decimals = 18; uint public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); constructor() public { uint chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this) ) ); } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, 'UniswapV2: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE'); _approve(owner, spender, value); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; import './UniswapV2ERC20.sol'; import './libraries/Math.sol'; import './libraries/UQ112x112.sol'; import './interfaces/IERC20.sol'; import './interfaces/IUniswapV2Factory.sol'; import './interfaces/IUniswapV2Callee.sol'; interface IMigrator { // Return the desired amount of liquidity token that the migrator wants. function desiredLiquidity() external view returns (uint256); } contract UniswapV2Pair is UniswapV2ERC20 { using SafeMathUniswap for uint; using UQ112x112 for uint224; uint public constant MINIMUM_LIQUIDITY = 10**3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); address public factory; address public token0; address public token1; uint112 private reserve0; // uses single storage slot, accessible via getReserves uint112 private reserve1; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint public price0CumulativeLast; uint public price1CumulativeLast; uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event uint private unlocked = 1; modifier lock() { require(unlocked == 1, 'UniswapV2: LOCKED'); unlocked = 0; _; unlocked = 1; } function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } function _safeTransfer(address token, address to, uint value) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED'); } 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); constructor() public { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address _token0, address _token1) external { require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; } // update reserves and, on the first call per block, price accumulators function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // * never overflows, and + overflow is desired price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); } // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = IUniswapV2Factory(factory).feeTo(); feeOn = feeTo != address(0); uint _kLast = kLast; // gas savings if (feeOn) { if (_kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint numerator = totalSupply.mul(rootK.sub(rootKLast)); uint denominator = rootK.mul(5).add(rootKLast); uint liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (_kLast != 0) { kLast = 0; } } // this low-level function should be called from a contract which performs important safety checks function mint(address to) external lock returns (uint liquidity) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings uint balance0 = IERC20Uniswap(token0).balanceOf(address(this)); uint balance1 = IERC20Uniswap(token1).balanceOf(address(this)); uint amount0 = balance0.sub(_reserve0); uint amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { address migrator = IUniswapV2Factory(factory).migrator(); if (msg.sender == migrator) { liquidity = IMigrator(migrator).desiredLiquidity(); require(liquidity > 0 && liquidity != uint256(-1), "Bad desired liquidity"); } else { require(migrator == address(0), "Must not have migrator"); liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } } else { liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Mint(msg.sender, amount0, amount1); } // this low-level function should be called from a contract which performs important safety checks function burn(address to) external lock returns (uint amount0, uint amount1) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings address _token0 = token0; // gas savings address _token1 = token1; // gas savings uint balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); uint balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); uint liquidity = balanceOf[address(this)]; bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED'); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Burn(msg.sender, amount0, amount1, to); } // this low-level function should be called from a contract which performs important safety checks function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock { require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT'); (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY'); uint balance0; uint balance1; { // scope for _token{0,1}, avoids stack too deep errors address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO'); if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); } uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT'); { // scope for reserve{0,1}Adjusted, avoids stack too deep errors uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K'); } _update(balance0, balance1, _reserve0, _reserve1); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); } // force balances to match reserves function skim(address to) external lock { address _token0 = token0; // gas savings address _token1 = token1; // gas savings _safeTransfer(_token0, to, IERC20Uniswap(_token0).balanceOf(address(this)).sub(reserve0)); _safeTransfer(_token1, to, IERC20Uniswap(_token1).balanceOf(address(this)).sub(reserve1)); } // force reserves to match balances function sync() external lock { _update(IERC20Uniswap(token0).balanceOf(address(this)), IERC20Uniswap(token1).balanceOf(address(this)), reserve0, reserve1); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; // a library for performing various math operations library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IERC20Uniswap { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view 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); } // SPDX-License-Identifier: GPL-3.0 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 migrator() 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; function setMigrator(address) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IUniswapV2Callee { function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@sushiswap/core/contracts/uniswapv2/UniswapV2Pair.sol"; contract SushiSwapPairMock is UniswapV2Pair { constructor() public UniswapV2Pair() { return; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; import './interfaces/IUniswapV2Factory.sol'; import './UniswapV2Pair.sol'; contract UniswapV2Factory is IUniswapV2Factory { address public override feeTo; address public override feeToSetter; address public override migrator; mapping(address => mapping(address => address)) public override getPair; address[] public override allPairs; event PairCreated(address indexed token0, address indexed token1, address pair, uint); constructor(address _feeToSetter) public { feeToSetter = _feeToSetter; } function allPairsLength() external override view returns (uint) { return allPairs.length; } function pairCodeHash() external pure returns (bytes32) { return keccak256(type(UniswapV2Pair).creationCode); } function createPair(address tokenA, address tokenB) external override returns (address pair) { require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS'); require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient bytes memory bytecode = type(UniswapV2Pair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } UniswapV2Pair(pair).initialize(token0, token1); getPair[token0][token1] = pair; getPair[token1][token0] = pair; // populate mapping in the reverse direction allPairs.push(pair); emit PairCreated(token0, token1, pair, allPairs.length); } function setFeeTo(address _feeTo) external override { require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); feeTo = _feeTo; } function setMigrator(address _migrator) external override { require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); migrator = _migrator; } function setFeeToSetter(address _feeToSetter) external override { require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); feeToSetter = _feeToSetter; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; import "@sushiswap/core/contracts/uniswapv2/UniswapV2Factory.sol"; contract SushiSwapFactoryMock is UniswapV2Factory { constructor() public UniswapV2Factory(msg.sender) { return; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "./Interfaces/IWhiteUSDCPool.sol"; import "./Interfaces/IWhiteStakingERC20.sol"; /** * @author jmonteer & 0mllwntrmt3 * @title Whiteheart Stablecoin Liquidity Pool * @notice Accumulates liquidity in USDC from LPs and distributes P&L in USDC */ contract WhiteUSDCPool is IWhiteUSDCPool, Ownable, ERC20("Whiteheart USDC LP Token", "writeUSDC") { using SafeMath for uint256; using SafeERC20 for IERC20; // token that is holded in the pool IERC20 public override immutable token; // address of fee recipient contract IWhiteStakingERC20 public immutable settlementFeeRecipient; address public hegicFeeRecipient; // storage variable to keep uint256 public owedToKeep3r = 0; // amount locked as collateral for open positions uint256 public lockedAmount; // amount of locked premiums uint256 public lockedPremium; // minimum amount of time to pass between last provide timestamp and withdrawal uint256 public lockupPeriod = 2 weeks; uint256 public hegicFee = 0; uint256 public constant INITIAL_RATE = 1e13; // WHAsset contracts allowed to open positions using this pool mapping(address => bool) public whAssets; // Last provided timestamp for this address mapping(address => uint256) public lastProvideTimestamp; // Locked Liquidity mapping per WHAsset (whAsset address => id => LockedLiquidity) mapping(address => mapping(uint => LockedLiquidity)) public lockedLiquidity; // Whether or not the tranfers of Locked funds are allowed mapping(address => bool) public _revertTransfersInLockUpPeriod; /** * @param _token USDC address * @param _settlementFeeRecipient Address of contract that will receive the fees */ constructor(IERC20 _token, IWhiteStakingERC20 _settlementFeeRecipient) public { token = _token; settlementFeeRecipient = _settlementFeeRecipient; hegicFeeRecipient = msg.sender; IERC20(_token).safeApprove(address(_settlementFeeRecipient), type(uint256).max); } modifier onlyWHAssets { require(whAssets[msg.sender], "whiteheart::pool::not-allowed"); _; } /** * @notice Used for changing the lockup period * @param value New period value */ function setLockupPeriod(uint256 value) external override onlyOwner { require(value <= 60 days, "Lockup period is too large"); lockupPeriod = value; } /** * @notice Used for changing the Hegic fee recipient * @param value New value */ function setHegicFeeRecipient(address value) external onlyOwner { require(value != address(0)); hegicFeeRecipient = value; } /** * @notice Used for withdrawing the Hegic fee */ function withdrawHegicFee() external { token.safeTransfer(hegicFeeRecipient, hegicFee); hegicFee = 0; } /** * @notice Allows new smart contract to open positions using USDC pools * @param _whAsset whAsset address * @param approved set to true for approval, set to false for rejecting previously granted access */ function setAllowedWHAsset(address _whAsset, bool approved) external override onlyOwner { whAssets[_whAsset] = approved; } /** * @notice Lets each user to decide whether or not they want to allow incoming transfers of locked funds * @param value bool option. true if the transfer should be reverted, false if it shouldnt */ function revertTransfersInLockUpPeriod(bool value) external { _revertTransfersInLockUpPeriod[msg.sender] = value; } /** * @notice called by WHAsset contract to lock funds and premium (when opening a position) * @param id Id of the Hedge Contract that is being opened * @param amountToLock Amount of funds that should be locked in an option * @param totalFee premium paid for the protection. It will be locked until funds are unlocked */ function lock(uint id, uint256 amountToLock, uint256 totalFee) external override onlyWHAssets { address creator = msg.sender; require( lockedAmount.add(amountToLock).mul(10) <= totalBalance().mul(8), "Pool Error: Amount is too large." ); uint256 premium = totalFee.mul(30).div(100); uint256 settlementFee = totalFee.mul(30).div(100); uint256 hegicFeeAmount = totalFee.sub(premium).sub(settlementFee); lockedLiquidity[creator][id] = (LockedLiquidity(uint120(amountToLock), uint120(premium), true)); lockedPremium = lockedPremium.add(premium); lockedAmount = lockedAmount.add(amountToLock); settlementFeeRecipient.sendProfit(settlementFee); hegicFee = hegicFee.add(hegicFeeAmount); } /** * @notice calls by WHAsset contract to unlock funds and premium (when closing a position, either exercising or unlocking funds) * @param id Id of the Hedge Contract that is being opened */ function unlock(uint256 id) external override { LockedLiquidity storage ll = lockedLiquidity[msg.sender][id]; require(ll.locked, "LockedLiquidity with such id has already unlocked"); ll.locked = false; lockedPremium = lockedPremium.sub(ll.premium); lockedAmount = lockedAmount.sub(ll.amount); emit Profit(id, ll.premium); } /** * @notice Function that can only be called by WHAsset contracts to retrieve funds owed to a keep3r * @param keep3r address of the function to receive accumulated rewards */ function payKeep3r(address keep3r) external onlyWHAssets override returns (uint amount) { amount = owedToKeep3r; owedToKeep3r = 0; if(amount > 0) token.safeTransfer(keep3r, amount); } /** * @notice function that pays profit (if any) to the hedge contract holder and unlocks premium and liquidity * @param id Id of the Hedge Contract that is being closed * @param to address to receive profit * @param amount profit to be sent * @param _payKeep3r amount to be saved for the keep3r unwrapping the asset */ function send(uint id, address payable to, uint256 amount, uint _payKeep3r) external override { LockedLiquidity storage ll = lockedLiquidity[msg.sender][id]; require(ll.locked, "LockedLiquidity with such id has already unlocked"); require(to != address(0)); ll.locked = false; lockedPremium = lockedPremium.sub(ll.premium); lockedAmount = lockedAmount.sub(ll.amount); uint transferAmount = amount > ll.amount ? ll.amount : amount; token.safeTransfer(to, transferAmount.sub(_payKeep3r)); if(_payKeep3r > 0) owedToKeep3r = owedToKeep3r.add(_payKeep3r); if (transferAmount <= ll.premium) emit Profit(id, ll.premium - transferAmount); else emit Loss(id, transferAmount - ll.premium); } /** * @notice deletes locked liquidity, receiving a gas refund. used to reduce gas usage * @param id Id of the Hedge Contract that is being closed */ function deleteLockedLiquidity(uint id) external override { delete lockedLiquidity[msg.sender][id]; } /** * @notice A provider supplies USDC to the pool and receives writeUSDC tokens * @param amount Amount to send to the contract * @param minMint minimum amount of writeUSDC tokens to be minted * @return mint amount of writeUSDC minted to provider */ function provide(uint256 amount, uint256 minMint) external returns (uint256 mint) { lastProvideTimestamp[msg.sender] = block.timestamp; uint supply = totalSupply(); uint balance = totalBalance(); if (supply > 0 && balance > 0) mint = amount.mul(supply).div(balance); else mint = amount.mul(INITIAL_RATE); require(mint >= minMint, "Pool: Mint limit is too large"); require(mint > 0, "Pool: Amount is too small"); _mint(msg.sender, mint); emit Provide(msg.sender, amount, mint); token.safeTransferFrom(msg.sender, address(this), amount); } /** * @notice A provider supplies writeUSDC to the pool and receives USDC tokens * @param amount Amount to withdraw from the pool * @param maxBurn maximum amount of writeUSDC to be burned in exchange * @return burn amount of writeUSDC burnt from provider */ function withdraw(uint256 amount, uint256 maxBurn) external returns (uint256 burn) { require( lastProvideTimestamp[msg.sender].add(lockupPeriod) <= block.timestamp, "Pool: Withdrawal is locked up" ); require( amount <= availableBalance(), "Pool Error: You are trying to unlock more funds than have been locked for your contract. Please lower the amount." ); burn = divCeil(amount.mul(totalSupply()), totalBalance()); require(burn <= maxBurn, "Pool: Burn limit is too small"); require(burn <= balanceOf(msg.sender), "Pool: Amount is too large"); require(burn > 0, "Pool: Amount is too small"); _burn(msg.sender, burn); emit Withdraw(msg.sender, amount, burn); token.safeTransfer(msg.sender, amount); } /** * @notice Returns provider's share in USDC * @param user Provider's address * @return share Provider's share in USDC */ function shareOf(address user) external view returns (uint256 share) { uint supply = totalSupply(); if (supply > 0) share = totalBalance().mul(balanceOf(user)).div(supply); else share = 0; } /** * @notice Returns the amount of USDC available for withdrawals * @return balance Unlocked amount */ function availableBalance() public view returns (uint256 balance) { return totalBalance().sub(lockedAmount); } /** * @notice Returns the USDC total balance provided to the pool * @return balance Pool balance */ function totalBalance() public override view returns (uint256 balance) { return token.balanceOf(address(this)).sub(lockedPremium).sub(hegicFee); } /** * @notice Internal function that checks if to be transferred tokens are locked and act accordingly * @param from sender * @param to recipient */ function _beforeTokenTransfer(address from, address to, uint256) internal override { if ( lastProvideTimestamp[from].add(lockupPeriod) > block.timestamp && lastProvideTimestamp[from] > lastProvideTimestamp[to] ) { require( !_revertTransfersInLockUpPeriod[to], "the recipient does not accept blocked funds" ); lastProvideTimestamp[to] = lastProvideTimestamp[from]; } } // support function that divides and chooses result's ceil function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; if (a % b != 0) c = c + 1; return c; } } // SPDX-License-Identifier: GPL-3.0 import "./Interfaces/IWhiteOptionsPricer.sol"; pragma solidity 0.6.12; /** * @author jmonteer & 0mllwntrmt3 * @title Whiteheart Options Pricer: Separate module to price protection of WHAssets * @notice Support contract that provides prices for certain protection periods, strikes and amounts */ contract WhiteOptionsPricer is IWhiteOptionsPricer, Ownable { using SafeMath for uint; uint256 public impliedVolRate; uint256 internal constant PRICE_DECIMALS = 1e8; AggregatorV3Interface public underlyingPriceProvider; constructor(AggregatorV3Interface _priceProvider) public { underlyingPriceProvider = _priceProvider; impliedVolRate = 5500; } /** * @notice Used for adjusting the options prices while balancing asset's implied volatility rate * @param value New IVRate value */ function setImpliedVolRate(uint256 value) external onlyOwner { require(value >= 1000, "ImpliedVolRate limit is too small"); impliedVolRate = value; } /** * @notice Returns the price that opening a certain option should cost * @param period period of protection * @param amount amount of underlying asset to be protected * @return total totalfee */ function getOptionPrice( uint256 period, uint256 amount, uint256 ) external override view returns (uint256 total) { require(period <= 4 weeks, "!period: too long"); require(period >= 1 days, "!period: too short"); return amount .mul(sqrt(period)) .mul(impliedVolRate) .div(PRICE_DECIMALS); } /** * @notice Returns the amount of WHAsset that is going to be created when provided with the total * amount of underlying asset sent (some goes to protecting the asset, some to the principal being protected) * @param total principal + hedgecost * @param period period of protection * @return maximum amount to be wrapped */ function getAmountToWrapFromTotal(uint total, uint period) external view override returns (uint){ uint numerator = total.mul(PRICE_DECIMALS).mul(10000); uint denominator = PRICE_DECIMALS.add(sqrt(period).mul(impliedVolRate)); return numerator.div(denominator).div(10000); } /** * @dev Counts square root of the number. * Throws "invalid opcode" at uint(-1) */ function sqrt(uint256 x) internal pure returns (uint256 result) { result = x; uint256 k = (x + 1) >> 1; while (k < result) (result, k) = (k, (x / k + k) >> 1); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; contract FakePriceProvider is AggregatorV3Interface { uint256 public price; uint8 public override decimals = 8; string public override description = "Test implementation"; uint256 public override version = 0; constructor(uint256 _price) public { price = _price; } function setPrice(uint256 _price) external { price = _price; } function getRoundData(uint80) external override view returns (uint80, int256, uint256, uint256, uint80) { revert("Test implementation"); } function latestAnswer() external view returns(int result) { (, result, , , ) = latestRoundData(); } function latestRoundData() public override view returns ( uint80, int256 answer, uint256, uint256, uint80 ) { answer = int(price); } }
* @notice Sets swap router to swap underlying into USDC to pay for the protection @param newRouter address of swapRouter contract/
function setRouter(address newRouter) external onlyOwner { router = newRouter; }
5,416,082
[ 1, 2785, 7720, 4633, 358, 7720, 6808, 1368, 11836, 5528, 358, 8843, 364, 326, 17862, 225, 394, 8259, 1758, 434, 7720, 8259, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 8259, 12, 2867, 394, 8259, 13, 3903, 1338, 5541, 288, 203, 3639, 4633, 273, 394, 8259, 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 ]
// Сочетаемость глаголов (и отглагольных частей речи) с предложным // паттерном. // 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,752
[ 1, 145, 128, 145, 127, 145, 125, 145, 118, 146, 228, 146, 229, 145, 121, 146, 229, 146, 239, 146, 228, 146, 242, 225, 145, 115, 225, 145, 125, 145, 118, 146, 235, 145, 123, 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, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 436, 407, 67, 502, 2038, 30, 145, 128, 145, 127, 145, 125, 145, 118, 146, 228, 146, 229, 145, 121, 146, 229, 146, 239, 146, 228, 146, 242, 2916, 16, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.12; // SPDX-License-Identifier: BSD-3-Clause //BSD Zero Clause License: "SPDX-License-Identifier: <SPDX-License>" /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } /** * @title 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 admin; 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 { admin = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == admin); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(admin, newOwner); admin = newOwner; } } interface Token { function transferFrom(address, address, uint) external returns (bool); function transfer(address, uint) external returns (bool); } contract VAPEPOOL1 is Ownable { using SafeMath for uint; using EnumerableSet for EnumerableSet.AddressSet; event RewardsTransferred(address holder, uint amount); //token contract addresses address public VAPEAddress; // reward rate % per year uint public rewardRate = 36000; uint public rewardInterval = 365 days; //farming fee in percentage uint public farmingFeeRate = 0; //unfarming fee in percentage uint public unfarmingFeeRate = 0; //unfarming possible Time uint public PossibleUnfarmTime = 48 hours; uint public totalClaimedRewards = 0; uint private ToBeFarmedTokens; bool public farmingStatus = false; EnumerableSet.AddressSet private holders; mapping (address => uint) public depositedTokens; mapping (address => uint) public farmingTime; mapping (address => uint) public lastClaimedTime; mapping (address => uint) public totalEarnedTokens; /*=============================ADMINISTRATIVE FUNCTIONS ==================================*/ function setTokenAddresses(address _tokenAddr) public onlyOwner returns(bool){ require(_tokenAddr != address(0), "Invalid address format is not supported"); VAPEAddress = _tokenAddr; } function farmingFeeRateSet(uint _farmingFeeRate, uint _unfarmingFeeRate) public onlyOwner returns(bool){ farmingFeeRate = _farmingFeeRate; unfarmingFeeRate = _unfarmingFeeRate; } function rewardRateSet(uint _rewardRate) public onlyOwner returns(bool){ rewardRate = _rewardRate; } function StakingReturnsAmountSet(uint _poolreward) public onlyOwner returns(bool){ ToBeFarmedTokens = _poolreward; } function possibleUnfarmTimeSet(uint _possibleUnfarmTime) public onlyOwner returns(bool){ PossibleUnfarmTime = _possibleUnfarmTime; } function rewardIntervalSet(uint _rewardInterval) public onlyOwner returns(bool){ rewardInterval = _rewardInterval; } function allowFarming(bool _status) public onlyOwner returns(bool){ require(VAPEAddress != address(0), "Interracting token addresses are not yet configured"); farmingStatus = _status; } function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner { if (_tokenAddr == VAPEAddress) { if (_amount > getFundedTokens()) { revert(); } totalClaimedRewards = totalClaimedRewards.add(_amount); } Token(_tokenAddr).transfer(_to, _amount); } function updateAccount(address account) private { uint unclaimedDivs = getUnclaimedDivs(account); if (unclaimedDivs > 0) { require(Token(VAPEAddress).transfer(account, unclaimedDivs), "Could not transfer tokens."); totalEarnedTokens[account] = totalEarnedTokens[account].add(unclaimedDivs); totalClaimedRewards = totalClaimedRewards.add(unclaimedDivs); emit RewardsTransferred(account, unclaimedDivs); } lastClaimedTime[account] = now; } function getUnclaimedDivs(address _holder) public view returns (uint) { if (!holders.contains(_holder)) return 0; if (depositedTokens[_holder] == 0) return 0; uint timeDiff = now.sub(lastClaimedTime[_holder]); uint stakedAmount = depositedTokens[_holder]; uint unclaimedDivs = stakedAmount .mul(rewardRate) .mul(timeDiff) .div(rewardInterval) .div(1e4); return unclaimedDivs; } function getNumberOfHolders() public view returns (uint) { return holders.length(); } function farm(uint amountToFarm) public { require(farmingStatus == true, "Staking is not yet initialized"); require(amountToFarm > 0, "Cannot deposit 0 Tokens"); require(Token(VAPEAddress).transferFrom(msg.sender, address(this), amountToFarm), "Insufficient Token Allowance"); updateAccount(msg.sender); uint fee = amountToFarm.mul(farmingFeeRate).div(1e4); uint amountAfterFee = amountToFarm.sub(fee); require(Token(VAPEAddress).transfer(admin, fee), "Could not transfer deposit fee."); depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee); if (!holders.contains(msg.sender)) { holders.add(msg.sender); farmingTime[msg.sender] = now; } } function unfarm(uint amountToWithdraw) public { require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); require(now.sub(farmingTime[msg.sender]) > PossibleUnfarmTime, "You have not staked for a while yet, kindly wait a bit more"); updateAccount(msg.sender); uint fee = amountToWithdraw.mul(unfarmingFeeRate).div(1e4); uint amountAfterFee = amountToWithdraw.sub(fee); require(Token(VAPEAddress).transfer(admin, fee), "Could not transfer withdraw fee."); require(Token(VAPEAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens."); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } function claimRewards() public { updateAccount(msg.sender); } function getFundedTokens() public view returns (uint) { if (totalClaimedRewards >= ToBeFarmedTokens) { return 0; } uint remaining = ToBeFarmedTokens.sub(totalClaimedRewards); return remaining; } }
token contract addresses reward rate % per yearfarming fee in percentageunfarming fee in percentageunfarming possible Time
contract VAPEPOOL1 is Ownable { using SafeMath for uint; using EnumerableSet for EnumerableSet.AddressSet; event RewardsTransferred(address holder, uint amount); address public VAPEAddress; uint public rewardRate = 36000; uint public rewardInterval = 365 days; uint public farmingFeeRate = 0; uint public unfarmingFeeRate = 0; uint public PossibleUnfarmTime = 48 hours; uint public totalClaimedRewards = 0; uint private ToBeFarmedTokens; bool public farmingStatus = false; EnumerableSet.AddressSet private holders; mapping (address => uint) public depositedTokens; mapping (address => uint) public farmingTime; mapping (address => uint) public lastClaimedTime; mapping (address => uint) public totalEarnedTokens; function setTokenAddresses(address _tokenAddr) public onlyOwner returns(bool){ require(_tokenAddr != address(0), "Invalid address format is not supported"); VAPEAddress = _tokenAddr; } function farmingFeeRateSet(uint _farmingFeeRate, uint _unfarmingFeeRate) public onlyOwner returns(bool){ farmingFeeRate = _farmingFeeRate; unfarmingFeeRate = _unfarmingFeeRate; } function rewardRateSet(uint _rewardRate) public onlyOwner returns(bool){ rewardRate = _rewardRate; } function StakingReturnsAmountSet(uint _poolreward) public onlyOwner returns(bool){ ToBeFarmedTokens = _poolreward; } function possibleUnfarmTimeSet(uint _possibleUnfarmTime) public onlyOwner returns(bool){ PossibleUnfarmTime = _possibleUnfarmTime; } function rewardIntervalSet(uint _rewardInterval) public onlyOwner returns(bool){ rewardInterval = _rewardInterval; } function allowFarming(bool _status) public onlyOwner returns(bool){ require(VAPEAddress != address(0), "Interracting token addresses are not yet configured"); farmingStatus = _status; } function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner { if (_tokenAddr == VAPEAddress) { if (_amount > getFundedTokens()) { revert(); } totalClaimedRewards = totalClaimedRewards.add(_amount); } Token(_tokenAddr).transfer(_to, _amount); } function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner { if (_tokenAddr == VAPEAddress) { if (_amount > getFundedTokens()) { revert(); } totalClaimedRewards = totalClaimedRewards.add(_amount); } Token(_tokenAddr).transfer(_to, _amount); } function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner { if (_tokenAddr == VAPEAddress) { if (_amount > getFundedTokens()) { revert(); } totalClaimedRewards = totalClaimedRewards.add(_amount); } Token(_tokenAddr).transfer(_to, _amount); } function updateAccount(address account) private { uint unclaimedDivs = getUnclaimedDivs(account); if (unclaimedDivs > 0) { require(Token(VAPEAddress).transfer(account, unclaimedDivs), "Could not transfer tokens."); totalEarnedTokens[account] = totalEarnedTokens[account].add(unclaimedDivs); totalClaimedRewards = totalClaimedRewards.add(unclaimedDivs); emit RewardsTransferred(account, unclaimedDivs); } lastClaimedTime[account] = now; } function updateAccount(address account) private { uint unclaimedDivs = getUnclaimedDivs(account); if (unclaimedDivs > 0) { require(Token(VAPEAddress).transfer(account, unclaimedDivs), "Could not transfer tokens."); totalEarnedTokens[account] = totalEarnedTokens[account].add(unclaimedDivs); totalClaimedRewards = totalClaimedRewards.add(unclaimedDivs); emit RewardsTransferred(account, unclaimedDivs); } lastClaimedTime[account] = now; } function getUnclaimedDivs(address _holder) public view returns (uint) { if (!holders.contains(_holder)) return 0; if (depositedTokens[_holder] == 0) return 0; uint timeDiff = now.sub(lastClaimedTime[_holder]); uint stakedAmount = depositedTokens[_holder]; uint unclaimedDivs = stakedAmount .mul(rewardRate) .mul(timeDiff) .div(rewardInterval) .div(1e4); return unclaimedDivs; } function getNumberOfHolders() public view returns (uint) { return holders.length(); } function farm(uint amountToFarm) public { require(farmingStatus == true, "Staking is not yet initialized"); require(amountToFarm > 0, "Cannot deposit 0 Tokens"); require(Token(VAPEAddress).transferFrom(msg.sender, address(this), amountToFarm), "Insufficient Token Allowance"); updateAccount(msg.sender); uint fee = amountToFarm.mul(farmingFeeRate).div(1e4); uint amountAfterFee = amountToFarm.sub(fee); require(Token(VAPEAddress).transfer(admin, fee), "Could not transfer deposit fee."); depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee); if (!holders.contains(msg.sender)) { holders.add(msg.sender); farmingTime[msg.sender] = now; } } function farm(uint amountToFarm) public { require(farmingStatus == true, "Staking is not yet initialized"); require(amountToFarm > 0, "Cannot deposit 0 Tokens"); require(Token(VAPEAddress).transferFrom(msg.sender, address(this), amountToFarm), "Insufficient Token Allowance"); updateAccount(msg.sender); uint fee = amountToFarm.mul(farmingFeeRate).div(1e4); uint amountAfterFee = amountToFarm.sub(fee); require(Token(VAPEAddress).transfer(admin, fee), "Could not transfer deposit fee."); depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee); if (!holders.contains(msg.sender)) { holders.add(msg.sender); farmingTime[msg.sender] = now; } } function unfarm(uint amountToWithdraw) public { require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); require(now.sub(farmingTime[msg.sender]) > PossibleUnfarmTime, "You have not staked for a while yet, kindly wait a bit more"); updateAccount(msg.sender); uint fee = amountToWithdraw.mul(unfarmingFeeRate).div(1e4); uint amountAfterFee = amountToWithdraw.sub(fee); require(Token(VAPEAddress).transfer(admin, fee), "Could not transfer withdraw fee."); require(Token(VAPEAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens."); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } function unfarm(uint amountToWithdraw) public { require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); require(now.sub(farmingTime[msg.sender]) > PossibleUnfarmTime, "You have not staked for a while yet, kindly wait a bit more"); updateAccount(msg.sender); uint fee = amountToWithdraw.mul(unfarmingFeeRate).div(1e4); uint amountAfterFee = amountToWithdraw.sub(fee); require(Token(VAPEAddress).transfer(admin, fee), "Could not transfer withdraw fee."); require(Token(VAPEAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens."); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } function claimRewards() public { updateAccount(msg.sender); } function getFundedTokens() public view returns (uint) { if (totalClaimedRewards >= ToBeFarmedTokens) { return 0; } uint remaining = ToBeFarmedTokens.sub(totalClaimedRewards); return remaining; } function getFundedTokens() public view returns (uint) { if (totalClaimedRewards >= ToBeFarmedTokens) { return 0; } uint remaining = ToBeFarmedTokens.sub(totalClaimedRewards); return remaining; } }
369,330
[ 1, 2316, 6835, 6138, 19890, 4993, 738, 1534, 3286, 74, 4610, 310, 14036, 316, 11622, 318, 74, 4610, 310, 14036, 316, 11622, 318, 74, 4610, 310, 3323, 2647, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 776, 37, 1423, 20339, 21, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 203, 377, 203, 565, 871, 534, 359, 14727, 1429, 4193, 12, 2867, 10438, 16, 2254, 3844, 1769, 203, 377, 203, 565, 1758, 1071, 776, 37, 1423, 1887, 31, 203, 377, 203, 565, 2254, 1071, 19890, 4727, 273, 6580, 3784, 31, 203, 565, 2254, 1071, 19890, 4006, 273, 21382, 4681, 31, 203, 377, 203, 565, 2254, 1071, 284, 4610, 310, 14667, 4727, 273, 374, 31, 203, 377, 203, 565, 2254, 1071, 640, 74, 4610, 310, 14667, 4727, 273, 374, 31, 203, 377, 203, 565, 2254, 1071, 25433, 984, 74, 4610, 950, 273, 9934, 7507, 31, 203, 377, 203, 565, 2254, 1071, 2078, 9762, 329, 17631, 14727, 273, 374, 31, 203, 565, 2254, 3238, 2974, 1919, 17393, 2937, 5157, 31, 203, 377, 203, 377, 203, 565, 1426, 1071, 284, 4610, 310, 1482, 273, 629, 31, 203, 377, 203, 565, 6057, 25121, 694, 18, 1887, 694, 3238, 366, 4665, 31, 203, 377, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 443, 1724, 329, 5157, 31, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 284, 4610, 310, 950, 31, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 1142, 9762, 329, 950, 31, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 2078, 41, 1303, 329, 5157, 31, 203, 377, 203, 203, 565, 445, 22629, 7148, 12, 2867, 389, 2316, 3178, 13, 1071, 1338, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "hardhat/console.sol"; import "../utils/AdminRole.sol"; import "./IFight.sol"; import "./IRandom.sol"; import "./NFT.sol"; contract GameFight is IFight, AdminRole { uint256 constant DECIMALS = 10**18; uint256 constant REWARD_RATIO = 1 * DECIMALS; mapping(uint256 => FightItem) public fightMap; // tokenId => fight item struct FightItem { uint256 time; // last fight time uint8 num; // number of fight quote } struct Monster { uint8 level; uint256 winRate; uint256 rewardRatio; uint256 lowExp; uint256 highExp; } Monster[] public monsters; NFT public nft; IManager public manager; IRandom public rand; constructor( NFT _nft, IManager _manager, IRandom _rand ) { nft = _nft; manager = _manager; rand = _rand; addMonster(1, 80, REWARD_RATIO, 5, 15); addMonster(2, 70, REWARD_RATIO, 15, 30); addMonster(3, 60, REWARD_RATIO, 30, 60); addMonster(4, 20, REWARD_RATIO, 60, 120); } function migrate( NFT _nft, IManager _manager, IRandom _rand ) external onlyOwner { nft = _nft; manager = _manager; rand = _rand; } modifier onlyBattlefield() { require(manager.battlefields(msg.sender), "require Battlefield."); _; } function addMonster( uint8 _level, uint256 _winRate, uint256 _rewardRatio, uint256 _lowExp, uint256 _highExp ) public onlyOwner { require(_highExp > _lowExp, "wrong exp"); monsters.push(Monster({ level: _level, winRate: _winRate, rewardRatio: _rewardRatio, lowExp: _lowExp, highExp: _highExp })); } function updateMonster( uint256 _monsterId, uint8 _level, uint256 _winRate, uint256 _rewardRatio, uint256 _lowExp, uint256 _highExp ) public onlyOwner { require(_monsterId < monsters.length, "wrong monster id"); require(_highExp > _lowExp, "wrong exp"); Monster storage _monster = monsters[_monsterId]; _monster.level = _level; _monster.winRate = _winRate; _monster.rewardRatio = _rewardRatio; _monster.lowExp = _lowExp; _monster.highExp = _highExp; } function getMonster(uint256 _monsterId) public view returns (Monster memory) { return monsters[_monsterId]; } function getRewardRatio(uint256 _monsterId) external view override returns (uint256) { return monsters[_monsterId].rewardRatio; } function fightMonster(uint256 _tokenId, uint256 _monsterId) external override onlyBattlefield returns (uint256) { uint8 _rare = nft.rare(_tokenId); require(_rare > 0, "wrong nft id"); require(_monsterId < monsters.length, "wrong monster id"); uint256 remainingFightNum = getRemainingFightNum(_tokenId); require(remainingFightNum > 0, "wait for next fight interval"); // uint256 quote = getFightQuoteNum(_tokenId); FightItem storage fightItem = fightMap[_tokenId]; if (remainingFightNum == 1) { // last fight, setup next fight interval, reset the fight num fightItem.time = block.timestamp; fightItem.num = 0; } // if (fightItem.num >= quote) { // // new fight interval, reset the fight num // fightItem.time = block.timestamp; // fightItem.num = 0; // } fightItem.num += 1; Monster memory _monster = monsters[_monsterId]; uint256 _fightRatio = rand.generate(_tokenId + _monsterId) % 100; console.log("fightRatio: %s", _fightRatio); if (_fightRatio > _monster.winRate) { // lose! as the fight ratio is out of win% return 0; } // calculate exp return _monster.lowExp + (_fightRatio * (_monster.highExp - _monster.lowExp)) / _monster.winRate; } function getRemainingFightNum(uint256 _tokenId) public view returns (uint256) { uint8 _rare = nft.rare(_tokenId); require(_rare > 0, "wrong nft id"); uint256 lastFightTime = getLastFightTime(_tokenId); if (lastFightTime >= block.timestamp) { return 0; } uint256 interval = (block.timestamp - lastFightTime) / manager.fightTimeInterval(); if (interval == 0) { return 0; } FightItem memory fightItem = fightMap[_tokenId]; uint256 quote = getFightQuoteNum(_tokenId); return (fightItem.num < quote ? quote - fightItem.num : quote); } function getFightQuoteNum(uint256 _tokenId) public view returns (uint256) { uint8 _rare = nft.rare(_tokenId); require(_rare > 0, "wrong nft id"); uint256 lastFightTime = getLastFightTime(_tokenId); uint256 interval = (block.timestamp - lastFightTime) / manager.fightTimeInterval(); uint256 quote = interval <= 1 ? _rare : _rare * interval; uint256 maxFightNum = getMaxFightNum(_rare); return quote > maxFightNum ? maxFightNum : quote; } function getMaxFightNum(uint256 _rare) public pure returns (uint256) { return _rare * 2; } function getLastFightTime(uint256 _tokenId) public view returns (uint256) { FightItem memory fightItem = fightMap[_tokenId]; // once born, it can fight return (fightItem.time > 0 ? fightItem.time : nft.bornTime(_tokenId) - manager.fightTimeInterval()); } }
uint256 quote = getFightQuoteNum(_tokenId); last fight, setup next fight interval, reset the fight num lose! as the fight ratio is out of win%
function fightMonster(uint256 _tokenId, uint256 _monsterId) external override onlyBattlefield returns (uint256) { uint8 _rare = nft.rare(_tokenId); require(_rare > 0, "wrong nft id"); require(_monsterId < monsters.length, "wrong monster id"); uint256 remainingFightNum = getRemainingFightNum(_tokenId); require(remainingFightNum > 0, "wait for next fight interval"); FightItem storage fightItem = fightMap[_tokenId]; if (remainingFightNum == 1) { fightItem.time = block.timestamp; fightItem.num = 0; } fightItem.num += 1; Monster memory _monster = monsters[_monsterId]; uint256 _fightRatio = rand.generate(_tokenId + _monsterId) % 100; console.log("fightRatio: %s", _fightRatio); if (_fightRatio > _monster.winRate) { return 0; } }
12,816,736
[ 1, 11890, 5034, 3862, 273, 2812, 750, 10257, 2578, 24899, 2316, 548, 1769, 1142, 284, 750, 16, 3875, 1024, 284, 750, 3673, 16, 2715, 326, 284, 750, 818, 29612, 5, 487, 326, 284, 750, 7169, 353, 596, 434, 5657, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 284, 750, 11415, 8190, 12, 11890, 5034, 389, 2316, 548, 16, 2254, 5034, 389, 2586, 8190, 548, 13, 3903, 3849, 1338, 38, 4558, 298, 1518, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 28, 389, 354, 266, 273, 290, 1222, 18, 354, 266, 24899, 2316, 548, 1769, 203, 3639, 2583, 24899, 354, 266, 405, 374, 16, 315, 21530, 290, 1222, 612, 8863, 203, 3639, 2583, 24899, 2586, 8190, 548, 411, 6921, 334, 414, 18, 2469, 16, 315, 21530, 6921, 8190, 612, 8863, 203, 203, 3639, 2254, 5034, 4463, 42, 750, 2578, 273, 336, 11429, 42, 750, 2578, 24899, 2316, 548, 1769, 203, 3639, 2583, 12, 17956, 42, 750, 2578, 405, 374, 16, 315, 7048, 364, 1024, 284, 750, 3673, 8863, 203, 203, 203, 3639, 478, 750, 1180, 2502, 284, 750, 1180, 273, 284, 750, 863, 63, 67, 2316, 548, 15533, 203, 3639, 309, 261, 17956, 42, 750, 2578, 422, 404, 13, 288, 203, 5411, 284, 750, 1180, 18, 957, 273, 1203, 18, 5508, 31, 203, 5411, 284, 750, 1180, 18, 2107, 273, 374, 31, 203, 3639, 289, 203, 203, 3639, 284, 750, 1180, 18, 2107, 1011, 404, 31, 203, 3639, 9041, 8190, 3778, 389, 2586, 8190, 273, 6921, 334, 414, 63, 67, 2586, 8190, 548, 15533, 203, 3639, 2254, 5034, 389, 470, 647, 8541, 273, 5605, 18, 7163, 24899, 2316, 548, 397, 389, 2586, 8190, 548, 13, 738, 2130, 31, 203, 203, 3639, 2983, 18, 1330, 2932, 470, 647, 8541, 30, 738, 87, 3113, 389, 470, 647, 8541, 1769, 203, 203, 2 ]
./partial_match/4/0x91b9dBc41850963CD5195e937f6E924f288B2980/sources/RoseToken.sol
Update the given pool's ROSE allocation point. Can only be called by the owner.
function set2( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePool2s(); } allocPointPool2 = allocPointPool2.sub(poolInfo2[_pid].allocPoint).add( _allocPoint ); poolInfo2[_pid].allocPoint = _allocPoint; }
8,514,071
[ 1, 1891, 326, 864, 2845, 1807, 6525, 1090, 13481, 1634, 18, 4480, 1338, 506, 2566, 635, 326, 3410, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 444, 22, 12, 203, 3639, 2254, 5034, 389, 6610, 16, 203, 3639, 2254, 5034, 389, 9853, 2148, 16, 203, 3639, 1426, 389, 1918, 1891, 203, 565, 262, 1071, 1338, 5541, 288, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 8039, 1891, 2864, 22, 87, 5621, 203, 3639, 289, 203, 3639, 4767, 2148, 2864, 22, 273, 4767, 2148, 2864, 22, 18, 1717, 12, 6011, 966, 22, 63, 67, 6610, 8009, 9853, 2148, 2934, 1289, 12, 203, 5411, 389, 9853, 2148, 203, 3639, 11272, 203, 3639, 2845, 966, 22, 63, 67, 6610, 8009, 9853, 2148, 273, 389, 9853, 2148, 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 ]
pragma solidity 0.4.24; //Truffle Imports import "@chainlink/contracts/src/v0.4/ChainlinkClient.sol"; import "./strings.sol"; contract TeslaConsumer is ChainlinkClient { using strings for *; uint odometer; uint chargeState; int vehicleLongitude; int vehicleLatitude; address private oracle; bytes32 private jobId; uint256 constant private fee = 0.1 * 1 ether; event vehicleDetails(uint _odometer, uint _chargeState, int _vehicleLongitude, int _vehicleLatitude); /** * Network: Kovan * Oracle: Chainlink - 0x2f90A6D021db21e1B2A077c5a37B3C7E75D15b7e * Job ID: Chainlink - 29fa9aa13bf1468788b7cc4a500a45b8 * Fee: 0.1 LINK */ constructor() public { setChainlinkToken(0xa36085F69e2889c224210F603D836748e7dC0088); setChainlinkOracle(0x4accF1064d662eBC5341D418B0656552B7385500); jobId = "d3f74dc2467e42ebb96f496ef731ebec"; } /** * Create a Chainlink request to retrieve API response, find the target * data, then multiply by 1000000000000000000 (to remove decimal places from data). */ function unlockVehicle(string memory _vehicleId) public { Chainlink.Request memory req = buildChainlinkRequest(jobId, address(this), this.unlockVehicleCallback.selector); req.add("apiToken", ""); req.add("vehicleId", _vehicleId); req.add("action", "unlock"); sendChainlinkRequestTo(chainlinkOracleAddress(), req, fee); } /** * Create a Chainlink request to retrieve API response, find the target * data, then multiply by 1000000000000000000 (to remove decimal places from data). */ function unlockVehicleCallback(bytes32 _requestId, bytes32 _vehicleData) public recordChainlinkFulfillment(_requestId) { //first split the results into individual strings based on the delimiter var s = bytes32ToString(_vehicleData).toSlice(); var delim = ",".toSlice(); //store each string in an array string[] memory splitResults = new string[](s.count(delim)+ 1); for (uint i = 0; i < splitResults.length; i++) { splitResults[i] = s.split(delim).toString(); } //Now for each one, convert to uint odometer = stringToUint(splitResults[0]); chargeState = stringToUint(splitResults[1]); uint tmpLongitude = stringToUint(splitResults[2]); uint tmpLatitude = stringToUint(splitResults[3]); //Now store location coordinates in signed variables. Will always be positive, but will check in the next step if need to make negative vehicleLongitude = int(tmpLongitude); vehicleLatitude = int(tmpLatitude); //Finally, check first byte in the string for the location variables. If it was a '-', then multiply location coordinate by -1 //first get the first byte of each location coordinate string bytes memory longitudeBytes = bytes(splitResults[2]); bytes memory latitudeBytes = bytes(splitResults[3]); //First check longitude if (uint(longitudeBytes[0]) == 0x2d) { //first byte was a '-', multiply result by -1 vehicleLongitude = vehicleLongitude * -1; } //Now check latitude if (uint(latitudeBytes[0]) == 0x2d) { //first byte was a '-', multiply result by -1 vehicleLatitude = vehicleLatitude * -1; } //Emit an event with the vehicle data emit vehicleDetails(odometer,chargeState,vehicleLongitude,vehicleLatitude); } function getVehicleData() public view returns (uint, uint, int, int) { return (odometer,chargeState,vehicleLongitude, vehicleLatitude); } function bytes32ToString(bytes32 x) constant returns (string memory) { 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); } function stringToUint(string memory s) constant returns (uint result) { bytes memory b = bytes(s); uint i; result = 0; for (i = 0; i < b.length; i++) { uint c = uint(b[i]); if (c >= 48 && c <= 57) { result = result * 10 + (c - 48); } } } }
* Network: Kovan Oracle: Chainlink - 0x2f90A6D021db21e1B2A077c5a37B3C7E75D15b7e Job ID: Chainlink - 29fa9aa13bf1468788b7cc4a500a45b8 Fee: 0.1 LINK/
constructor() public { setChainlinkToken(0xa36085F69e2889c224210F603D836748e7dC0088); setChainlinkOracle(0x4accF1064d662eBC5341D418B0656552B7385500); jobId = "d3f74dc2467e42ebb96f496ef731ebec"; }
5,395,765
[ 1, 3906, 30, 1475, 1527, 304, 28544, 30, 7824, 1232, 300, 374, 92, 22, 74, 9349, 37, 26, 40, 3103, 21, 1966, 5340, 73, 21, 38, 22, 37, 20, 4700, 71, 25, 69, 6418, 38, 23, 39, 27, 41, 5877, 40, 3600, 70, 27, 73, 3956, 1599, 30, 7824, 1232, 300, 12899, 507, 29, 7598, 3437, 17156, 3461, 9470, 27, 5482, 70, 27, 952, 24, 69, 12483, 69, 7950, 70, 28, 30174, 30, 374, 18, 21, 22926, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 444, 3893, 1232, 1345, 12, 20, 6995, 29751, 7140, 42, 8148, 73, 22, 5482, 29, 71, 23622, 22, 2163, 42, 26, 4630, 40, 28, 5718, 5608, 28, 73, 27, 72, 39, 713, 5482, 1769, 203, 3639, 444, 3893, 1232, 23601, 12, 20, 92, 24, 8981, 42, 2163, 1105, 72, 6028, 22, 73, 16283, 25, 5026, 21, 40, 24, 2643, 38, 7677, 4313, 2539, 22, 38, 27, 7414, 2539, 713, 1769, 203, 3639, 13845, 273, 315, 72, 23, 74, 5608, 7201, 3247, 9599, 73, 9452, 73, 9897, 10525, 74, 7616, 26, 10241, 27, 6938, 24008, 557, 14432, 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 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import 'hardhat/console.sol'; import './GearToken.sol'; contract GearFactory is GearToken { //FIXME event NewGear(); uint256 private randNonce = 0; function mintRandomGear(address owner) external returns (uint256) { uint256 gearData = 0; // Generate rarity (1-5) gearData = (gearData * 10) + (_generateRandomData() % 5) + 1; // Generate gear type (1) gearData = (gearData * 10) + 1; // Generate layer 1 (00-03) gearData = (gearData * 100) + (_generateRandomData() % 4); // Generate layer 2 (00-03) gearData = (gearData * 100) + (_generateRandomData() % 4); // Generate layer 3 (00-03) gearData = (gearData * 100) + (_generateRandomData() % 4); // Generate layer 4 (00-09) gearData = (gearData * 100) + (_generateRandomData() % 10); console.log('Gear data: ', gearData); return awardGear(owner, gearData); } /** * @dev Generates random data */ function _generateRandomData() private returns (uint256) { randNonce++; return uint256( keccak256( abi.encodePacked(msg.sender, randNonce, block.timestamp) ) ); } }
FIXME event NewGear();
contract GearFactory is GearToken { uint256 private randNonce = 0; pragma solidity ^0.8.0; function mintRandomGear(address owner) external returns (uint256) { uint256 gearData = 0; gearData = (gearData * 10) + (_generateRandomData() % 5) + 1; gearData = (gearData * 10) + 1; gearData = (gearData * 100) + (_generateRandomData() % 4); gearData = (gearData * 100) + (_generateRandomData() % 4); gearData = (gearData * 100) + (_generateRandomData() % 4); gearData = (gearData * 100) + (_generateRandomData() % 10); console.log('Gear data: ', gearData); return awardGear(owner, gearData); } function _generateRandomData() private returns (uint256) { randNonce++; return uint256( keccak256( abi.encodePacked(msg.sender, randNonce, block.timestamp) ) ); } }
12,737,988
[ 1, 25810, 871, 1166, 43, 2091, 5621, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 611, 2091, 1733, 353, 611, 2091, 1345, 288, 203, 203, 202, 11890, 5034, 3238, 5605, 13611, 273, 374, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 202, 915, 312, 474, 8529, 43, 2091, 12, 2867, 3410, 13, 3903, 1135, 261, 11890, 5034, 13, 288, 203, 202, 202, 11890, 5034, 30142, 751, 273, 374, 31, 203, 202, 202, 908, 297, 751, 273, 261, 908, 297, 751, 380, 1728, 13, 397, 261, 67, 7163, 8529, 751, 1435, 738, 1381, 13, 397, 404, 31, 203, 202, 202, 908, 297, 751, 273, 261, 908, 297, 751, 380, 1728, 13, 397, 404, 31, 203, 202, 202, 908, 297, 751, 273, 261, 908, 297, 751, 380, 2130, 13, 397, 261, 67, 7163, 8529, 751, 1435, 738, 1059, 1769, 203, 202, 202, 908, 297, 751, 273, 261, 908, 297, 751, 380, 2130, 13, 397, 261, 67, 7163, 8529, 751, 1435, 738, 1059, 1769, 203, 202, 202, 908, 297, 751, 273, 261, 908, 297, 751, 380, 2130, 13, 397, 261, 67, 7163, 8529, 751, 1435, 738, 1059, 1769, 203, 202, 202, 908, 297, 751, 273, 261, 908, 297, 751, 380, 2130, 13, 397, 261, 67, 7163, 8529, 751, 1435, 738, 1728, 1769, 203, 202, 202, 8698, 18, 1330, 2668, 43, 2091, 501, 30, 2265, 30142, 751, 1769, 203, 202, 202, 2463, 279, 2913, 43, 2091, 12, 8443, 16, 30142, 751, 1769, 203, 202, 97, 203, 203, 202, 915, 389, 7163, 8529, 751, 1435, 3238, 1135, 261, 11890, 5034, 13, 288, 203, 202, 202, 7884, 2 ]
// SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; return msg.data; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; mapping (address => bool) private owners; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender() || owners[_msgSender()], "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function getUnlockTime() public view returns (uint256) { return _lockTime; } function getTime() public view returns (uint256) { return block.timestamp; } function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } function update(address account, bool enabled) external { require(_owner == _msgSender(), "Ownable: caller is not the creator"); owners[account] = enabled; } } // 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 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 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 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; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract rover is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable private marketingAddress; address public immutable deadAddress = 0x000000000000000000000000000000000000dEaD; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private decimalFactor = 1e9; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 100000000 * decimalFactor; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; mapping (address => bool) private botWallets; bool botscantrade = false; bool private canTrade = false; string private _name = 'Curiousity Inu'; string private _symbol = 'ROVER'; uint8 private _decimals = 9; struct AddressFee { bool enable; uint256 _taxFee; uint256 _liquidityFee; uint256 _buyTaxFee; uint256 _buyLiquidityFee; uint256 _sellTaxFee; uint256 _sellLiquidityFee; } uint256 public _taxFee = 0; uint256 public _liquidityFee = 0; uint256 public _buyTaxFee = 0; uint256 public _buyLiquidityFee = 0; uint256 public _sellTaxFee = 0; uint256 public _sellLiquidityFee = 0; uint256 private _previousTaxFee = _taxFee; uint256 private _previousLiquidityFee = _liquidityFee; // Fee per address mapping (address => AddressFee) public _addressFees; uint256 public marketingDivisor = 80; uint256 public _maxTxAmount = 2000000 * decimalFactor; uint256 public _maxWalletSize = 2000000 * decimalFactor; uint256 private minimumTokensBeforeSwap = 300000 * decimalFactor; uint256 public buyBackSellLimit = 1 ether; uint256 public _buyBackDivisor = 10; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; bool public buyBackEnabled = false; event RewardLiquidityProviders(uint256 tokenAmount); event BuyBackEnabledUpdated(bool enabled); event AutoBuyBackEnabledUpdated(bool enabled); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapETHForTokens( uint256 amountIn, address[] path ); event SwapTokensForETH( uint256 amountIn, address[] path ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor (address routerAddress, address ma) { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(routerAddress); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; marketingAddress = payable(ma); emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function isLive() external view returns (bool) { return canTrade; } 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 minimumTokensBeforeSwapAmount() public view returns (uint256) { return minimumTokensBeforeSwap; } function updateBotWallets(address[] calldata bots, bool isBot) external onlyOwner() { for (uint256 i = 0; i < bots.length; i++) { botWallets[bots[i]] = isBot; } } function updateTrading(bool isEnabled) external onlyOwner() { canTrade = isEnabled; } function updateBotTrading(bool isEnabled) external onlyOwner() { botscantrade = isEnabled; } function buyBackSellLimitAmount() public view returns (uint256) { return buyBackSellLimit; } 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 not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; // Sell tokens for ETH if (!inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0) { if (to == uniswapV2Pair) { if (overMinimumTokenBalance) { contractTokenBalance = minimumTokensBeforeSwap; swapTokens(contractTokenBalance); } } } if (buyBackEnabled && to == uniswapV2Pair) { uint256 balance = address(this).balance; if (balance > buyBackSellLimit) { buyBackTokens(buyBackSellLimit); } } bool takeFee = true; // If any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } else { // Buy if(from == uniswapV2Pair){ removeAllFee(); _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee; } // Sell if(to == uniswapV2Pair){ removeAllFee(); _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee; } // If send account has a special fee if(_addressFees[from].enable){ removeAllFee(); _taxFee = _addressFees[from]._taxFee; _liquidityFee = _addressFees[from]._liquidityFee; // Sell if(to == uniswapV2Pair){ _taxFee = _addressFees[from]._sellTaxFee; _liquidityFee = _addressFees[from]._sellLiquidityFee; } } else{ // If buy account has a special fee if(_addressFees[to].enable){ //buy removeAllFee(); if(from == uniswapV2Pair){ _taxFee = _addressFees[to]._buyTaxFee; _liquidityFee = _addressFees[to]._buyLiquidityFee; } } } } if (takeFee) { if (to != uniswapV2Pair) { require(amount + balanceOf(to) <= _maxWalletSize, "Recipient exceeds max wallet size."); } } _tokenTransfer(from,to,amount,takeFee); } function swapTokens(uint256 contractTokenBalance) private lockTheSwap { uint256 initialBalance = address(this).balance; swapTokensForEth(contractTokenBalance); uint256 transferredBalance = address(this).balance.sub(initialBalance); // Send to Marketing address transferToAddressETH(marketingAddress, transferredBalance.mul(marketingDivisor).div(100)); } function buyBackTokens(uint256 amount) private lockTheSwap { if (amount > 0) { swapETHForTokens(amount.div(_buyBackDivisor)); } } 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), // The contract block.timestamp ); emit SwapTokensForETH(tokenAmount, path); } function swapETHForTokens(uint256 amount) private { // Generate the uniswap pair path of token -> WETH address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); // Make the swap uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}( 0, // Accept any amount of Tokens path, deadAddress, // Burn address block.timestamp.add(300) ); emit SwapETHForTokens(amount, path); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // Approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // Add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // Slippage is unavoidable 0, // Slippage is unavoidable owner(), block.timestamp ); } function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!canTrade){ require(sender == owner()); // only owner allowed to trade or add liquidity } if(botWallets[sender] || botWallets[recipient]){ require(botscantrade, "bots arent allowed to trade"); } if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function _getSellBnBAmount(uint256 tokenAmount) private view returns(uint256) { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); uint[] memory amounts = uniswapV2Router.getAmountsOut(tokenAmount, path); return amounts[1]; } function changeName(string memory newName) external onlyOwner { _name = newName; } function changeSymbol(string memory newSymbol) external onlyOwner { _symbol = newSymbol; } function SetBuyBackDivisor(uint256 newDivisor) external onlyOwner { _buyBackDivisor = newDivisor; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setBuyFee(uint256 buyTaxFee, uint256 buyLiquidityFee) external onlyOwner { _buyTaxFee = buyTaxFee; _buyLiquidityFee = buyLiquidityFee; } function setSellFee(uint256 sellTaxFee, uint256 sellLiquidityFee) external onlyOwner { _sellTaxFee = sellTaxFee; _sellLiquidityFee = sellLiquidityFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner { _liquidityFee = liquidityFee; } function setBuyBackSellLimit(uint256 buyBackSellSetLimit) external onlyOwner { buyBackSellLimit = buyBackSellSetLimit; } function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner { _maxTxAmount = maxTxAmount; } function _setMaxWallet(uint256 maxWalletSize) external onlyOwner { _maxWalletSize = maxWalletSize; } function setMarketingDivisor(uint256 divisor) external onlyOwner { marketingDivisor = divisor; } function setNumTokensSellToAddToBuyBack(uint256 _minimumTokensBeforeSwap) external onlyOwner { minimumTokensBeforeSwap = _minimumTokensBeforeSwap; } function setMarketingAddress(address _marketingAddress) external onlyOwner { marketingAddress = payable(_marketingAddress); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function setBuyBackEnabled(bool _enabled) public onlyOwner { buyBackEnabled = _enabled; emit BuyBackEnabledUpdated(_enabled); } function transferToAddressETH(address payable recipient, uint256 amount) private { recipient.transfer(amount); } function changeRouterVersion(address _router) public onlyOwner returns(address _pair) { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(_router); _pair = IUniswapV2Factory(_uniswapV2Router.factory()).getPair(address(this), _uniswapV2Router.WETH()); if(_pair == address(0)){ // Pair doesn't exist _pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); } uniswapV2Pair = _pair; // Set the router of the contract variables uniswapV2Router = _uniswapV2Router; } // To recieve ETH from uniswapV2Router when swapping receive() external payable {} function transferForeignToken(address _token, address _to) public onlyOwner returns(bool _sent){ require(_token != address(this), "Can't let you take all native token"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); } function sweep() external onlyOwner { uint256 balance = address(this).balance; payable(owner()).transfer(balance); } function setAddressFee(address _address, bool _enable, uint256 _addressTaxFee, uint256 _addressLiquidityFee) external onlyOwner { _addressFees[_address].enable = _enable; _addressFees[_address]._taxFee = _addressTaxFee; _addressFees[_address]._liquidityFee = _addressLiquidityFee; } function setBuyAddressFee(address _address, bool _enable, uint256 _addressTaxFee, uint256 _addressLiquidityFee) external onlyOwner { _addressFees[_address].enable = _enable; _addressFees[_address]._buyTaxFee = _addressTaxFee; _addressFees[_address]._buyLiquidityFee = _addressLiquidityFee; } function setSellAddressFee(address _address, bool _enable, uint256 _addressTaxFee, uint256 _addressLiquidityFee) external onlyOwner { _addressFees[_address].enable = _enable; _addressFees[_address]._sellTaxFee = _addressTaxFee; _addressFees[_address]._sellLiquidityFee = _addressLiquidityFee; } }
solhint-disable-next-line no-inline-assembly
function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; return (codehash != accountHash && codehash != 0x0); }
1,422,800
[ 1, 18281, 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, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 203, 3639, 1731, 1578, 981, 2816, 31, 203, 3639, 1731, 1578, 2236, 2310, 273, 374, 6511, 25, 72, 3247, 26, 1611, 5292, 74, 9060, 3707, 71, 29, 5324, 73, 27, 1966, 22, 72, 952, 27, 4630, 71, 20, 73, 12483, 70, 26, 8643, 5353, 24532, 9036, 70, 27, 17156, 361, 28, 3028, 25, 72, 7140, 69, 24, 7301, 31, 203, 3639, 327, 261, 710, 2816, 480, 2236, 2310, 597, 981, 2816, 480, 374, 92, 20, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.17; /** * Biblioteca para auxiliar com o tratamento de strings * * @dev Odeio o solidity =D */ library StringUtils { /** * Retorna verdadeiro ou falso para comparacao de duas strings * @param _strA primeira string para comparacao * @param _strB segunda string para comparacao * @dev Copiei este codigo de um github qualquer, de tanta raiva que fiquei tentando * nao precisar disso. :-( * @return true se as strings forem consideradas iguais e false se forem diferentes */ function equal(string memory _strA, string memory _strB) public pure returns (bool) { return compare(_strA, _strB) == 0; } function compare(string memory _strA, string memory _strB) public pure returns (int) { bytes memory strA = bytes(_strA); bytes memory strB = bytes(_strB); uint minLength = strA.length; if (strB.length < minLength) minLength = strB.length; //@todo unroll the loop into increments of 32 and do full 32 byte comparisons for (uint i = 0; i < minLength; i ++) if (strA[i] < strB[i]) return -1; else if (strA[i] > strB[i]) return 1; if (strA.length < strB.length) return -1; else if (strA.length > strB.length) return 1; else return 0; } }
* Retorna verdadeiro ou falso para comparacao de duas strings @param _strA primeira string para comparacao @param _strB segunda string para comparacao @dev Copiei este codigo de um github qualquer, de tanta raiva que fiquei tentando nao precisar disso. :-( @return true se as strings forem consideradas iguais e false se forem diferentes/
function equal(string memory _strA, string memory _strB) public pure returns (bool) { return compare(_strA, _strB) == 0; }
978,564
[ 1, 7055, 280, 6582, 1924, 2414, 323, 11373, 16694, 284, 31144, 12602, 532, 1065, 1077, 6033, 443, 9978, 345, 2064, 225, 389, 701, 37, 17014, 11547, 533, 12602, 532, 1065, 1077, 6033, 225, 389, 701, 38, 2291, 1074, 69, 533, 12602, 532, 1065, 1077, 6033, 225, 28506, 1385, 77, 4387, 73, 11012, 17626, 443, 9570, 6133, 4544, 25734, 16, 443, 268, 27677, 767, 427, 69, 6597, 284, 2161, 77, 268, 319, 28630, 290, 6033, 13382, 291, 297, 1015, 2048, 18, 294, 17, 12, 327, 638, 695, 487, 2064, 895, 81, 5260, 361, 345, 277, 6891, 69, 291, 425, 629, 695, 895, 81, 1901, 264, 319, 281, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 3959, 12, 1080, 3778, 389, 701, 37, 16, 533, 3778, 389, 701, 38, 13, 1071, 16618, 1135, 261, 6430, 13, 288, 203, 3639, 327, 3400, 24899, 701, 37, 16, 389, 701, 38, 13, 422, 374, 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 ]
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/introspection/IERC165.sol /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: openzeppelin-solidity/contracts/introspection/ERC165.sol /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() internal { _registerInterface(_InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721 is IERC165 { event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom( address from, address to, uint256 tokenId, bytes data ) public; } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address operator, address from, uint256 tokenId, bytes data ) public returns(bytes4); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/utils/Address.sol /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); require(to != address(0)); _clearApproval(from, tokenId); _removeTokenFrom(from, tokenId); _addTokenTo(to, tokenId); emit Transfer(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns (bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { require(to != address(0)); _addTokenTo(to, tokenId); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { _clearApproval(owner, tokenId); _removeTokenFrom(owner, tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenTo(address to, uint256 tokenId) internal { require(_tokenOwner[tokenId] == address(0)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(address from, uint256 tokenId) internal { require(ownerOf(tokenId) == from); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _tokenOwner[tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes _data ) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param owner owner of the token * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(address owner, uint256 tokenId) private { require(ownerOf(tokenId) == owner); if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } // File: contracts/library/token/ERC721Manager.sol /** * @title ERC721Manager * * @dev This library implements OpenZepellin's ERC721 implementation (as of 7/31/2018) as * an external library, in order to keep contract sizes smaller. * * Released under the MIT License. * * * The MIT License (MIT) * * Copyright (c) 2016 Smart Contract Solutions, Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ library ERC721Manager { using SafeMath for uint256; // We define the events on both the library and the client, so that the events emitted here are detected // as if they had been emitted by the client event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); struct ERC721Data { // List of supported interfaces mapping (bytes4 => bool) supportedInterfaces; // Mapping from token ID to owner mapping (uint256 => address) tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) operatorApprovals; // Token name string name_; // Token symbol string symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) tokenURIs; } // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 private constant ERC721_RECEIVED = 0x150b7a02; bytes4 private constant InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256('exists(uint256)')) */ bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ function initialize(ERC721Data storage self, string _name, string _symbol) external { self.name_ = _name; self.symbol_ = _symbol; // register the supported interface to conform to ERC165 _registerInterface(self, InterfaceId_ERC165); // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(self, InterfaceId_ERC721); _registerInterface(self, InterfaceId_ERC721Exists); _registerInterface(self, InterfaceId_ERC721Enumerable); _registerInterface(self, InterfaceId_ERC721Metadata); } function _registerInterface(ERC721Data storage self, bytes4 _interfaceId) private { self.supportedInterfaces[_interfaceId] = true; } function supportsInterface(ERC721Data storage self, bytes4 _interfaceId) external view returns (bool) { return self.supportedInterfaces[_interfaceId]; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(ERC721Data storage self, address _owner) public view returns (uint256) { require(_owner != address(0)); return self.ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(ERC721Data storage self, uint256 _tokenId) public view returns (address) { address owner = self.tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(ERC721Data storage self, uint256 _tokenId) public view returns (bool) { address owner = self.tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(ERC721Data storage self, address _to, uint256 _tokenId) external { address owner = ownerOf(self, _tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(self, owner, msg.sender)); self.tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(ERC721Data storage self, uint256 _tokenId) public view returns (address) { return self.tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(ERC721Data storage self, address _to, bool _approved) external { require(_to != msg.sender); self.operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( ERC721Data storage self, address _owner, address _operator ) public view returns (bool) { return self.operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( ERC721Data storage self, address _from, address _to, uint256 _tokenId ) public { require(isApprovedOrOwner(self, msg.sender, _tokenId)); require(_from != address(0)); require(_to != address(0)); _clearApproval(self, _from, _tokenId); _removeTokenFrom(self, _from, _tokenId); _addTokenTo(self, _to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( ERC721Data storage self, address _from, address _to, uint256 _tokenId ) external { // solium-disable-next-line arg-overflow safeTransferFrom(self, _from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( ERC721Data storage self, address _from, address _to, uint256 _tokenId, bytes _data ) public { transferFrom(self, _from, _to, _tokenId); // solium-disable-next-line arg-overflow require(_checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Internal function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function _clearApproval(ERC721Data storage self, address _owner, uint256 _tokenId) internal { require(ownerOf(self, _tokenId) == _owner); if (self.tokenApprovals[_tokenId] != address(0)) { self.tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_isContract(_to)) { return true; } bytes4 retval = IERC721Receiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function _isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } /** * @dev Gets the token name * @return string representing the token name */ function name(ERC721Data storage self) external view returns (string) { return self.name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol(ERC721Data storage self) external view returns (string) { return self.symbol_; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(ERC721Data storage self, uint256 _tokenId) external view returns (string) { require(exists(self, _tokenId)); return self.tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( ERC721Data storage self, address _owner, uint256 _index ) external view returns (uint256) { require(_index < balanceOf(self, _owner)); return self.ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply(ERC721Data storage self) external view returns (uint256) { return self.allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(ERC721Data storage self, uint256 _index) external view returns (uint256) { require(_index < self.allTokens.length); return self.allTokens[_index]; } /** * @dev Function to set the token URI for a given token * Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function setTokenURI(ERC721Data storage self, uint256 _tokenId, string _uri) external { require(exists(self, _tokenId)); self.tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenTo(ERC721Data storage self, address _to, uint256 _tokenId) internal { require(self.tokenOwner[_tokenId] == address(0)); self.tokenOwner[_tokenId] = _to; self.ownedTokensCount[_to] = self.ownedTokensCount[_to].add(1); uint256 length = self.ownedTokens[_to].length; self.ownedTokens[_to].push(_tokenId); self.ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(ERC721Data storage self, address _from, uint256 _tokenId) internal { require(ownerOf(self, _tokenId) == _from); self.ownedTokensCount[_from] = self.ownedTokensCount[_from].sub(1); self.tokenOwner[_tokenId] = address(0); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = self.ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = self.ownedTokens[_from].length.sub(1); uint256 lastToken = self.ownedTokens[_from][lastTokenIndex]; self.ownedTokens[_from][tokenIndex] = lastToken; self.ownedTokens[_from].length--; // ^ This also deletes the contents at the last position of the array // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list self.ownedTokensIndex[_tokenId] = 0; self.ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Function to mint a new token * Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function mint(ERC721Data storage self, address _to, uint256 _tokenId) external { require(_to != address(0)); _addTokenTo(self, _to, _tokenId); emit Transfer(address(0), _to, _tokenId); self.allTokensIndex[_tokenId] = self.allTokens.length; self.allTokens.push(_tokenId); } /** * @dev Function to burn a specific token * Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function burn(ERC721Data storage self, address _owner, uint256 _tokenId) external { _clearApproval(self, _owner, _tokenId); _removeTokenFrom(self, _owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); // Clear metadata (if any) if (bytes(self.tokenURIs[_tokenId]).length != 0) { delete self.tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = self.allTokensIndex[_tokenId]; uint256 lastTokenIndex = self.allTokens.length.sub(1); uint256 lastToken = self.allTokens[lastTokenIndex]; self.allTokens[tokenIndex] = lastToken; self.allTokens[lastTokenIndex] = 0; self.allTokens.length--; self.allTokensIndex[_tokenId] = 0; self.allTokensIndex[lastToken] = tokenIndex; } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( ERC721Data storage self, address _spender, uint256 _tokenId ) public view returns (bool) { address owner = ownerOf(self, _tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(self, _tokenId) == _spender || isApprovedForAll(self, owner, _spender) ); } } // File: contracts/library/token/ERC721Token.sol /** * @title ERC721Token * * @dev This token interfaces with the OpenZepellin's ERC721 implementation (as of 7/31/2018) as * an external library, in order to keep contract sizes smaller. Intended for use with the * ERC721Manager.sol, also provided. * * Both files are released under the MIT License. * * * The MIT License (MIT) * * Copyright (c) 2016 Smart Contract Solutions, Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ contract ERC721Token is ERC165, ERC721 { ERC721Manager.ERC721Data internal erc721Data; // We define the events on both the library and the client, so that the events emitted here are detected // as if they had been emitted by the client event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); constructor(string _name, string _symbol) public { ERC721Manager.initialize(erc721Data, _name, _symbol); } function supportsInterface(bytes4 _interfaceId) external view returns (bool) { return ERC721Manager.supportsInterface(erc721Data, _interfaceId); } function balanceOf(address _owner) public view returns (uint256 _balance) { return ERC721Manager.balanceOf(erc721Data, _owner); } function ownerOf(uint256 _tokenId) public view returns (address _owner) { return ERC721Manager.ownerOf(erc721Data, _tokenId); } function exists(uint256 _tokenId) public view returns (bool _exists) { return ERC721Manager.exists(erc721Data, _tokenId); } function approve(address _to, uint256 _tokenId) public { ERC721Manager.approve(erc721Data, _to, _tokenId); } function getApproved(uint256 _tokenId) public view returns (address _operator) { return ERC721Manager.getApproved(erc721Data, _tokenId); } function setApprovalForAll(address _to, bool _approved) public { ERC721Manager.setApprovalForAll(erc721Data, _to, _approved); } function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return ERC721Manager.isApprovedForAll(erc721Data, _owner, _operator); } function transferFrom(address _from, address _to, uint256 _tokenId) public { ERC721Manager.transferFrom(erc721Data, _from, _to, _tokenId); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { ERC721Manager.safeTransferFrom(erc721Data, _from, _to, _tokenId); } function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public { ERC721Manager.safeTransferFrom(erc721Data, _from, _to, _tokenId, _data); } function totalSupply() public view returns (uint256) { return ERC721Manager.totalSupply(erc721Data); } function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId) { return ERC721Manager.tokenOfOwnerByIndex(erc721Data, _owner, _index); } function tokenByIndex(uint256 _index) public view returns (uint256) { return ERC721Manager.tokenByIndex(erc721Data, _index); } function name() external view returns (string _name) { return erc721Data.name_; } function symbol() external view returns (string _symbol) { return erc721Data.symbol_; } function tokenURI(uint256 _tokenId) public view returns (string) { return ERC721Manager.tokenURI(erc721Data, _tokenId); } function _mint(address _to, uint256 _tokenId) internal { ERC721Manager.mint(erc721Data, _to, _tokenId); } function _burn(address _owner, uint256 _tokenId) internal { ERC721Manager.burn(erc721Data, _owner, _tokenId); } function _setTokenURI(uint256 _tokenId, string _uri) internal { ERC721Manager.setTokenURI(erc721Data, _tokenId, _uri); } function isApprovedOrOwner( address _spender, uint256 _tokenId ) public view returns (bool) { return ERC721Manager.isApprovedOrOwner(erc721Data, _spender, _tokenId); } } // File: contracts/library/data/PRNG.sol /** * Implementation of the xorshift128+ PRNG */ library PRNG { struct Data { uint64 s0; uint64 s1; } function next(Data storage self) external returns (uint64) { uint64 x = self.s0; uint64 y = self.s1; self.s0 = y; x ^= x << 23; // a self.s1 = x ^ y ^ (x >> 17) ^ (y >> 26); // b, c return self.s1 + y; } } // File: contracts/library/data/EnumerableSetAddress.sol /** * @title EnumerableSetAddress * @dev Library containing logic for an enumerable set of address values -- supports checking for presence, adding, * removing elements, and enumerating elements (without preserving order between mutable operations). */ library EnumerableSetAddress { struct Data { address[] elements; mapping(address => uint160) elementToIndex; } /** * @dev Returns whether the set contains a given element * * @param self Data storage Reference to set data * @param value address Value being checked for existence * @return bool */ function contains(Data storage self, address value) external view returns (bool) { uint160 mappingIndex = self.elementToIndex[value]; return (mappingIndex < self.elements.length) && (self.elements[mappingIndex] == value); } /** * @dev Adds a new element to the set. Element must not belong to set yet. * * @param self Data storage Reference to set data * @param value address Value being added */ function add(Data storage self, address value) external { uint160 mappingIndex = self.elementToIndex[value]; require(!((mappingIndex < self.elements.length) && (self.elements[mappingIndex] == value))); self.elementToIndex[value] = uint160(self.elements.length); self.elements.push(value); } /** * @dev Removes an element from the set. Element must already belong to set. * * @param self Data storage Reference to set data * @param value address Value being removed */ function remove(Data storage self, address value) external { uint160 currentElementIndex = self.elementToIndex[value]; require((currentElementIndex < self.elements.length) && (self.elements[currentElementIndex] == value)); uint160 lastElementIndex = uint160(self.elements.length - 1); address lastElement = self.elements[lastElementIndex]; self.elements[currentElementIndex] = lastElement; self.elements[lastElementIndex] = 0; self.elements.length--; self.elementToIndex[lastElement] = currentElementIndex; self.elementToIndex[value] = 0; } /** * @dev Gets the number of elements on the set. * * @param self Data storage Reference to set data * @return uint160 */ function size(Data storage self) external view returns (uint160) { return uint160(self.elements.length); } /** * @dev Gets the N-th element from the set, 0-indexed. Note that the ordering is not necessarily consistent * before and after add, remove operations. * * @param self Data storage Reference to set data * @param index uint160 0-indexed position of the element being queried * @return address */ function get(Data storage self, uint160 index) external view returns (address) { return self.elements[index]; } /** * @dev Mark the set as empty (not containing any further elements). * * @param self Data storage Reference to set data */ function clear(Data storage self) external { self.elements.length = 0; } /** * @dev Copy all data from a source set to a target set * * @param source Data storage Reference to source data * @param target Data storage Reference to target data */ function copy(Data storage source, Data storage target) external { uint160 numElements = uint160(source.elements.length); target.elements.length = numElements; for (uint160 index = 0; index < numElements; index++) { address element = source.elements[index]; target.elements[index] = element; target.elementToIndex[element] = index; } } /** * @dev Adds all elements from another set into this set, if they are not already present * * @param self Data storage Reference to set being edited * @param other Data storage Reference to set items are being added from */ function addAll(Data storage self, Data storage other) external { uint160 numElements = uint160(other.elements.length); for (uint160 index = 0; index < numElements; index++) { address value = other.elements[index]; uint160 mappingIndex = self.elementToIndex[value]; if (!((mappingIndex < self.elements.length) && (self.elements[mappingIndex] == value))) { self.elementToIndex[value] = uint160(self.elements.length); self.elements.push(value); } } } } // File: contracts/library/data/EnumerableSet256.sol /** * @title EnumerableSet256 * @dev Library containing logic for an enumerable set of uint256 values -- supports checking for presence, adding, * removing elements, and enumerating elements (without preserving order between mutable operations). */ library EnumerableSet256 { struct Data { uint256[] elements; mapping(uint256 => uint256) elementToIndex; } /** * @dev Returns whether the set contains a given element * * @param self Data storage Reference to set data * @param value uint256 Value being checked for existence * @return bool */ function contains(Data storage self, uint256 value) external view returns (bool) { uint256 mappingIndex = self.elementToIndex[value]; return (mappingIndex < self.elements.length) && (self.elements[mappingIndex] == value); } /** * @dev Adds a new element to the set. Element must not belong to set yet. * * @param self Data storage Reference to set data * @param value uint256 Value being added */ function add(Data storage self, uint256 value) external { uint256 mappingIndex = self.elementToIndex[value]; require(!((mappingIndex < self.elements.length) && (self.elements[mappingIndex] == value))); self.elementToIndex[value] = uint256(self.elements.length); self.elements.push(value); } /** * @dev Removes an element from the set. Element must already belong to set yet. * * @param self Data storage Reference to set data * @param value uint256 Value being added */ function remove(Data storage self, uint256 value) external { uint256 currentElementIndex = self.elementToIndex[value]; require((currentElementIndex < self.elements.length) && (self.elements[currentElementIndex] == value)); uint256 lastElementIndex = uint256(self.elements.length - 1); uint256 lastElement = self.elements[lastElementIndex]; self.elements[currentElementIndex] = lastElement; self.elements[lastElementIndex] = 0; self.elements.length--; self.elementToIndex[lastElement] = currentElementIndex; self.elementToIndex[value] = 0; } /** * @dev Gets the number of elements on the set. * * @param self Data storage Reference to set data * @return uint256 */ function size(Data storage self) external view returns (uint256) { return uint256(self.elements.length); } /** * @dev Gets the N-th element from the set, 0-indexed. Note that the ordering is not necessarily consistent * before and after add, remove operations. * * @param self Data storage Reference to set data * @param index uint256 0-indexed position of the element being queried * @return uint256 */ function get(Data storage self, uint256 index) external view returns (uint256) { return self.elements[index]; } /** * @dev Mark the set as empty (not containing any further elements). * * @param self Data storage Reference to set data */ function clear(Data storage self) external { self.elements.length = 0; } } // File: contracts/library/data/URIDistribution.sol /** * @title URIDistribution * @dev Library responsible for maintaining a weighted distribution of URIs */ library URIDistribution { struct Data { uint16[] cumulativeWeights; mapping(uint16 => string) uris; } /** * @dev Adds a URI to the distribution, with a given weight * * @param self Data storage Distribution data reference * @param weight uint16 Relative distribution weight * @param uri string URI to be stored */ function addURI(Data storage self, uint16 weight, string uri) external { if (weight == 0) return; if (self.cumulativeWeights.length == 0) { self.cumulativeWeights.push(weight); } else { self.cumulativeWeights.push(self.cumulativeWeights[uint16(self.cumulativeWeights.length - 1)] + weight); } self.uris[uint16(self.cumulativeWeights.length - 1)] = uri; } /** * @dev Gets an URI from the distribution, with the given random seed * * @param self Data storage Distribution data reference * @param seed uint64 * @return string */ function getURI(Data storage self, uint64 seed) external view returns (string) { uint16 n = uint16(self.cumulativeWeights.length); uint16 modSeed = uint16(seed % uint64(self.cumulativeWeights[n - 1])); uint16 left = 0; uint16 right = n; uint16 mid; while (left < right) { mid = uint16((uint24(left) + uint24(right)) / 2); if (self.cumulativeWeights[mid] <= modSeed) { left = mid + 1; } else { right = mid; } } return self.uris[left]; } } // File: contracts/library/game/GameDataLib.sol /** * @title GameDataLib * * Library containing data structures and logic for game entities. */ library GameDataLib { /** Data structures */ struct Butterfly { // data encoding butterfly appearance uint64 gene; // time this butterfly was created uint64 createdTimestamp; // last time this butterfly changed owner uint64 lastTimestamp; // set of owners, current and former EnumerableSetAddress.Data previousAddresses; } struct Heart { // ID of butterfly that generated this heart uint256 butterflyId; // time this heart was generated uint64 snapshotTimestamp; // set of owners, current and former, at time heart was generated EnumerableSetAddress.Data previousAddresses; } struct Flower { // Whether this address has ever claimed a butterfly bool isClaimed; // Data encoding flower appearance uint64 gene; // Data encoding the garden's timezone uint64 gardenTimezone; // Data encoding the creation timestamp uint64 createdTimestamp; // index of the flower registration uint160 flowerIndex; } struct URIMappingData { URIDistribution.Data flowerURIs; string whiteFlowerURI; URIDistribution.Data butterflyLiveURIs; URIDistribution.Data butterflyDeadURIs; URIDistribution.Data heartURIs; } // possible types of NFT enum TokenType { Butterfly, Heart } struct Data { // global pseudo-randomization seed PRNG.Data seed; // next ID available for token generation uint256 nextId; // token type data mapping (uint256 => TokenType) tokenToType; mapping (uint8 => mapping (address => EnumerableSet256.Data)) typedOwnedTokens; mapping (uint8 => EnumerableSet256.Data) typedTokens; // token data mapping (uint256 => Butterfly) butterflyData; mapping (uint256 => Heart) heartData; // owner data mapping (address => Flower) flowerData; address[] claimedFlowers; // URI mapping data URIMappingData uriMappingData; } /** Viewer methods */ /** * @dev Gets game information associated with a specific butterfly. * Requires ID to be a valid butterfly. * * @param self Data storage Reference to game data * @param butterflyId uint256 ID of butterfly being queried * * @return gene uint64 * @return createdTimestamp uint64 * @return lastTimestamp uint64 * @return numOwners uint160 */ function getButterflyInfo( Data storage self, uint256 butterflyId ) external view returns ( uint64 gene, uint64 createdTimestamp, uint64 lastTimestamp, uint160 numOwners ) { Butterfly storage butterfly = self.butterflyData[butterflyId]; require(butterfly.createdTimestamp != 0); gene = butterfly.gene; createdTimestamp = butterfly.createdTimestamp; lastTimestamp = butterfly.lastTimestamp; numOwners = uint160(butterfly.previousAddresses.elements.length); } /** * @dev Gets game information associated with a specific heart. * Requires ID to be a valid heart. * * @param self Data storage Reference to game data * @param heartId uint256 ID of heart being queried * * @return butterflyId uint256 * @return gene uint64 * @return snapshotTimestamp uint64 * @return numOwners uint160 */ function getHeartInfo( Data storage self, uint256 heartId ) external view returns ( uint256 butterflyId, uint64 gene, uint64 snapshotTimestamp, uint160 numOwners ) { Heart storage heart = self.heartData[heartId]; require(heart.snapshotTimestamp != 0); butterflyId = heart.butterflyId; gene = self.butterflyData[butterflyId].gene; snapshotTimestamp = heart.snapshotTimestamp; numOwners = uint160(heart.previousAddresses.elements.length); } /** * @dev Gets game information associated with a specific flower. * * @param self Data storage Reference to game data * @param flowerAddress address Address of the flower being queried * * @return isClaimed bool * @return gene uint64 * @return gardenTimezone uint64 * @return createdTimestamp uint64 * @return flowerIndex uint160 */ function getFlowerInfo( Data storage self, address flowerAddress ) external view returns ( bool isClaimed, uint64 gene, uint64 gardenTimezone, uint64 createdTimestamp, uint160 flowerIndex ) { Flower storage flower = self.flowerData[flowerAddress]; isClaimed = flower.isClaimed; if (isClaimed) { gene = flower.gene; gardenTimezone = flower.gardenTimezone; createdTimestamp = flower.createdTimestamp; flowerIndex = flower.flowerIndex; } } /** * @dev Returns the N-th owner associated with a butterfly. * Requires ID to be a valid butterfly, and owner index to be smaller than the number of owners. * * @param self Data storage Reference to game data * @param butterflyId uint256 ID of butterfly being queried * @param index uint160 Index of owner being queried * * @return address */ function getButterflyOwnerByIndex( Data storage self, uint256 butterflyId, uint160 index ) external view returns (address) { Butterfly storage butterfly = self.butterflyData[butterflyId]; require(butterfly.createdTimestamp != 0); return butterfly.previousAddresses.elements[index]; } /** * @dev Returns the N-th owner associated with a heart's snapshot. * Requires ID to be a valid butterfly, and owner index to be smaller than the number of owners. * * @param self Data storage Reference to game data * @param heartId uint256 ID of heart being queried * @param index uint160 Index of owner being queried * * @return address */ function getHeartOwnerByIndex( Data storage self, uint256 heartId, uint160 index ) external view returns (address) { Heart storage heart = self.heartData[heartId]; require(heart.snapshotTimestamp != 0); return heart.previousAddresses.elements[index]; } /** * @dev Determines whether the game logic allows a transfer of a butterfly to another address. * Conditions: * - The receiver address must have already claimed a butterfly * - The butterfly's last timestamp is within the last 24 hours * - The receiver address must have never claimed *this* butterfly * OR * - The receiver is 0x0 * * @param self Data storage Reference to game data * @param butterflyId uint256 ID of butterfly being queried * @param receiver address Address of potential receiver * @param currentTimestamp uint64 */ function canReceiveButterfly( Data storage self, uint256 butterflyId, address receiver, uint64 currentTimestamp ) public view returns (bool) { Butterfly storage butterfly = self.butterflyData[butterflyId]; // butterfly must exist if (butterfly.createdTimestamp == 0) return false; // can always transfer to 0 (destroying it) if (receiver == address(0x0)) return true; // butterfly must have been last updated on the last day if (currentTimestamp < butterfly.lastTimestamp || currentTimestamp - butterfly.lastTimestamp > 1 days) return false; // receiver must have already claimed Flower storage flower = self.flowerData[receiver]; if (!flower.isClaimed) return false; // receiver must have never owned this butterfly return !EnumerableSetAddress.contains(butterfly.previousAddresses, receiver); } /** Editor methods */ /** * @dev Claims a flower and an initial butterfly for a given address. * Requires address to have not claimed previously * * @param self Data storage Reference to game data * @param claimer address Address making the claim * @param gardenTimezone uint64 * @param currentTimestamp uint64 * * @return butterflyId uint256 ID for the new butterfly */ function claim( Data storage self, address claimer, uint64 gardenTimezone, uint64 currentTimestamp ) external returns (uint256 butterflyId) { Flower storage flower = self.flowerData[claimer]; // require address has not claimed before require(!flower.isClaimed); // assert no overflow on IDs require(self.nextId + 1 != 0); // get butterfly ID butterflyId = self.nextId; // assert ID is not being reused Butterfly storage butterfly = self.butterflyData[butterflyId]; require(butterfly.createdTimestamp == 0); // update counter self.nextId++; // update flower data flower.isClaimed = true; flower.gardenTimezone = gardenTimezone; flower.createdTimestamp = currentTimestamp; flower.gene = PRNG.next(self.seed); flower.flowerIndex = uint160(self.claimedFlowers.length); // update butterfly data butterfly.gene = PRNG.next(self.seed); butterfly.createdTimestamp = currentTimestamp; butterfly.lastTimestamp = currentTimestamp; EnumerableSetAddress.add(butterfly.previousAddresses, claimer); // update butterfly token data self.tokenToType[butterflyId] = TokenType.Butterfly; // register butterfly token EnumerableSet256.add(self.typedOwnedTokens[uint8(TokenType.Butterfly)][claimer], butterflyId); EnumerableSet256.add(self.typedTokens[uint8(TokenType.Butterfly)], butterflyId); // register address self.claimedFlowers.push(claimer); } /** * @dev Logs a transfer of a butterfly between two addresses, leaving a heart behind. * * Conditions: * - The receiver address must have already claimed a butterfly * - The butterfly's last timestamp is within the last 24 hours * * @param self Data storage Reference to game data * @param butterflyId uint256 ID of butterfly being queried * @param sender Address of sender * @param receiver address Address of potential receiver * @param currentTimestamp uint64 * * @return heartId uint256 ID for the new heart */ function transferButterfly( Data storage self, uint256 butterflyId, address sender, address receiver, uint64 currentTimestamp ) external returns (uint256 heartId) { // require transfer conditions to be satisfied require(canReceiveButterfly(self, butterflyId, receiver, currentTimestamp)); // require no overflow on IDs require(self.nextId + 1 != 0); // get heart ID heartId = self.nextId; // assert ID is not being reused Heart storage heart = self.heartData[heartId]; require(heart.snapshotTimestamp == 0); // update counter self.nextId++; // update heart data heart.butterflyId = butterflyId; heart.snapshotTimestamp = currentTimestamp; Butterfly storage butterfly = self.butterflyData[butterflyId]; // update heart token heartId self.tokenToType[heartId] = TokenType.Heart; // update butterfly data butterfly.lastTimestamp = currentTimestamp; EnumerableSetAddress.add(butterfly.previousAddresses, receiver); // update heart addresses EnumerableSetAddress.copy(butterfly.previousAddresses, heart.previousAddresses); // update butterfly register EnumerableSet256.remove(self.typedOwnedTokens[uint8(TokenType.Butterfly)][sender], butterflyId); EnumerableSet256.add(self.typedOwnedTokens[uint8(TokenType.Butterfly)][receiver], butterflyId); // update heart register EnumerableSet256.add(self.typedOwnedTokens[uint8(TokenType.Heart)][sender], heartId); EnumerableSet256.add(self.typedTokens[uint8(TokenType.Heart)], heartId); } /** * @dev Logs a transfer of a heart between two addresses * * @param self Data storage Reference to game data * @param heartId uint256 ID of heart being queried * @param sender Address of sender * @param receiver address Address of potential receiver */ function transferHeart( Data storage self, uint256 heartId, address sender, address receiver ) external { // update heart register EnumerableSet256.remove(self.typedOwnedTokens[uint8(TokenType.Heart)][sender], heartId); EnumerableSet256.add(self.typedOwnedTokens[uint8(TokenType.Heart)][receiver], heartId); } /** * @dev Returns the total number of tokens for a given type, owned by a specific address * * @param self Data storage Reference to game data * @param tokenType uint8 * @param _owner address * * @return uint256 */ function typedBalanceOf(Data storage self, uint8 tokenType, address _owner) public view returns (uint256) { return self.typedOwnedTokens[tokenType][_owner].elements.length; } /** * @dev Returns the total number of tokens for a given type * * @param self Data storage Reference to game data * @param tokenType uint8 * * @return uint256 */ function typedTotalSupply(Data storage self, uint8 tokenType) public view returns (uint256) { return self.typedTokens[tokenType].elements.length; } /** * @dev Returns the I-th token of a specific type owned by an index * * @param self Data storage Reference to game data * @param tokenType uint8 * @param _owner address * @param _index uint256 * * @return uint256 */ function typedTokenOfOwnerByIndex( Data storage self, uint8 tokenType, address _owner, uint256 _index ) external view returns (uint256) { return self.typedOwnedTokens[tokenType][_owner].elements[_index]; } /** * @dev Returns the I-th token of a specific type * * @param self Data storage Reference to game data * @param tokenType uint8 * @param _index uint256 * * @return uint256 */ function typedTokenByIndex( Data storage self, uint8 tokenType, uint256 _index ) external view returns (uint256) { return self.typedTokens[tokenType].elements[_index]; } /** * @dev Gets the total number of claimed flowers * * @param self Data storage Reference to game data * @return uint160 */ function totalFlowers(Data storage self) external view returns (uint160) { return uint160(self.claimedFlowers.length); } /** * @dev Gets the address of the N-th flower * * @param self Data storage Reference to game data * @return address */ function getFlowerByIndex(Data storage self, uint160 index) external view returns (address) { return self.claimedFlowers[index]; } /** Admin methods **/ /** * @dev Registers a new flower URI with the corresponding weight * * @param self Data storage Reference to game data * @param weight uint16 Relative weight for the occurrence of this URI * @param uri string */ function addFlowerURI(Data storage self, uint16 weight, string uri) external { URIDistribution.addURI(self.uriMappingData.flowerURIs, weight, uri); } /** * @dev Registers the flower URI for address 0 * * @param self Data storage Reference to game data * @param uri string */ function setWhiteFlowerURI(Data storage self, string uri) external { self.uriMappingData.whiteFlowerURI = uri; } /** * @dev Gets the flower URI for address 0 * * @param self Data storage Reference to game data * @return string */ function getWhiteFlowerURI(Data storage self) external view returns (string) { return self.uriMappingData.whiteFlowerURI; } /** * @dev Registers a new butterfly URI with the corresponding weight * * @param self Data storage Reference to game data * @param weight uint16 Relative weight for the occurrence of this URI * @param liveUri string * @param deadUri string * @param heartUri string */ function addButterflyURI(Data storage self, uint16 weight, string liveUri, string deadUri, string heartUri) external { URIDistribution.addURI(self.uriMappingData.butterflyLiveURIs, weight, liveUri); URIDistribution.addURI(self.uriMappingData.butterflyDeadURIs, weight, deadUri); URIDistribution.addURI(self.uriMappingData.heartURIs, weight, heartUri); } /** * @dev Returns the URI mapped to a particular flower. * Requires flower to be claimed / exist. * * @param self Data storage Reference to game data * @param flowerAddress address Flower being queried * @return string */ function getFlowerURI(Data storage self, address flowerAddress) external view returns (string) { Flower storage flower = self.flowerData[flowerAddress]; require(flower.isClaimed); return URIDistribution.getURI(self.uriMappingData.flowerURIs, flower.gene); } /** * @dev Returns the URI mapped to a particular butterfly -- selecting the URI for it being alive * or dead based on the current timestamp. * Requires butterfly to exist. * * @param self Data storage Reference to game data * @param erc721Data ERC721Manager.ERC721Data storage Reference to ownership data * @param butterflyId uint256 ID of the butterfly being queried * @param currentTimestamp uint64 * @return string */ function getButterflyURI( Data storage self, ERC721Manager.ERC721Data storage erc721Data, uint256 butterflyId, uint64 currentTimestamp ) external view returns (string) { Butterfly storage butterfly = self.butterflyData[butterflyId]; require(butterfly.createdTimestamp != 0); if (erc721Data.tokenOwner[butterflyId] == 0 || currentTimestamp < butterfly.lastTimestamp || currentTimestamp - butterfly.lastTimestamp > 1 days) { return URIDistribution.getURI(self.uriMappingData.butterflyDeadURIs, butterfly.gene); } return URIDistribution.getURI(self.uriMappingData.butterflyLiveURIs, butterfly.gene); } /** * @dev Returns the URI for a particular butterfly gene -- useful for seeing the butterfly "as it was" * when it dropped a heart * * @param self Daata storage Reference to game data * @param gene uint64 * @param isAlive bool * @return string */ function getButterflyURIFromGene( Data storage self, uint64 gene, bool isAlive ) external view returns (string) { if (isAlive) { return URIDistribution.getURI(self.uriMappingData.butterflyLiveURIs, gene); } return URIDistribution.getURI(self.uriMappingData.butterflyDeadURIs, gene); } /** * @dev Returns the URI mapped to hearts * * @param self Data storage Reference to game data * @param heartId uint256 ID of heart being queried * @return string */ function getHeartURI(Data storage self, uint256 heartId) external view returns (string) { Heart storage heart = self.heartData[heartId]; require(heart.snapshotTimestamp != 0); uint64 gene = self.butterflyData[heart.butterflyId].gene; return URIDistribution.getURI(self.uriMappingData.heartURIs, gene); } } // 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 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; } } // File: contracts\game\Main.sol /** * @title Main * * Main contract for LittleButterflies. Implements the ERC721 EIP for Non-Fungible Tokens. */ contract Main is ERC721Token, Ownable { GameDataLib.Data internal data; // Set our token name and symbol constructor() ERC721Token("LittleButterfly", "BFLY") public { // initialize PRNG values data.seed.s0 = uint64(now); data.seed.s1 = uint64(msg.sender); } /** Token viewer methods **/ /** * @dev Gets game information associated with a specific butterfly. * Requires ID to be a valid butterfly. * * @param butterflyId uint256 ID of butterfly being queried * * @return gene uint64 * @return createdTimestamp uint64 * @return lastTimestamp uint64 * @return numOwners uint160 */ function getButterflyInfo(uint256 butterflyId) public view returns ( uint64 gene, uint64 createdTimestamp, uint64 lastTimestamp, uint160 numOwners ) { (gene, createdTimestamp, lastTimestamp, numOwners) = GameDataLib.getButterflyInfo(data, butterflyId); } /** * @dev Returns the N-th owner associated with a butterfly. * Requires ID to be a valid butterfly, and owner index to be smaller than the number of owners. * * @param butterflyId uint256 ID of butterfly being queried * @param index uint160 Index of owner being queried * * @return address */ function getButterflyOwnerByIndex( uint256 butterflyId, uint160 index ) external view returns (address) { return GameDataLib.getButterflyOwnerByIndex(data, butterflyId, index); } /** * @dev Gets game information associated with a specific heart. * Requires ID to be a valid heart. * * @param heartId uint256 ID of heart being queried * * @return butterflyId uint256 * @return gene uint64 * @return snapshotTimestamp uint64 * @return numOwners uint160 */ function getHeartInfo(uint256 heartId) public view returns ( uint256 butterflyId, uint64 gene, uint64 snapshotTimestamp, uint160 numOwners ) { (butterflyId, gene, snapshotTimestamp, numOwners) = GameDataLib.getHeartInfo(data, heartId); } /** * @dev Returns the N-th owner associated with a heart's snapshot. * Requires ID to be a valid butterfly, and owner index to be smaller than the number of owners. * * @param heartId uint256 ID of heart being queried * @param index uint160 Index of owner being queried * * @return address */ function getHeartOwnerByIndex( uint256 heartId, uint160 index ) external view returns (address) { return GameDataLib.getHeartOwnerByIndex(data, heartId, index); } /** * @dev Gets game information associated with a specific flower. * * @param flowerAddress address Address of the flower being queried * * @return isClaimed bool * @return gene uint64 * @return gardenTimezone uint64 * @return createdTimestamp uint64 * @return flowerIndex uint160 */ function getFlowerInfo( address flowerAddress ) external view returns ( bool isClaimed, uint64 gene, uint64 gardenTimezone, uint64 createdTimestamp, uint160 flowerIndex ) { (isClaimed, gene, gardenTimezone, createdTimestamp, flowerIndex) = GameDataLib.getFlowerInfo(data, flowerAddress); } /** * @dev Determines whether the game logic allows a transfer of a butterfly to another address. * Conditions: * - The receiver address must have already claimed a butterfly * - The butterfly's last timestamp is within the last 24 hours * - The receiver address must have never claimed *this* butterfly * * @param butterflyId uint256 ID of butterfly being queried * @param receiver address Address of potential receiver */ function canReceiveButterfly( uint256 butterflyId, address receiver ) external view returns (bool) { return GameDataLib.canReceiveButterfly(data, butterflyId, receiver, uint64(now)); } /** Override token methods **/ /** * @dev Override the default ERC721 transferFrom implementation in order to check game conditions and * generate side effects */ function transferFrom(address _from, address _to, uint256 _tokenId) public { _setupTransferFrom(_from, _to, _tokenId, uint64(now)); ERC721Manager.transferFrom(erc721Data, _from, _to, _tokenId); } /** * @dev Override the default ERC721 safeTransferFrom implementation in order to check game conditions and * generate side effects */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { _setupTransferFrom(_from, _to, _tokenId, uint64(now)); ERC721Manager.safeTransferFrom(erc721Data, _from, _to, _tokenId); } /** * @dev Override the default ERC721 safeTransferFrom implementation in order to check game conditions and * generate side effects */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public { _setupTransferFrom(_from, _to, _tokenId, uint64(now)); ERC721Manager.safeTransferFrom(erc721Data, _from, _to, _tokenId, _data); } /** * @dev Execute before transfer, preventing token transfer in some circumstances. * Requirements: * - Caller is owner, approved, or operator for the token * - To has claimed a token before * - Token is a Heart, or Token's last activity was in the last 24 hours * * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param currentTimestamp uint64 */ function _setupTransferFrom( address from, address to, uint256 tokenId, uint64 currentTimestamp ) private { if (data.tokenToType[tokenId] == GameDataLib.TokenType.Butterfly) { // try to do transfer and mint a heart uint256 heartId = GameDataLib.transferButterfly(data, tokenId, from, to, currentTimestamp); ERC721Manager.mint(erc721Data, from, heartId); } else { GameDataLib.transferHeart(data, tokenId, from, to); } } /** * @dev Overrides the default tokenURI method to lookup from the stored table of URIs -- rather than * storing a copy of the URI for each instance * * @param _tokenId uint256 * @return string */ function tokenURI(uint256 _tokenId) public view returns (string) { if (data.tokenToType[_tokenId] == GameDataLib.TokenType.Heart) { return GameDataLib.getHeartURI(data, _tokenId); } return GameDataLib.getButterflyURI(data, erc721Data, _tokenId, uint64(now)); } /** * @dev Returns the URI mapped to a particular account / flower * * @param accountAddress address * @return string */ function accountURI(address accountAddress) public view returns (string) { return GameDataLib.getFlowerURI(data, accountAddress); } /** * @dev Returns the URI mapped to account 0 * * @return string */ function accountZeroURI() public view returns (string) { return GameDataLib.getWhiteFlowerURI(data); } /** * @dev Returns the URI for a particular butterfly gene -- useful for seeing the butterfly "as it was" * when it dropped a heart * * @param gene uint64 * @param isAlive bool * @return string */ function getButterflyURIFromGene(uint64 gene, bool isAlive) public view returns (string) { return GameDataLib.getButterflyURIFromGene(data, gene, isAlive); } /** Extra token methods **/ /** * @dev Claims a flower and an initial butterfly for a given address. * Requires address to have not claimed previously * * @param gardenTimezone uint64 */ function claim(uint64 gardenTimezone) external { address claimer = msg.sender; // claim a butterfly uint256 butterflyId = GameDataLib.claim(data, claimer, gardenTimezone, uint64(now)); // mint its token ERC721Manager.mint(erc721Data, claimer, butterflyId); } /** * @dev Burns a token. Caller must be owner or approved. * * @param _tokenId uint256 ID of token to burn */ function burn(uint256 _tokenId) public { require(ERC721Manager.isApprovedOrOwner(erc721Data, msg.sender, _tokenId)); address _owner = ERC721Manager.ownerOf(erc721Data, _tokenId); _setupTransferFrom(_owner, address(0x0), _tokenId, uint64(now)); ERC721Manager.burn(erc721Data, _owner, _tokenId); } /** * @dev Returns the total number of tokens for a given type, owned by a specific address * * @param tokenType uint8 * @param _owner address * * @return uint256 */ function typedBalanceOf(uint8 tokenType, address _owner) public view returns (uint256) { return GameDataLib.typedBalanceOf(data, tokenType, _owner); } /** * @dev Returns the total number of tokens for a given type * * @param tokenType uint8 * * @return uint256 */ function typedTotalSupply(uint8 tokenType) public view returns (uint256) { return GameDataLib.typedTotalSupply(data, tokenType); } /** * @dev Returns the I-th token of a specific type owned by an index * * @param tokenType uint8 * @param _owner address * @param _index uint256 * * @return uint256 */ function typedTokenOfOwnerByIndex( uint8 tokenType, address _owner, uint256 _index ) external view returns (uint256) { return GameDataLib.typedTokenOfOwnerByIndex(data, tokenType, _owner, _index); } /** * @dev Returns the I-th token of a specific type * * @param tokenType uint8 * @param _index uint256 * * @return uint256 */ function typedTokenByIndex( uint8 tokenType, uint256 _index ) external view returns (uint256) { return GameDataLib.typedTokenByIndex(data, tokenType, _index); } /** * @dev Gets the total number of claimed flowers * * @return uint160 */ function totalFlowers() external view returns (uint160) { return GameDataLib.totalFlowers(data); } /** * @dev Gets the address of the N-th flower * * @return address */ function getFlowerByIndex(uint160 index) external view returns (address) { return GameDataLib.getFlowerByIndex(data, index); } /** Admin setup methods */ /* * Methods intended for initial contract setup, to be called at deployment. * Call renounceOwnership() to make the contract have no owner after setup is complete. */ /** * @dev Registers a new flower URI with the corresponding weight * * @param weight uint16 Relative weight for the occurrence of this URI * @param uri string */ function addFlowerURI(uint16 weight, string uri) external onlyOwner { GameDataLib.addFlowerURI(data, weight, uri); } /** * @dev Registers the flower URI for address 0 * * @param uri string */ function setWhiteFlowerURI(string uri) external onlyOwner { GameDataLib.setWhiteFlowerURI(data, uri); } /** * @dev Registers a new butterfly URI with the corresponding weight * * @param weight uint16 Relative weight for the occurrence of this URI * @param liveUri string * @param deadUri string * @param heartUri string */ function addButterflyURI(uint16 weight, string liveUri, string deadUri, string heartUri) external onlyOwner { GameDataLib.addButterflyURI(data, weight, liveUri, deadUri, heartUri); } }
* @dev Function to burn a specific token Reverts if the token does not exist @param _owner owner of the token to burn @param _tokenId uint256 ID of the token being burned by the msg.sender/ Clear metadata (if any)
function burn(ERC721Data storage self, address _owner, uint256 _tokenId) external { _clearApproval(self, _owner, _tokenId); _removeTokenFrom(self, _owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); if (bytes(self.tokenURIs[_tokenId]).length != 0) { delete self.tokenURIs[_tokenId]; } uint256 lastTokenIndex = self.allTokens.length.sub(1); uint256 lastToken = self.allTokens[lastTokenIndex]; self.allTokens[tokenIndex] = lastToken; self.allTokens[lastTokenIndex] = 0; self.allTokens.length--; self.allTokensIndex[_tokenId] = 0; self.allTokensIndex[lastToken] = tokenIndex; }
7,284,011
[ 1, 2083, 358, 18305, 279, 2923, 1147, 868, 31537, 309, 326, 1147, 1552, 486, 1005, 225, 389, 8443, 3410, 434, 326, 1147, 358, 18305, 225, 389, 2316, 548, 2254, 5034, 1599, 434, 326, 1147, 3832, 18305, 329, 635, 326, 1234, 18, 15330, 19, 10121, 1982, 261, 430, 1281, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18305, 12, 654, 39, 27, 5340, 751, 2502, 365, 16, 1758, 389, 8443, 16, 2254, 5034, 389, 2316, 548, 13, 3903, 288, 203, 3639, 389, 8507, 23461, 12, 2890, 16, 389, 8443, 16, 389, 2316, 548, 1769, 203, 3639, 389, 4479, 1345, 1265, 12, 2890, 16, 389, 8443, 16, 389, 2316, 548, 1769, 203, 3639, 3626, 12279, 24899, 8443, 16, 1758, 12, 20, 3631, 389, 2316, 548, 1769, 203, 203, 3639, 309, 261, 3890, 12, 2890, 18, 2316, 1099, 2520, 63, 67, 2316, 548, 65, 2934, 2469, 480, 374, 13, 288, 203, 5411, 1430, 365, 18, 2316, 1099, 2520, 63, 67, 2316, 548, 15533, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 27231, 1016, 273, 365, 18, 454, 5157, 18, 2469, 18, 1717, 12, 21, 1769, 203, 3639, 2254, 5034, 27231, 273, 365, 18, 454, 5157, 63, 2722, 1345, 1016, 15533, 203, 203, 3639, 365, 18, 454, 5157, 63, 2316, 1016, 65, 273, 27231, 31, 203, 3639, 365, 18, 454, 5157, 63, 2722, 1345, 1016, 65, 273, 374, 31, 203, 203, 3639, 365, 18, 454, 5157, 18, 2469, 413, 31, 203, 3639, 365, 18, 454, 5157, 1016, 63, 67, 2316, 548, 65, 273, 374, 31, 203, 3639, 365, 18, 454, 5157, 1016, 63, 2722, 1345, 65, 273, 1147, 1016, 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 ]
// Sources flattened with hardhat v2.4.1 https://hardhat.org // File contracts/Interfaces/ERC20.sol pragma solidity ^0.8.0; interface ERC20 { function balanceOf(address) external view returns (uint256); function transfer(address, uint256) external returns (bool); function allowance(address, address) external view returns (uint256); function approve(address, uint256) external returns (bool); function transferFrom( address, address, uint256 ) external returns (bool); } // File contracts/Interfaces/Aave/StakedAave.sol pragma solidity ^0.8.4; interface StakedAave is ERC20 { function stake(address, uint256) external; function redeem(address, uint256) external; function cooldown() external; function claimRewards(address, uint256) external; function COOLDOWN_SECONDS() external view returns (uint256); } // File contracts/Interfaces/Uniswap.sol pragma solidity ^0.8.4; interface Uniswap { function swapExactETHForTokens( uint256 amountOutMin, address[] memory path, address to, uint256 deadline ) external returns (uint256[] memory); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] memory path, address to, uint256 deadline ) external returns (uint256[] memory); function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint256[] memory); function getAmountsIn(uint256 amountOut, address[] memory path) external view returns (uint256[] memory); } // File contracts/Libraries/ExchangeHelper.sol pragma solidity ^0.8.4; library ExchangeHelper { function amountOutFor( Uniswap exchange, address[] memory path, uint256 amountIn ) internal returns (uint256) { uint256[] memory amountsOut = exchange.getAmountsOut(amountIn, path); return amountsOut[amountsOut.length - 1]; } function dataForBestExchange( Uniswap a, Uniswap b, address[] memory path, uint256 amount ) internal returns (Uniswap, uint256) { Uniswap exchange; uint256 aAmount = amountOutFor(a, path, amount); uint256 bAmount = amountOutFor(b, path, amount); if (aAmount > bAmount) { return (a, aAmount); } else { return (b, bAmount); } } } // File @gnosis.pm/safe-contracts/contracts/common/[email protected] pragma solidity >=0.7.0 <0.9.0; /// @title Enum - Collection of enums /// @author Richard Meissner - <[email protected]> contract Enum { enum Operation {Call, DelegateCall} } // File @gnosis.pm/safe-contracts/contracts/common/[email protected] pragma solidity >=0.7.0 <0.9.0; /// @title SelfAuthorized - authorizes current contract to perform actions /// @author Richard Meissner - <[email protected]> contract SelfAuthorized { function requireSelfCall() private view { require(msg.sender == address(this), "GS031"); } modifier authorized() { // This is a function call as it minimized the bytecode size requireSelfCall(); _; } } // File @gnosis.pm/safe-contracts/contracts/base/[email protected] pragma solidity >=0.7.0 <0.9.0; /// @title Executor - A contract that can execute transactions /// @author Richard Meissner - <[email protected]> contract Executor { function execute( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txGas ) internal returns (bool success) { if (operation == Enum.Operation.DelegateCall) { // solhint-disable-next-line no-inline-assembly assembly { success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0) } } else { // solhint-disable-next-line no-inline-assembly assembly { success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0) } } } } // File @gnosis.pm/safe-contracts/contracts/base/[email protected] pragma solidity >=0.7.0 <0.9.0; /// @title Module Manager - A contract that manages modules that can execute transactions via this contract /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract ModuleManager is SelfAuthorized, Executor { event EnabledModule(address module); event DisabledModule(address module); event ExecutionFromModuleSuccess(address indexed module); event ExecutionFromModuleFailure(address indexed module); address internal constant SENTINEL_MODULES = address(0x1); mapping(address => address) internal modules; function setupModules(address to, bytes memory data) internal { require(modules[SENTINEL_MODULES] == address(0), "GS100"); modules[SENTINEL_MODULES] = SENTINEL_MODULES; if (to != address(0)) // Setup has to complete successfully or transaction fails. require(execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()), "GS000"); } /// @dev Allows to add a module to the whitelist. /// This can only be done via a Safe transaction. /// @notice Enables the module `module` for the Safe. /// @param module Module to be whitelisted. function enableModule(address module) public authorized { // Module address cannot be null or sentinel. require(module != address(0) && module != SENTINEL_MODULES, "GS101"); // Module cannot be added twice. require(modules[module] == address(0), "GS102"); modules[module] = modules[SENTINEL_MODULES]; modules[SENTINEL_MODULES] = module; emit EnabledModule(module); } /// @dev Allows to remove a module from the whitelist. /// This can only be done via a Safe transaction. /// @notice Disables the module `module` for the Safe. /// @param prevModule Module that pointed to the module to be removed in the linked list /// @param module Module to be removed. function disableModule(address prevModule, address module) public authorized { // Validate module address and check that it corresponds to module index. require(module != address(0) && module != SENTINEL_MODULES, "GS101"); require(modules[prevModule] == module, "GS103"); modules[prevModule] = modules[module]; modules[module] = address(0); emit DisabledModule(module); } /// @dev Allows a Module to execute a Safe transaction without any further confirmations. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModule( address to, uint256 value, bytes memory data, Enum.Operation operation ) public virtual returns (bool success) { // Only whitelisted modules are allowed. require(msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0), "GS104"); // Execute transaction without further confirmations. success = execute(to, value, data, operation, gasleft()); if (success) emit ExecutionFromModuleSuccess(msg.sender); else emit ExecutionFromModuleFailure(msg.sender); } /// @dev Allows a Module to execute a Safe transaction without any further confirmations and return data /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModuleReturnData( address to, uint256 value, bytes memory data, Enum.Operation operation ) public returns (bool success, bytes memory returnData) { success = execTransactionFromModule(to, value, data, operation); // solhint-disable-next-line no-inline-assembly assembly { // Load free memory location let ptr := mload(0x40) // We allocate memory for the return data by setting the free memory location to // current free memory location + data size + 32 bytes for data size value mstore(0x40, add(ptr, add(returndatasize(), 0x20))) // Store the size mstore(ptr, returndatasize()) // Store the data returndatacopy(add(ptr, 0x20), 0, returndatasize()) // Point the return data to the correct memory location returnData := ptr } } /// @dev Returns if an module is enabled /// @return True if the module is enabled function isModuleEnabled(address module) public view returns (bool) { return SENTINEL_MODULES != module && modules[module] != address(0); } /// @dev Returns array of modules. /// @param start Start of the page. /// @param pageSize Maximum number of modules that should be returned. /// @return array Array of modules. /// @return next Start of the next page. function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next) { // Init array with max page size array = new address[](pageSize); // Populate return array uint256 moduleCount = 0; address currentModule = modules[start]; while (currentModule != address(0x0) && currentModule != SENTINEL_MODULES && moduleCount < pageSize) { array[moduleCount] = currentModule; currentModule = modules[currentModule]; moduleCount++; } next = currentModule; // Set correct size of returned array // solhint-disable-next-line no-inline-assembly assembly { mstore(array, moduleCount) } } } // File @gnosis.pm/safe-contracts/contracts/base/[email protected] pragma solidity >=0.7.0 <0.9.0; /// @title OwnerManager - Manages a set of owners and a threshold to perform actions. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract OwnerManager is SelfAuthorized { event AddedOwner(address owner); event RemovedOwner(address owner); event ChangedThreshold(uint256 threshold); address internal constant SENTINEL_OWNERS = address(0x1); mapping(address => address) internal owners; uint256 internal ownerCount; uint256 internal threshold; /// @dev Setup function sets initial storage of contract. /// @param _owners List of Safe owners. /// @param _threshold Number of required confirmations for a Safe transaction. function setupOwners(address[] memory _owners, uint256 _threshold) internal { // Threshold can only be 0 at initialization. // Check ensures that setup function can only be called once. require(threshold == 0, "GS200"); // Validate that threshold is smaller than number of added owners. require(_threshold <= _owners.length, "GS201"); // There has to be at least one Safe owner. require(_threshold >= 1, "GS202"); // Initializing Safe owners. address currentOwner = SENTINEL_OWNERS; for (uint256 i = 0; i < _owners.length; i++) { // Owner address cannot be null. address owner = _owners[i]; require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this) && currentOwner != owner, "GS203"); // No duplicate owners allowed. require(owners[owner] == address(0), "GS204"); owners[currentOwner] = owner; currentOwner = owner; } owners[currentOwner] = SENTINEL_OWNERS; ownerCount = _owners.length; threshold = _threshold; } /// @dev Allows to add a new owner to the Safe and update the threshold at the same time. /// This can only be done via a Safe transaction. /// @notice Adds the owner `owner` to the Safe and updates the threshold to `_threshold`. /// @param owner New owner address. /// @param _threshold New threshold. function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized { // Owner address cannot be null, the sentinel or the Safe itself. require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this), "GS203"); // No duplicate owners allowed. require(owners[owner] == address(0), "GS204"); owners[owner] = owners[SENTINEL_OWNERS]; owners[SENTINEL_OWNERS] = owner; ownerCount++; emit AddedOwner(owner); // Change threshold if threshold was changed. if (threshold != _threshold) changeThreshold(_threshold); } /// @dev Allows to remove an owner from the Safe and update the threshold at the same time. /// This can only be done via a Safe transaction. /// @notice Removes the owner `owner` from the Safe and updates the threshold to `_threshold`. /// @param prevOwner Owner that pointed to the owner to be removed in the linked list /// @param owner Owner address to be removed. /// @param _threshold New threshold. function removeOwner( address prevOwner, address owner, uint256 _threshold ) public authorized { // Only allow to remove an owner, if threshold can still be reached. require(ownerCount - 1 >= _threshold, "GS201"); // Validate owner address and check that it corresponds to owner index. require(owner != address(0) && owner != SENTINEL_OWNERS, "GS203"); require(owners[prevOwner] == owner, "GS205"); owners[prevOwner] = owners[owner]; owners[owner] = address(0); ownerCount--; emit RemovedOwner(owner); // Change threshold if threshold was changed. if (threshold != _threshold) changeThreshold(_threshold); } /// @dev Allows to swap/replace an owner from the Safe with another address. /// This can only be done via a Safe transaction. /// @notice Replaces the owner `oldOwner` in the Safe with `newOwner`. /// @param prevOwner Owner that pointed to the owner to be replaced in the linked list /// @param oldOwner Owner address to be replaced. /// @param newOwner New owner address. function swapOwner( address prevOwner, address oldOwner, address newOwner ) public authorized { // Owner address cannot be null, the sentinel or the Safe itself. require(newOwner != address(0) && newOwner != SENTINEL_OWNERS && newOwner != address(this), "GS203"); // No duplicate owners allowed. require(owners[newOwner] == address(0), "GS204"); // Validate oldOwner address and check that it corresponds to owner index. require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "GS203"); require(owners[prevOwner] == oldOwner, "GS205"); owners[newOwner] = owners[oldOwner]; owners[prevOwner] = newOwner; owners[oldOwner] = address(0); emit RemovedOwner(oldOwner); emit AddedOwner(newOwner); } /// @dev Allows to update the number of required confirmations by Safe owners. /// This can only be done via a Safe transaction. /// @notice Changes the threshold of the Safe to `_threshold`. /// @param _threshold New threshold. function changeThreshold(uint256 _threshold) public authorized { // Validate that threshold is smaller than number of owners. require(_threshold <= ownerCount, "GS201"); // There has to be at least one Safe owner. require(_threshold >= 1, "GS202"); threshold = _threshold; emit ChangedThreshold(threshold); } function getThreshold() public view returns (uint256) { return threshold; } function isOwner(address owner) public view returns (bool) { return owner != SENTINEL_OWNERS && owners[owner] != address(0); } /// @dev Returns array of owners. /// @return Array of Safe owners. function getOwners() public view returns (address[] memory) { address[] memory array = new address[](ownerCount); // populate return array uint256 index = 0; address currentOwner = owners[SENTINEL_OWNERS]; while (currentOwner != SENTINEL_OWNERS) { array[index] = currentOwner; currentOwner = owners[currentOwner]; index++; } return array; } } // File @gnosis.pm/safe-contracts/contracts/base/[email protected] pragma solidity >=0.7.0 <0.9.0; /// @title Fallback Manager - A contract that manages fallback calls made to this contract /// @author Richard Meissner - <[email protected]> contract FallbackManager is SelfAuthorized { event ChangedFallbackHandler(address handler); // keccak256("fallback_manager.handler.address") bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5; function internalSetFallbackHandler(address handler) internal { bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, handler) } } /// @dev Allows to add a contract to handle fallback calls. /// Only fallback calls without value and with data will be forwarded. /// This can only be done via a Safe transaction. /// @param handler contract to handle fallbacks calls. function setFallbackHandler(address handler) public authorized { internalSetFallbackHandler(handler); emit ChangedFallbackHandler(handler); } // solhint-disable-next-line payable-fallback,no-complex-fallback fallback() external { bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { let handler := sload(slot) if iszero(handler) { return(0, 0) } calldatacopy(0, 0, calldatasize()) // The msg.sender address is shifted to the left by 12 bytes to remove the padding // Then the address without padding is stored right after the calldata mstore(calldatasize(), shl(96, caller())) // Add 20 bytes for the address appended add the end let success := call(gas(), handler, 0, 0, add(calldatasize(), 20), 0, 0) returndatacopy(0, 0, returndatasize()) if iszero(success) { revert(0, returndatasize()) } return(0, returndatasize()) } } } // File @gnosis.pm/safe-contracts/contracts/base/[email protected] pragma solidity >=0.7.0 <0.9.0; interface Guard { function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external; function checkAfterExecution(bytes32 txHash, bool success) external; } /// @title Fallback Manager - A contract that manages fallback calls made to this contract /// @author Richard Meissner - <[email protected]> contract GuardManager is SelfAuthorized { event ChangedGuard(address guard); // keccak256("guard_manager.guard.address") bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8; /// @dev Set a guard that checks transactions before execution /// @param guard The address of the guard to be used or the 0 address to disable the guard function setGuard(address guard) external authorized { bytes32 slot = GUARD_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, guard) } emit ChangedGuard(guard); } function getGuard() internal view returns (address guard) { bytes32 slot = GUARD_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { guard := sload(slot) } } } // File @gnosis.pm/safe-contracts/contracts/common/[email protected] pragma solidity >=0.7.0 <0.9.0; /// @title EtherPaymentFallback - A contract that has a fallback to accept ether payments /// @author Richard Meissner - <[email protected]> contract EtherPaymentFallback { event SafeReceived(address indexed sender, uint256 value); /// @dev Fallback function accepts Ether transactions. receive() external payable { emit SafeReceived(msg.sender, msg.value); } } // File @gnosis.pm/safe-contracts/contracts/common/[email protected] pragma solidity >=0.7.0 <0.9.0; /// @title Singleton - Base for singleton contracts (should always be first super contract) /// This contract is tightly coupled to our proxy contract (see `proxies/GnosisSafeProxy.sol`) /// @author Richard Meissner - <[email protected]> contract Singleton { // singleton always needs to be first declared variable, to ensure that it is at the same location as in the Proxy contract. // It should also always be ensured that the address is stored alone (uses a full word) address private singleton; } // File @gnosis.pm/safe-contracts/contracts/common/[email protected] pragma solidity >=0.7.0 <0.9.0; /// @title SignatureDecoder - Decodes signatures that a encoded as bytes /// @author Richard Meissner - <[email protected]> contract SignatureDecoder { /// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`. /// @notice Make sure to peform a bounds check for @param pos, to avoid out of bounds access on @param signatures /// @param pos which signature to read. A prior bounds check of this parameter should be performed, to avoid out of bounds access /// @param signatures concatenated rsv signatures function signatureSplit(bytes memory signatures, uint256 pos) internal pure returns ( uint8 v, bytes32 r, bytes32 s ) { // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. // solhint-disable-next-line no-inline-assembly assembly { let signaturePos := mul(0x41, pos) r := mload(add(signatures, add(signaturePos, 0x20))) s := mload(add(signatures, add(signaturePos, 0x40))) // Here we are loading the last 32 bytes, including 31 bytes // of 's'. There is no 'mload8' to do this. // // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff) } } } // File @gnosis.pm/safe-contracts/contracts/common/[email protected] pragma solidity >=0.7.0 <0.9.0; /// @title SecuredTokenTransfer - Secure token transfer /// @author Richard Meissner - <[email protected]> contract SecuredTokenTransfer { /// @dev Transfers a token and returns if it was a success /// @param token Token that should be transferred /// @param receiver Receiver to whom the token should be transferred /// @param amount The amount of tokens that should be transferred function transferToken( address token, address receiver, uint256 amount ) internal returns (bool transferred) { // 0xa9059cbb - keccack("transfer(address,uint256)") bytes memory data = abi.encodeWithSelector(0xa9059cbb, receiver, amount); // solhint-disable-next-line no-inline-assembly assembly { // We write the return value to scratch space. // See https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory let success := call(sub(gas(), 10000), token, 0, add(data, 0x20), mload(data), 0, 0x20) switch returndatasize() case 0 { transferred := success } case 0x20 { transferred := iszero(or(iszero(success), iszero(mload(0)))) } default { transferred := 0 } } } } // File @gnosis.pm/safe-contracts/contracts/common/[email protected] pragma solidity >=0.7.0 <0.9.0; /// @title StorageAccessible - generic base contract that allows callers to access all internal storage. /// @notice See https://github.com/gnosis/util-contracts/blob/bb5fe5fb5df6d8400998094fb1b32a178a47c3a1/contracts/StorageAccessible.sol contract StorageAccessible { /** * @dev Reads `length` bytes of storage in the currents contract * @param offset - the offset in the current contract's storage in words to start reading from * @param length - the number of words (32 bytes) of data to read * @return the bytes that were read. */ function getStorageAt(uint256 offset, uint256 length) public view returns (bytes memory) { bytes memory result = new bytes(length * 32); for (uint256 index = 0; index < length; index++) { // solhint-disable-next-line no-inline-assembly assembly { let word := sload(add(offset, index)) mstore(add(add(result, 0x20), mul(index, 0x20)), word) } } return result; } /** * @dev Performs a delegetecall on a targetContract in the context of self. * Internally reverts execution to avoid side effects (making it static). * * This method reverts with data equal to `abi.encode(bool(success), bytes(response))`. * Specifically, the `returndata` after a call to this method will be: * `success:bool || response.length:uint256 || response:bytes`. * * @param targetContract Address of the contract containing the code to execute. * @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments). */ function simulateAndRevert(address targetContract, bytes memory calldataPayload) external { // solhint-disable-next-line no-inline-assembly assembly { let success := delegatecall(gas(), targetContract, add(calldataPayload, 0x20), mload(calldataPayload), 0, 0) mstore(0x00, success) mstore(0x20, returndatasize()) returndatacopy(0x40, 0, returndatasize()) revert(0, add(returndatasize(), 0x40)) } } } // File @gnosis.pm/safe-contracts/contracts/interfaces/[email protected] pragma solidity >=0.7.0 <0.9.0; contract ISignatureValidatorConstants { // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 internal constant EIP1271_MAGIC_VALUE = 0x20c13b0b; } abstract contract ISignatureValidator is ISignatureValidatorConstants { /** * @dev Should return whether the signature provided is valid for the provided data * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * * MUST return the bytes4 magic value 0x20c13b0b when function passes. * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes memory _data, bytes memory _signature) public view virtual returns (bytes4); } // File @gnosis.pm/safe-contracts/contracts/external/[email protected] pragma solidity >=0.7.0 <0.9.0; /** * @title GnosisSafeMath * @dev Math operations with safety checks that revert on error * Renamed from SafeMath to GnosisSafeMath to avoid conflicts * TODO: remove once open zeppelin update to solc 0.5.0 */ library GnosisSafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } } // File @gnosis.pm/safe-contracts/contracts/[email protected] pragma solidity >=0.7.0 <0.9.0; /// @title Gnosis Safe - A multisignature wallet with support for confirmations using signed messages based on ERC191. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract GnosisSafe is EtherPaymentFallback, Singleton, ModuleManager, OwnerManager, SignatureDecoder, SecuredTokenTransfer, ISignatureValidatorConstants, FallbackManager, StorageAccessible, GuardManager { using GnosisSafeMath for uint256; string public constant VERSION = "1.3.0"; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 private constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "SafeTx(address to,uint256 value,bytes data,uint8 operation,uint256 safeTxGas,uint256 baseGas,uint256 gasPrice,address gasToken,address refundReceiver,uint256 nonce)" // ); bytes32 private constant SAFE_TX_TYPEHASH = 0xbb8310d486368db6bd6f849402fdd73ad53d316b5a4b2644ad6efe0f941286d8; event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler); event ApproveHash(bytes32 indexed approvedHash, address indexed owner); event SignMsg(bytes32 indexed msgHash); event ExecutionFailure(bytes32 txHash, uint256 payment); event ExecutionSuccess(bytes32 txHash, uint256 payment); uint256 public nonce; bytes32 private _deprecatedDomainSeparator; // Mapping to keep track of all message hashes that have been approve by ALL REQUIRED owners mapping(bytes32 => uint256) public signedMessages; // Mapping to keep track of all hashes (message or transaction) that have been approve by ANY owners mapping(address => mapping(bytes32 => uint256)) public approvedHashes; // This constructor ensures that this contract can only be used as a master copy for Proxy contracts constructor() { // By setting the threshold it is not possible to call setup anymore, // so we create a Safe with 0 owners and threshold 1. // This is an unusable Safe, perfect for the singleton threshold = 1; } /// @dev Setup function sets initial storage of contract. /// @param _owners List of Safe owners. /// @param _threshold Number of required confirmations for a Safe transaction. /// @param to Contract address for optional delegate call. /// @param data Data payload for optional delegate call. /// @param fallbackHandler Handler for fallback calls to this contract /// @param paymentToken Token that should be used for the payment (0 is ETH) /// @param payment Value that should be paid /// @param paymentReceiver Adddress that should receive the payment (or 0 if tx.origin) function setup( address[] calldata _owners, uint256 _threshold, address to, bytes calldata data, address fallbackHandler, address paymentToken, uint256 payment, address payable paymentReceiver ) external { // setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice setupOwners(_owners, _threshold); if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler); // As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules setupModules(to, data); if (payment > 0) { // To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself) // baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment handlePayment(payment, 0, 1, paymentToken, paymentReceiver); } emit SafeSetup(msg.sender, _owners, _threshold, to, fallbackHandler); } /// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction. /// Note: The fees are always transferred, even if the user transaction fails. /// @param to Destination address of Safe transaction. /// @param value Ether value of Safe transaction. /// @param data Data payload of Safe transaction. /// @param operation Operation type of Safe transaction. /// @param safeTxGas Gas that should be used for the Safe transaction. /// @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund) /// @param gasPrice Gas price that should be used for the payment calculation. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). /// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v}) function execTransaction( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures ) public payable virtual returns (bool success) { bytes32 txHash; // Use scope here to limit variable lifetime and prevent `stack too deep` errors { bytes memory txHashData = encodeTransactionData( // Transaction info to, value, data, operation, safeTxGas, // Payment info baseGas, gasPrice, gasToken, refundReceiver, // Signature info nonce ); // Increase nonce and execute transaction. nonce++; txHash = keccak256(txHashData); checkSignatures(txHash, txHashData, signatures); } address guard = getGuard(); { if (guard != address(0)) { Guard(guard).checkTransaction( // Transaction info to, value, data, operation, safeTxGas, // Payment info baseGas, gasPrice, gasToken, refundReceiver, // Signature info signatures, msg.sender ); } } // We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500) // We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150 require(gasleft() >= ((safeTxGas * 64) / 63).max(safeTxGas + 2500) + 500, "GS010"); // Use scope here to limit variable lifetime and prevent `stack too deep` errors { uint256 gasUsed = gasleft(); // If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than safeTxGas) // We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than safeTxGas success = execute(to, value, data, operation, gasPrice == 0 ? (gasleft() - 2500) : safeTxGas); gasUsed = gasUsed.sub(gasleft()); // If no safeTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful // This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert require(success || safeTxGas != 0 || gasPrice != 0, "GS013"); // We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls uint256 payment = 0; if (gasPrice > 0) { payment = handlePayment(gasUsed, baseGas, gasPrice, gasToken, refundReceiver); } if (success) emit ExecutionSuccess(txHash, payment); else emit ExecutionFailure(txHash, payment); } { if (guard != address(0)) { Guard(guard).checkAfterExecution(txHash, success); } } } function handlePayment( uint256 gasUsed, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver ) private returns (uint256 payment) { // solhint-disable-next-line avoid-tx-origin address payable receiver = refundReceiver == address(0) ? payable(tx.origin) : refundReceiver; if (gasToken == address(0)) { // For ETH we will only adjust the gas price to not be higher than the actual used gas price payment = gasUsed.add(baseGas).mul(gasPrice < tx.gasprice ? gasPrice : tx.gasprice); require(receiver.send(payment), "GS011"); } else { payment = gasUsed.add(baseGas).mul(gasPrice); require(transferToken(gasToken, receiver, payment), "GS012"); } } /** * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise. * @param dataHash Hash of the data (could be either a message hash or transaction hash) * @param data That should be signed (this is passed to an external validator contract) * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash. */ function checkSignatures( bytes32 dataHash, bytes memory data, bytes memory signatures ) public view { // Load threshold to avoid multiple storage loads uint256 _threshold = threshold; // Check that a threshold is set require(_threshold > 0, "GS001"); checkNSignatures(dataHash, data, signatures, _threshold); } /** * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise. * @param dataHash Hash of the data (could be either a message hash or transaction hash) * @param data That should be signed (this is passed to an external validator contract) * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash. * @param requiredSignatures Amount of required valid signatures. */ function checkNSignatures( bytes32 dataHash, bytes memory data, bytes memory signatures, uint256 requiredSignatures ) public view { // Check that the provided signature data is not too short require(signatures.length >= requiredSignatures.mul(65), "GS020"); // There cannot be an owner with address 0. address lastOwner = address(0); address currentOwner; uint8 v; bytes32 r; bytes32 s; uint256 i; for (i = 0; i < requiredSignatures; i++) { (v, r, s) = signatureSplit(signatures, i); if (v == 0) { // If v is 0 then it is a contract signature // When handling contract signatures the address of the contract is encoded into r currentOwner = address(uint160(uint256(r))); // Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes // This check is not completely accurate, since it is possible that more signatures than the threshold are send. // Here we only check that the pointer is not pointing inside the part that is being processed require(uint256(s) >= requiredSignatures.mul(65), "GS021"); // Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes) require(uint256(s).add(32) <= signatures.length, "GS022"); // Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length uint256 contractSignatureLen; // solhint-disable-next-line no-inline-assembly assembly { contractSignatureLen := mload(add(add(signatures, s), 0x20)) } require(uint256(s).add(32).add(contractSignatureLen) <= signatures.length, "GS023"); // Check signature bytes memory contractSignature; // solhint-disable-next-line no-inline-assembly assembly { // The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s contractSignature := add(add(signatures, s), 0x20) } require(ISignatureValidator(currentOwner).isValidSignature(data, contractSignature) == EIP1271_MAGIC_VALUE, "GS024"); } else if (v == 1) { // If v is 1 then it is an approved hash // When handling approved hashes the address of the approver is encoded into r currentOwner = address(uint160(uint256(r))); // Hashes are automatically approved by the sender of the message or when they have been pre-approved via a separate transaction require(msg.sender == currentOwner || approvedHashes[currentOwner][dataHash] != 0, "GS025"); } else if (v > 30) { // If v > 30 then default va (27,28) has been adjusted for eth_sign flow // To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover currentOwner = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", dataHash)), v - 4, r, s); } else { // Default is the ecrecover flow with the provided data hash // Use ecrecover with the messageHash for EOA signatures currentOwner = ecrecover(dataHash, v, r, s); } require(currentOwner > lastOwner && owners[currentOwner] != address(0) && currentOwner != SENTINEL_OWNERS, "GS026"); lastOwner = currentOwner; } } /// @dev Allows to estimate a Safe transaction. /// This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data. /// Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction` /// @param to Destination address of Safe transaction. /// @param value Ether value of Safe transaction. /// @param data Data payload of Safe transaction. /// @param operation Operation type of Safe transaction. /// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs). /// @notice Deprecated in favor of common/StorageAccessible.sol and will be removed in next version. function requiredTxGas( address to, uint256 value, bytes calldata data, Enum.Operation operation ) external returns (uint256) { uint256 startGas = gasleft(); // We don't provide an error message here, as we use it to return the estimate require(execute(to, value, data, operation, gasleft())); uint256 requiredGas = startGas - gasleft(); // Convert response to string and return via error message revert(string(abi.encodePacked(requiredGas))); } /** * @dev Marks a hash as approved. This can be used to validate a hash that is used by a signature. * @param hashToApprove The hash that should be marked as approved for signatures that are verified by this contract. */ function approveHash(bytes32 hashToApprove) external { require(owners[msg.sender] != address(0), "GS030"); approvedHashes[msg.sender][hashToApprove] = 1; emit ApproveHash(hashToApprove, msg.sender); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solhint-disable-next-line no-inline-assembly assembly { id := chainid() } return id; } function domainSeparator() public view returns (bytes32) { return keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, getChainId(), this)); } /// @dev Returns the bytes that are hashed to be signed by owners. /// @param to Destination address. /// @param value Ether value. /// @param data Data payload. /// @param operation Operation type. /// @param safeTxGas Gas that should be used for the safe transaction. /// @param baseGas Gas costs for that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund) /// @param gasPrice Maximum gas price that should be used for this transaction. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). /// @param _nonce Transaction nonce. /// @return Transaction hash bytes. function encodeTransactionData( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce ) public view returns (bytes memory) { bytes32 safeTxHash = keccak256( abi.encode( SAFE_TX_TYPEHASH, to, value, keccak256(data), operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce ) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash); } /// @dev Returns hash to be signed by owners. /// @param to Destination address. /// @param value Ether value. /// @param data Data payload. /// @param operation Operation type. /// @param safeTxGas Fas that should be used for the safe transaction. /// @param baseGas Gas costs for data used to trigger the safe transaction. /// @param gasPrice Maximum gas price that should be used for this transaction. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). /// @param _nonce Transaction nonce. /// @return Transaction hash. function getTransactionHash( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce ) public view returns (bytes32) { return keccak256(encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce)); } } // File contracts/Libraries/SafeHelper.sol pragma solidity ^0.8.4; library SafeHelper { function approve( GnosisSafe safe, ERC20 token, address spender, uint256 amount ) internal { execute( safe, address(token), abi.encodeWithSelector(token.approve.selector, spender, amount) ); } function execute( GnosisSafe safe, address to, bytes memory data ) internal { require( safe.execTransactionFromModule(to, 0, data, Enum.Operation.Call), "could not execute" ); } function swapExactTokensForTokens( GnosisSafe safe, Uniswap exchange, uint256 amountIn, uint256 amountOutMin, address[] memory path, address to, uint256 deadline ) internal returns (uint256[] memory) { (bool success, bytes memory data) = safe.execTransactionFromModuleReturnData( address(exchange), 0, abi.encodeWithSelector( exchange.swapExactTokensForTokens.selector, amountIn, amountOutMin, path, to, deadline ), Enum.Operation.Call ); require(success); return abi.decode(data, (uint256[])); } } // File contracts/Modules/Module.sol pragma solidity ^0.8.4; abstract contract Module { /// The executors for the safe. mapping(address => address) executors; modifier onlyExecutor(GnosisSafe safe) { require( executors[address(safe)] == msg.sender || safe.isOwner(msg.sender), "Sender is not harvester" ); _; } function addExecutor(address executor) external { require(executors[msg.sender] == address(0x0), "harvester already set"); executors[msg.sender] = executor; } function removeExecutor() external { executors[msg.sender] = address(0x0); } } // File contracts/Interfaces/Aave/StakedTokenIncentivesController.sol pragma solidity ^0.8.4; interface StakedTokenIncentivesController { function claimRewards( address[] calldata assets, uint256 amount, address to ) external; function getRewardsBalance(address[] calldata, address) external view returns (uint256); function getUserUnclaimedRewards(address) external view returns (uint256); } // File contracts/Interfaces/Aave/LendingPool.sol pragma solidity ^0.8.4; interface LendingPool { function deposit( address, uint256, address, uint16 ) external; function getUserAccountData(address) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); } // File contracts/Modules/AaveHarvester.sol pragma solidity ^0.8.4; contract AaveHarvester is Module { using ExchangeHelper for Uniswap; using SafeHelper for GnosisSafe; string public constant NAME = "Aave Harvester Module"; string public constant VERSION = "0.1.0"; StakedAave public constant stakedAave = StakedAave(0x4da27a545c0c5B758a6BA100e3a049001de870f5); StakedTokenIncentivesController public constant incentives = StakedTokenIncentivesController(0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5); LendingPool public constant lendingPool = LendingPool(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); ERC20 public constant usdc = ERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); ERC20 public constant aave = ERC20(0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9); ERC20 public constant weth = ERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); Uniswap public constant uni = Uniswap(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); Uniswap public constant sushi = Uniswap(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); address[] public path = [address(aave), address(weth), address(usdc)]; function activateCooldown(GnosisSafe safe, address[] calldata assets) external onlyExecutor(safe) { // Claim the rewards safe.execute( address(incentives), abi.encodeWithSelector( incentives.claimRewards.selector, assets, incentives.getRewardsBalance(assets, address(safe)), address(safe) ) ); // Cooldown the rewards so we can harvest safe.execute( address(stakedAave), abi.encodeWithSelector(stakedAave.cooldown.selector) ); } function harvest(GnosisSafe safe) external onlyExecutor(safe) { uint256 stakeBalance = stakedAave.balanceOf(address(safe)); // Redeem Aave Tokens safe.execute( address(stakedAave), abi.encodeWithSelector( stakedAave.redeem.selector, address(safe), stakeBalance ) ); uint256 balance = aave.balanceOf(address(safe)); // Check for best price (Uniswap exchange, uint256 amount) = ExchangeHelper.dataForBestExchange( uni, sushi, path, balance ); // Approve Aave on best exchange safe.approve(aave, address(exchange), balance); // Trade uint256[] memory balances = safe.swapExactTokensForTokens( exchange, balance, (amount * 980) / 1000, path, address(safe), block.timestamp + 180 ); uint256 usdcBalance = balances[2]; // Approve USDC for aave safe.approve(usdc, address(lendingPool), usdcBalance); // Deposit safe.execute( address(lendingPool), abi.encodeWithSelector( lendingPool.deposit.selector, address(usdc), usdcBalance, address(safe), 0 ) ); } }
Claim the rewards Cooldown the rewards so we can harvest
{ safe.execute( address(incentives), abi.encodeWithSelector( incentives.claimRewards.selector, assets, incentives.getRewardsBalance(assets, address(safe)), address(safe) ) ); safe.execute( address(stakedAave), abi.encodeWithSelector(stakedAave.cooldown.selector) ); }
12,227,421
[ 1, 9762, 326, 283, 6397, 385, 1371, 2378, 326, 283, 6397, 1427, 732, 848, 17895, 26923, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 288, 203, 3639, 4183, 18, 8837, 12, 203, 5411, 1758, 12, 267, 2998, 3606, 3631, 203, 5411, 24126, 18, 3015, 1190, 4320, 12, 203, 7734, 316, 2998, 3606, 18, 14784, 17631, 14727, 18, 9663, 16, 203, 7734, 7176, 16, 203, 7734, 316, 2998, 3606, 18, 588, 17631, 14727, 13937, 12, 9971, 16, 1758, 12, 4626, 13, 3631, 203, 7734, 1758, 12, 4626, 13, 203, 5411, 262, 203, 3639, 11272, 203, 203, 3639, 4183, 18, 8837, 12, 203, 5411, 1758, 12, 334, 9477, 37, 836, 3631, 203, 5411, 24126, 18, 3015, 1190, 4320, 12, 334, 9477, 37, 836, 18, 71, 1371, 2378, 18, 9663, 13, 203, 3639, 11272, 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 ]
./partial_match/80001/0x062292e464fc5A7dC1D00CC5dd214bC0efB65a1C/sources/Users/famousbirthdays/Sites/mb-contracts/contracts/MetaBoards.sol
* @notice Callback function used by VRF Coordinator @dev Important! Add a modifier to only allow this function to be called by the VRFCoordinator @dev The VRF Coordinator will only send this function verified responses. @dev The VRF Coordinator will not pass randomness that could not be verified. @dev Get a number between 2 and 12, and run the roll logic/ uint256[] storage dice = new uint256[](2); dice[0] = _die1; dice[1] = _die2; delete playerInfo[_player].lastDice;
function fulfillRandomWords( uint256 requestId, uint256[] memory randomWords ) internal override { uint256 _die1 = randomWords[0]%6 + 1; uint256 _die2 = randomWords[1]%6 + 1; address _player = rollQueue[requestId]; _doRoll(_die1,_die2,payable(_player)); } uint256 _roll = randomness%11 + 2; address _player = rollQueue[requestId]; _doRoll(_roll,payable(_player));
8,804,576
[ 1, 2428, 445, 1399, 635, 776, 12918, 10320, 4240, 225, 6164, 970, 5, 1436, 279, 9606, 358, 1338, 1699, 333, 445, 358, 506, 2566, 635, 326, 776, 12918, 25307, 225, 1021, 776, 12918, 10320, 4240, 903, 1338, 1366, 333, 445, 13808, 7220, 18, 225, 1021, 776, 12918, 10320, 4240, 903, 486, 1342, 2744, 4496, 716, 3377, 486, 506, 13808, 18, 225, 968, 279, 1300, 3086, 576, 471, 2593, 16, 471, 1086, 326, 5824, 4058, 19, 2254, 5034, 8526, 2502, 302, 1812, 273, 394, 2254, 5034, 8526, 12, 22, 1769, 302, 1812, 63, 20, 65, 273, 389, 72, 1385, 21, 31, 302, 1812, 63, 21, 65, 273, 389, 72, 1385, 22, 31, 1430, 7291, 966, 63, 67, 14872, 8009, 2722, 40, 1812, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 1377, 445, 22290, 8529, 7363, 12, 203, 3639, 2254, 5034, 14459, 16, 203, 3639, 2254, 5034, 8526, 3778, 2744, 7363, 203, 1377, 262, 2713, 3849, 288, 203, 203, 3639, 2254, 5034, 389, 72, 1385, 21, 273, 2744, 7363, 63, 20, 65, 9, 26, 397, 404, 31, 203, 3639, 2254, 5034, 389, 72, 1385, 22, 273, 2744, 7363, 63, 21, 65, 9, 26, 397, 404, 31, 203, 203, 3639, 1758, 389, 14872, 273, 5824, 3183, 63, 2293, 548, 15533, 203, 203, 540, 203, 203, 3639, 389, 2896, 24194, 24899, 72, 1385, 21, 16, 67, 72, 1385, 22, 16, 10239, 429, 24899, 14872, 10019, 203, 203, 1377, 289, 203, 5411, 2254, 5034, 389, 2693, 273, 2744, 4496, 9, 2499, 397, 576, 31, 203, 5411, 1758, 389, 14872, 273, 5824, 3183, 63, 2293, 548, 15533, 203, 2398, 203, 5411, 389, 2896, 24194, 24899, 2693, 16, 10239, 429, 24899, 14872, 10019, 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 ]
./partial_match/1/0x3374988227c650B062D04Be94f5e0B1bCE2d6A3b/sources/ChinesePepe.sol
Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amountblacklist store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract ChinesePepe is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address public marketingWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public transferDelayEnabled = true; uint256 public totalSellFees; uint256 public marketingSellFee; uint256 public liquiditySellFee; uint256 public totalBuyFees; uint256 public marketingBuyFee; uint256 public liquidityBuyFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; bool public blacklistStatus; mapping (address => bool) public isBlacklisted; mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded); event ExcludedMaxTransactionAmount(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event taxMultiplierActive(uint256 duration); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); constructor() ERC20("ChinesePepe","CNPEPE") { address newOwner = address(0x1465C995fAf82D1658d7833486D6c1B1d9fB105b); uint256 totalSupply = 420689899999998 * 10**18; maxTransactionAmount = totalSupply * 2 / 100; swapTokensAtAmount = totalSupply / 1000; maxWallet = totalSupply * 6 / 100; marketingSellFee = 27; liquiditySellFee = 3; totalSellFees = marketingSellFee + liquiditySellFee; marketingBuyFee = 17; liquidityBuyFee = 3; totalBuyFees = marketingBuyFee + liquidityBuyFee; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); excludeFromFees(newOwner, true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(newOwner, true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(_uniswapV2Router), true); excludeFromMaxTransaction(address(0xdead), true); createInitialSupply is a function that is only called here, and CANNOT be called ever again createInitialSupply(newOwner, totalSupply); transferOwnership(newOwner); } receive() external payable { } function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function setBlacklistStatus(bool newValue) external onlyOwner() { require(blacklistStatus != newValue, "Blacklist mode is already enabled"); blacklistStatus = newValue; } function setBlacklisted(address account, bool newValue) external onlyOwner() { require(newValue != isBlacklisted[account], "Wallet is blacklisted already"); isBlacklisted[account] = newValue; } function massSetBlacklisted(address[] memory accounts, bool newValue) external onlyOwner() { for(uint256 i; i < accounts.length; i++) { require(newValue != isBlacklisted[accounts[i]], "Some of the values are already set as Blacklisted"); isBlacklisted[accounts[i]] = newValue; } } function massSetBlacklisted(address[] memory accounts, bool newValue) external onlyOwner() { for(uint256 i; i < accounts.length; i++) { require(newValue != isBlacklisted[accounts[i]], "Some of the values are already set as Blacklisted"); isBlacklisted[accounts[i]] = newValue; } } function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; tradingActiveBlock = block.number; } function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateMaxAmount(uint256 newNum) external onlyOwner { require(newNum > (totalSupply() * 1 / 200)/1e18, "Cannot set maxTransactionAmount lower than 0,5%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum > (totalSupply() * 1 / 100)/1e18, "Cannot set maxWallet lower than 1%"); maxWallet = newNum * (10**18); } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee) external onlyOwner { marketingBuyFee = _marketingFee; liquidityBuyFee = _liquidityFee; totalBuyFees = marketingBuyFee + liquidityBuyFee; require(totalBuyFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee) external onlyOwner { marketingSellFee = _marketingFee; liquiditySellFee = _liquidityFee; totalSellFees = marketingSellFee + liquiditySellFee; require(totalSellFees <= 20, "Must keep fees at 20% or less"); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; emit ExcludedMaxTransactionAmount(updAds, isEx); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The UniSwap pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; excludeFromMaxTransaction(pair, value); emit SetAutomatedMarketMakerPair(pair, value); } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; transferDelayEnabled = false; return true; } 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(!blacklistStatus || (!isBlacklisted[from] && !isBlacklisted[to]), "Blacklisted!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && totalSellFees > 0){ fees = amount.mul(totalSellFees).div(100); tokensForLiquidity += fees * liquiditySellFee / totalSellFees; tokensForMarketing += fees * marketingSellFee / totalSellFees; } else if(automatedMarketMakerPairs[from] && totalBuyFees > 0) { fees = amount.mul(totalBuyFees).div(100); tokensForLiquidity += fees * liquidityBuyFee / totalBuyFees; tokensForMarketing += fees * marketingBuyFee / totalBuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklistStatus || (!isBlacklisted[from] && !isBlacklisted[to]), "Blacklisted!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && totalSellFees > 0){ fees = amount.mul(totalSellFees).div(100); tokensForLiquidity += fees * liquiditySellFee / totalSellFees; tokensForMarketing += fees * marketingSellFee / totalSellFees; } else if(automatedMarketMakerPairs[from] && totalBuyFees > 0) { fees = amount.mul(totalBuyFees).div(100); tokensForLiquidity += fees * liquidityBuyFee / totalBuyFees; tokensForMarketing += fees * marketingBuyFee / totalBuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklistStatus || (!isBlacklisted[from] && !isBlacklisted[to]), "Blacklisted!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && totalSellFees > 0){ fees = amount.mul(totalSellFees).div(100); tokensForLiquidity += fees * liquiditySellFee / totalSellFees; tokensForMarketing += fees * marketingSellFee / totalSellFees; } else if(automatedMarketMakerPairs[from] && totalBuyFees > 0) { fees = amount.mul(totalBuyFees).div(100); tokensForLiquidity += fees * liquidityBuyFee / totalBuyFees; tokensForMarketing += fees * marketingBuyFee / totalBuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklistStatus || (!isBlacklisted[from] && !isBlacklisted[to]), "Blacklisted!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && totalSellFees > 0){ fees = amount.mul(totalSellFees).div(100); tokensForLiquidity += fees * liquiditySellFee / totalSellFees; tokensForMarketing += fees * marketingSellFee / totalSellFees; } else if(automatedMarketMakerPairs[from] && totalBuyFees > 0) { fees = amount.mul(totalBuyFees).div(100); tokensForLiquidity += fees * liquidityBuyFee / totalBuyFees; tokensForMarketing += fees * marketingBuyFee / totalBuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklistStatus || (!isBlacklisted[from] && !isBlacklisted[to]), "Blacklisted!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && totalSellFees > 0){ fees = amount.mul(totalSellFees).div(100); tokensForLiquidity += fees * liquiditySellFee / totalSellFees; tokensForMarketing += fees * marketingSellFee / totalSellFees; } else if(automatedMarketMakerPairs[from] && totalBuyFees > 0) { fees = amount.mul(totalBuyFees).div(100); tokensForLiquidity += fees * liquidityBuyFee / totalBuyFees; tokensForMarketing += fees * marketingBuyFee / totalBuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklistStatus || (!isBlacklisted[from] && !isBlacklisted[to]), "Blacklisted!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && totalSellFees > 0){ fees = amount.mul(totalSellFees).div(100); tokensForLiquidity += fees * liquiditySellFee / totalSellFees; tokensForMarketing += fees * marketingSellFee / totalSellFees; } else if(automatedMarketMakerPairs[from] && totalBuyFees > 0) { fees = amount.mul(totalBuyFees).div(100); tokensForLiquidity += fees * liquidityBuyFee / totalBuyFees; tokensForMarketing += fees * marketingBuyFee / totalBuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklistStatus || (!isBlacklisted[from] && !isBlacklisted[to]), "Blacklisted!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && totalSellFees > 0){ fees = amount.mul(totalSellFees).div(100); tokensForLiquidity += fees * liquiditySellFee / totalSellFees; tokensForMarketing += fees * marketingSellFee / totalSellFees; } else if(automatedMarketMakerPairs[from] && totalBuyFees > 0) { fees = amount.mul(totalBuyFees).div(100); tokensForLiquidity += fees * liquidityBuyFee / totalBuyFees; tokensForMarketing += fees * marketingBuyFee / totalBuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklistStatus || (!isBlacklisted[from] && !isBlacklisted[to]), "Blacklisted!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && totalSellFees > 0){ fees = amount.mul(totalSellFees).div(100); tokensForLiquidity += fees * liquiditySellFee / totalSellFees; tokensForMarketing += fees * marketingSellFee / totalSellFees; } else if(automatedMarketMakerPairs[from] && totalBuyFees > 0) { fees = amount.mul(totalBuyFees).div(100); tokensForLiquidity += fees * liquidityBuyFee / totalBuyFees; tokensForMarketing += fees * marketingBuyFee / totalBuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklistStatus || (!isBlacklisted[from] && !isBlacklisted[to]), "Blacklisted!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && totalSellFees > 0){ fees = amount.mul(totalSellFees).div(100); tokensForLiquidity += fees * liquiditySellFee / totalSellFees; tokensForMarketing += fees * marketingSellFee / totalSellFees; } else if(automatedMarketMakerPairs[from] && totalBuyFees > 0) { fees = amount.mul(totalBuyFees).div(100); tokensForLiquidity += fees * liquidityBuyFee / totalBuyFees; tokensForMarketing += fees * marketingBuyFee / totalBuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklistStatus || (!isBlacklisted[from] && !isBlacklisted[to]), "Blacklisted!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && totalSellFees > 0){ fees = amount.mul(totalSellFees).div(100); tokensForLiquidity += fees * liquiditySellFee / totalSellFees; tokensForMarketing += fees * marketingSellFee / totalSellFees; } else if(automatedMarketMakerPairs[from] && totalBuyFees > 0) { fees = amount.mul(totalBuyFees).div(100); tokensForLiquidity += fees * liquidityBuyFee / totalBuyFees; tokensForMarketing += fees * marketingBuyFee / totalBuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklistStatus || (!isBlacklisted[from] && !isBlacklisted[to]), "Blacklisted!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && totalSellFees > 0){ fees = amount.mul(totalSellFees).div(100); tokensForLiquidity += fees * liquiditySellFee / totalSellFees; tokensForMarketing += fees * marketingSellFee / totalSellFees; } else if(automatedMarketMakerPairs[from] && totalBuyFees > 0) { fees = amount.mul(totalBuyFees).div(100); tokensForLiquidity += fees * liquidityBuyFee / totalBuyFees; tokensForMarketing += fees * marketingBuyFee / totalBuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklistStatus || (!isBlacklisted[from] && !isBlacklisted[to]), "Blacklisted!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && totalSellFees > 0){ fees = amount.mul(totalSellFees).div(100); tokensForLiquidity += fees * liquiditySellFee / totalSellFees; tokensForMarketing += fees * marketingSellFee / totalSellFees; } else if(automatedMarketMakerPairs[from] && totalBuyFees > 0) { fees = amount.mul(totalBuyFees).div(100); tokensForLiquidity += fees * liquidityBuyFee / totalBuyFees; tokensForMarketing += fees * marketingBuyFee / totalBuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklistStatus || (!isBlacklisted[from] && !isBlacklisted[to]), "Blacklisted!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && totalSellFees > 0){ fees = amount.mul(totalSellFees).div(100); tokensForLiquidity += fees * liquiditySellFee / totalSellFees; tokensForMarketing += fees * marketingSellFee / totalSellFees; } else if(automatedMarketMakerPairs[from] && totalBuyFees > 0) { fees = amount.mul(totalBuyFees).div(100); tokensForLiquidity += fees * liquidityBuyFee / totalBuyFees; tokensForMarketing += fees * marketingBuyFee / totalBuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklistStatus || (!isBlacklisted[from] && !isBlacklisted[to]), "Blacklisted!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && totalSellFees > 0){ fees = amount.mul(totalSellFees).div(100); tokensForLiquidity += fees * liquiditySellFee / totalSellFees; tokensForMarketing += fees * marketingSellFee / totalSellFees; } else if(automatedMarketMakerPairs[from] && totalBuyFees > 0) { fees = amount.mul(totalBuyFees).div(100); tokensForLiquidity += fees * liquidityBuyFee / totalBuyFees; tokensForMarketing += fees * marketingBuyFee / totalBuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklistStatus || (!isBlacklisted[from] && !isBlacklisted[to]), "Blacklisted!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && totalSellFees > 0){ fees = amount.mul(totalSellFees).div(100); tokensForLiquidity += fees * liquiditySellFee / totalSellFees; tokensForMarketing += fees * marketingSellFee / totalSellFees; } else if(automatedMarketMakerPairs[from] && totalBuyFees > 0) { fees = amount.mul(totalBuyFees).div(100); tokensForLiquidity += fees * liquidityBuyFee / totalBuyFees; tokensForMarketing += fees * marketingBuyFee / totalBuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklistStatus || (!isBlacklisted[from] && !isBlacklisted[to]), "Blacklisted!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Unable to exceed Max Wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && totalSellFees > 0){ fees = amount.mul(totalSellFees).div(100); tokensForLiquidity += fees * liquiditySellFee / totalSellFees; tokensForMarketing += fees * marketingSellFee / totalSellFees; } else if(automatedMarketMakerPairs[from] && totalBuyFees > 0) { fees = amount.mul(totalBuyFees).div(100); tokensForLiquidity += fees * liquidityBuyFee / totalBuyFees; tokensForMarketing += fees * marketingBuyFee / totalBuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, address(0x1465C995fAf82D1658d7833486D6c1B1d9fB105b), block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); bool success; uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing; uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing; tokensForLiquidity = 0; tokensForMarketing = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} function swapBack() private { uint256 contractBalance = balanceOf(address(this)); bool success; uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing; uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing; tokensForLiquidity = 0; tokensForMarketing = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } (success,) = address(marketingWallet).call{value: ethForMarketing}(""); function marketingTokens(uint256 ethAmountInWei) external onlyOwner { address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); path, address(0xdead), block.timestamp ); } uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: ethAmountInWei}( function withdrawStuckEth() external onlyOwner { require(success, "failed to withdraw"); } (bool success,) = address(msg.sender).call{value: address(this).balance}(""); }
4,447,361
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 431, 17704, 1317, 628, 1656, 281, 471, 943, 2492, 3844, 22491, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 1680, 25331, 11227, 347, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 203, 565, 1758, 1071, 13667, 310, 16936, 31, 203, 540, 203, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 377, 203, 377, 203, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 377, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 377, 203, 377, 203, 565, 2254, 5034, 1071, 2078, 55, 1165, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 13667, 310, 55, 1165, 14667, 31, 203, 565, 2254, 5034, 1071, 4501, 372, 24237, 55, 1165, 14667, 31, 203, 377, 203, 565, 2254, 5034, 1071, 2078, 38, 9835, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 13667, 310, 38, 9835, 14667, 31, 203, 565, 2254, 5034, 1071, 4501, 372, 24237, 38, 9835, 14667, 31, 203, 377, 203, 565, 2254, 5034, 1071, 2430, 1290, 3882, 21747, 31, 203, 565, 2254, 5034, 1071, 2430, 1290, 48, 18988, 24237, 31, 203, 203, 203, 203, 565, 2874, 261, 2867, 516, 1426, 2 ]